Phoenix adding a new subform in nested form

I have schemas:

schema "users" do
  field :name, :string
  has_many :addresses, App.Address
end
schema "addresses" do
  field :street, :string
  field :city, :string
  ...
  belongs_to :user, App.User
end

I want to create a form for User with multiple Address subforms. Working with Ecto associations and embeds describes how to edit and remove items from collections. But there’s nothing about adding new ones dynamically, I mean generating a subform for new Address.

In Symfony there is something called prototype, a simple function that generates a form for new item in collection. It generates inputs with names like name="addresses[__name__][city]". Then I need to replace in JS __name__ with proper index of item in collection. I didn’t find any equivalent of that in Phoenix.

How should it be done in Phoenix? Or should we add this functionality to Phoenix?

I have already asked this question on Stackoverflow 8 months ago, but no one answered. Has anything changed in Phoenix since then? Today, once again I wanted to find an answer. And found my own question on SO with 168 views.

1 Like

I have the same question, on ruby there is a gem called cocoon to add new nested forms dynamically.

2 Likes

I think that all we need is to create a new function based on:

that will produce "__name__" instead of index_string. Then write proper JavaScript

1 Like