mc92
mc92

Reputation: 495

Phoenix LiveView Nested Associations Form

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)

Upvotes: 4

Views: 1378

Answers (1)

Vladimir R
Vladimir R

Reputation: 1

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

Upvotes: 0

Related Questions