My schema is very simple:
schema "partnerships" do
field :email, :string
field :name, :string
field :social_media_urls, {:array, :string}
timestamps()
end
I want to be able to click on Add Another to add another input to the UI.
Here’s what I’ve tried so far:
def mount(_params, _session, socket) do
roles = Partnerships.list_partnership_roles()
changeset = make_changeset()
socket =
socket
|> assign(%{
page_title: "Partnerships",
roles: Enum.map(roles, &{&1.name, &1.id}),
changeset: changeset,
social_media_urls: changeset.data.social_media_urls
})
{:ok, socket}
end
@impl true
def handle_event(
"validate",
%{"partnership" => attrs},
socket
) do
changeset =
%Partnership{}
|> Partnerships.change_partnership(attrs)
|> Map.put(:action, :validate)
{:noreply,
assign(socket,
changeset: changeset,
social_media_urls: changeset.data.social_media_urls || [""]
)}
end
def handle_event("add-new-social-media-urls", attrs, socket) do
social_media_urls = ["" | socket.assigns.social_media_urls]
changeset =
socket.assigns.changeset
|> Ecto.Changeset.change(social_media_urls: social_media_urls)
{:noreply, assign(socket, :changeset, changeset)}
end
defp make_changeset(attrs \\ %{}) do
%Partnership{
social_media_urls: [""]
}
|> Partnerships.change_partnership(attrs)
end
The problem is that as soon as validate
runs it wipes out my social media url fields.
How would you wire up this form?