Disabling form input in LiveView (form helper question)

phoenix
liveview
#1

Hello, I am building multiplayer forms with LiveView.

I want to disable the input when it’s selected by another user.

Here’s what I got (will explain why it doesn’t work)

= text_input :post, :name, value: @value, phx_focus: “user_focus”, phx_keyup: “user_keyup”, phx_blur: “user_blur”, class: “form-input big-input”, autocomplete: “off”, disabled: @disabled

value: @value works perfectly with LiveView, but disabled: @disabled doesn’t work, this is because in html value=“blah blah blah” sets the value, but disabled=“true” is still disabled. disabled=“true” and disabled=“false” are the same thing, the input is disabled just with the presence of the word disabled.

Anyone have a way around this to just manipulate the key “e.g. disabled: part” with LiveView and not just value.

#2

Hi,

The last element to text_input is a keyword list, so basically:

value: @value , phx_focus: “user_focus”, phx_keyup: “user_keyup”, phx_blur: “user_blur”, class: “form-input big-input”, autocomplete: “off”, disabled: @disabled

is the same as [{: value, @value}, {:phx_focus, “user_focus”}, {:phx_keyup, “user_keyup”}, {:phx_blur, “user_blur”}, {:class, “form-input big-input”}, {:autocomplete, “off”}, {:disabled, @disabled}]

With this you can create a helper function that takes the usual list, plus @disabled and adds it to the list if it’s true or doesn’t if it’s not.

defmodule MyHelpers.Attrs do
  @spec maybe_disable(boolean, list) :: list
  def maybe_disable(true, attrs_list), do: [{:disabled, 1} | attrs_list]
  def maybe_disable(_, attrs_list), do: attrs_list
end
iex(1)> MyHelpers.Attrs.maybe_disable(true, [test: 1, test_2: 2])
[disabled: 1, test: 1, test_2: 2]
iex(2)> MyHelpers.Attrs.maybe_disable(false, [test: 1, test_2: 2])
[test: 1, test_2: 2]

3 Likes
#3

Thanks for this, let me make sure I am understanding correctly.

Do I use the helper function in the LiveView event handler to pass a new input element over the socket?

I was hoping just to delete or add the word “disabled” into the input somehow through the assigns in the socket.

#4

I was thinking of using it the form itself

Like:

= text_input :post, :name, MyHelpers.Attrs(@disabled, [value: @value, phx_focus: “user_focus”, phx_keyup: “user_keyup”, phx_blur: “user_blur”, class: “form-input big-input”, autocomplete: “off”])
2 Likes
#5

Got it. Getting an error: syntax error before: '('