2

I have created this simple form which I handle in my LiveView component. What is the communities best practice for clearing / resetting my form after I submit this?

I do want to take validations etc. into account. Is this then always via an Ecto.Changeset, even when no schema is backing a form directly?

  def handle_event("add", %{"text" => text}, socket) do
    IO.inspect(text)
    {:noreply, socket}
  end

  def render(assigns) do
    ~H"""
    <form phx-submit="add">
      <input type="text" name="text" placeholder="What needs to be done?" autofocus>
      <input type="submit" />
    </form>
    """
  end
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
Hoetmaaiers
  • 3,413
  • 2
  • 19
  • 29
  • After submitting the form successfully, you should direct the user to another page or view such that the UX provides feedback to the user that they did everything correctly for their form submission. With this method, you don't need to worry about resetting the form because when the user navigates back to create something new with the form, it will be blank as the first time. – DogEatDog Jan 08 '22 at 16:30
  • Hm, is that way of thinking also valid when thinking of an interactive application like a SPA or LiveView in this case? To add on that, this is a TodoMVC example app, so the page is both adding a todo and showing the list of all todos (also the newly created ones). – Hoetmaaiers Jan 08 '22 at 19:08
  • When generating a new Phoenix Project and using the LiveView Generators, creating new records with `new` or `edit` renders a modal dialog form to create or update the record. The User can remain on the page after creating the record. I'm not sure why this wouldn't work for your use case. – DogEatDog Jan 10 '22 at 14:22

2 Answers2

0

LiveView should automatically reset the input field once it is submitted, but that might be an Ecto only thing. You can also write a JS hook for this if you want to clear the input. It's pretty simple.

You can always redirect the user somewhere with a flash message for better UX.

Allyedge
  • 45
  • 2
  • 6
0

If you want validation, using a changeset (Ecto) can give all lot of fire power. And <.form> will handle automagically!

thelastinuit
  • 311
  • 1
  • 5
  • 9