Prevent form clearing on url patch


I have a page with two tabs, and when I change tabs, the form on the first tab clears.

The tabs have been implemented by using the url to determine which tab is active. I use a .link with patch=... to change tabs. The active tab just applies CSS rules to show/hide the relevant content.

When navigating, the form clears. Is there any way to prevent this, or is there a better approach to get this working?


Are you updating it on change? Usually this is done via a “validate” event:

<.simple_form for={@form} phx-change="validate" ...>
def handle_event("validate", %{"my_schema" => my_schema_params}, socket) do
  changeset =
    |> SchemaContext.change_my_schema(my_schema_params)
    |> struct!(action: :validate)

  {:noreply, assign(socket, form: to_form(changeset))}

Otherwise the server knows nothing of your form’s state so it gets blown away.

When the user click on the tab that does not have the form, does the form still exist in the DOM? If not, when the user click back the form has to be re-rendered. If the form exists in the DOM, just hidden, then form data should be there.

1 Like

Ya, I was imagining you had something like this in your routes:

live ThingLive, :tab_one
live ThingLive, :tab_two
def render(assigns) when assigns.live_action == :tab_one do # ...
def render(assigns) when assigns.live_action == :tab_two do # ...

Otherwise, what @derek-zhou said and you won’t need the validate stuff (unless of course you want live validation).

Thanks for the responses, I figured it out, and it was a bit silly.

In my liveview, I was setting up the form component in handle_params, and that was resetting the form when patching.