LiveView validation of a form with a Trix editor field

Hi there,

I have added a Trix editor (2.0.4) field into a LiveView form (Phoenix 1.7.0). My problem is that the form’s phx-change event handler receives the previous value of the editor contents not the current one:

<.simple_form for={@form} id="ticket-form" phx-change="validate" phx-submit="save">
  <.input field={@form[:subject]} type="text" label="Subject" />
  <input
    type="hidden"
    name={@form[:description].name}
    id={@form[:description].id}
    value={@form[:description].value}
    />
  <div id={"ignore-#{@form[:description].id}"} phx-update="ignore">
    <trix-editor input={@form[:description].id} class="trix-content"></trix-editor>
  </div>
  <:actions>
    <.button phx-disable-with="Saving...">Save Ticket</.button>
  </:actions>
</.simple_form>

An example:

  1. the field originally contains the value 123
  2. I append 4 to it
  3. the hidden input field correctly updated with the value 1234
  4. phx-change handler receives the value 123

If I replace trix-editor with a textarea and not change anything else then it works perfectly:

<.simple_form for={@form} id="ticket-form" phx-change="validate" phx-submit="save">
  <.input field={@form[:subject]} type="text" label="Subject" />
  <textarea name={@form[:description].name} id={@form[:description].id}>
    <%= @form[:description].value %>
  </textarea>
  <:actions>
    <.button phx-disable-with="Saving...">Save Ticket</.button>
  </:actions>
</.simple_form>

Any idea?

Thx

1 Like

I have the same problem.
Did you solve it?

That’s odd, my guess is that there’s some disconnect between how Trix updates the hidden field and how LiveView detects form changes. If you subsequently append a 5 to 1234, then does the phx-change event handler then receive the value 1234?

It might be worth trying to manually pass the contents of the Trix editor input to the hidden input field using a LiveView hook that listens for the trix-change event.

Observing Editor Changes

The <trix-editor> element emits several events which you can use to observe and respond to changes in editor state.

  • trix-change fires whenever the editor’s contents have changed.

source: GitHub - basecamp/trix: A rich text editor for everyday writing

1 Like