Hi,
I’m tring to create a form inside a live view that allows the user to dynamically add associated items to an Ecto schema. My schemas look a little like this:
defmodule Post do
schema "posts" do
field :topic, :string
has_many :comments, Comment
end
end
defmodule Post do
schema "posts" do
field :content, :string
belongs_to :post, Post
end
end
I want to createa a form that allows a user to create a Post and 1 or more Comments at the same time. This looks a little like:
<.form phx-submit="save" ...>
<!-- post form here -->
<%= inputs_for ... %><!-- comment for here --><% end %>
</.form>
Underneath the comment forms is an add button, when the user clicks that a new comment is added to the form. This is handled through phx-click and on the server an event handler simply adds a new empty %Comment{} to the changeset data and rerenders the form. Similarly, all the comments have a delete button, that removes the specified comment and rerenders.
This all works fine, except for one important detail. When the user fills out the Post form and than clicks the “Add comment” button, without submitting the form, a new empty comment is added. However, since this is handled through phx-click, the form is never submitted and the changeset is never updated. So on rerendering the previously filled out form is now empty again.
I understand why this is happenign, I just don’t understand how to fix this. I have tried a couple things.
First I tried looking for a way to submit the entire form with the phx-click, in that case I would be able to update the changeset. However, according to the docs this is not possible, the px-click only ever sends the value of the clicked element as event param.
The next thing I tried was modifying the save handler to accept a situation where the add button was clicked, instead of the submit button. In this case the problem is the other way around, I can’t figure out a way to determine which button was clicked.
The third thing I tried was leaving the phx-click and phx-submit both in their place, and changing the button to type=“submit”. This actually works, the server handles the ‘add’ event first and than the savce event. However, I can’t really find any documentation on wether or not the events are processed in order. Besides, this would submit the form every time the add button is clicked, and potentially persist it in the database, which is not the intended effect.
What would be a good way to handle this case?