I'm experimenting with Phoenix 1.6 and LiveView, and trying to get my nested form/models to work as expected.
I have a schema with something like: Parent
, Child
, where Parent has_many Children // Child belongs_to parent.
I want to have something like an Add Child button, which will render another Child model in my form in the inputs_for block, that I can make changes to, and eventually submit.
I've tried a handful of things such as https://fullstackphoenix.com/tutorials/nested-model-forms-with-phoenix-liveview , but they either don't seem to work, or seem a bit outdated (referencing things that don't exist for me). The documentation helps a little bit, but doesn't seem to connect the Ecto bits with the LiveView bits that I'm looking for very well. Does anyone have thoughts/advice on the best way to achieve what I'm looking for? (I'm also a bit newer to Elixir/Phoenix/Ecto, so there may be things that I'm overlooking)
I don't know if you're still struggling with this but I made it work some time ago. I was working on some e-commerce application prototype and found the same post you shared.
Here's a form_component example that uses the variants concept. If you use Phoenix 1.5 you can look a few commits back before the migration to .heex
happened.
I could give you some more advice if you share a bit of code where the problem resides.
This is a basic example.
<.icon phx-click="add_row" phx-value-id={f.data.id}
...
def handle_event("add_row", %{"id" => id}, socket) do
%{changeset: changeset, parent: parent} = socket.assigns
l = length(parent.childs)
new_child = %Child{order: l, parent_id: id}
childs =
changeset.changes
|> Map.get(:childs, parent.childs)
|> Enum.concat([new_child])
parent = Map.put(parent, :childs, childs)
{:noreply,
socket
|> update(:changeset, fn changeset ->
Ecto.Changeset.put_assoc(changeset, :childs, childs)
end)
|> assign(:parent, parent)}
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.