Dynamically added/remove inputs in LiveView form

Hi, I’m stuck on how should I implement a liveview form where it can add or remove fields.

Poll schema:

schema "polls" do
    field :expiration, :naive_datetime
    field :question, :string

    belongs_to(:user, Botar.Accounts.User)
    has_many(:choices, Botar.Polls.Choice)
    has_many(:votes, Botar.Polls.Vote)

Choice schema:

  schema "choices" do
    field :choice, :string
    belongs_to(:poll, Botar.Polls.Poll)

I can make this work in javascript but I think it is also possible with LiveView.
Any guide/pointers much appreciated.

Thank you.

I think you can do it with this flow:

  1. create simple form with simple LV render (poll should have empty list of choices)
  2. create button to add more choice with phx-click=“add-choice”
  3. handle this event in LV but don’t forget to process already filled data. You have poll.choices empty list now. So add one more empty struct Choice (or with default values).
  4. Your html.leex file should know to handle poll.choices with “for cycle” and html inputs.
  5. Don’t forget to use phx_submit flag into your form_for definition

Maybe there is some tutorial on internet with better wording than my :slight_smile:

Is there any guide/post/article for this for Phoenix 1.6? Would love to see an actual example :slight_smile:

There’s a article I found here though it’s not Phoenix 1.6. There might some changes in the code needed since the version used in the article was an older one but I think you can get the idea on how to implement it.