Fields of form disappearing after live view reload

Hi,
I’m currently struggling with a problem mentioned in the title. I’m using Live View 0.1.0, Phoenix 1.4.9 and Elixir 1.9.0. I’ve got a form, which is used to filter a table. After submitting there is an event sent to the hande_event function. Although filtering after submitting works fine (query is good, parameters of submitted form are sent to the backend and it responds with correct results) it clears all fields of my form, which is no-go for me. Is there any way I can keep values of fields after submitting?

There is form partial:

<form action="#" phx-submit="search" id="search-form">

<%= label :city, gettext("City") %>

<%= text_input :params, :city, id: "city" %>

<%= label :street, gettext("Street") %>

<%= text_input :params, :street, id: "street" %>

<%= label :title, gettext("Title") %>

<%= text_input :params, :title, id: "title" %>

... many other params ...

<%= submit gettext("Search"), phx_disable_with: gettext("Searching...") %>

</form>

Handle event function:

def handle_event("search", %{"params" => params}, socket) do
    members = Context.get_members(params)
    {:noreply, assign(socket, members: members)}
  end

Your form inputs aren’t referencing any value, so when they are re-rendered they aren’t populated with a value. It’s for this reason that I basically always use changesets for my live view forms since it makes it easy to get the correct state on the form fields. If you wish to do it manually you can, you’ll want to do something like text_input :params, :city, id: "city", value: @form_state.city. Then on search-form submit you need to set form_state based on the submitted form values.

6 Likes