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)
timestamps()
end
Choice schema:
schema "choices" do
field :choice, :string
belongs_to(:poll, Botar.Polls.Poll)
timestamps()
end
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:
- create simple form with simple LV render (poll should have empty list of choices)
- create button to add more choice with phx-click=“add-choice”
- 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).
- Your html.leex file should know to handle poll.choices with “for cycle” and html inputs.
- 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
Is there any guide/post/article for this for Phoenix 1.6? Would love to see an actual example
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.