I am trying to create a LiveView form that allows 6 checkboxs to be toggled and saved as a single array of boolean values under Ecto.
The problem is that every time I change the form by clicking on the checkboxes, this array grows and new empty fields are added to the LV. As far as I can tell, it looks like it is appending a value before the validate handle_event
. I cannot figure out why (I have another field, {:array. :float}
that works just fine in the same view. Otherwise, i have nothing but boilerplate in my live component file (nothing added to mount, update, etc)…
What the bug looks like:
In my context:
defmodule AppName.Things.MyThing do
use Ecto.Schema
import Ecto.Changeset
schema "things" do
field :my_list, {:array, :boolean}, default: [false, false, false, false, false, false]
timestamps(type: :utc_datetime)
end
@doc false
def changeset(my_thing, attrs) do
my_thing
|> cast(attrs, [
:included
])
end
end
In my LV:
@impl true
def render(assigns) do
~H"""
<div>
<.simple_form
for={@form}
id="my_thing-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<.input
:for={
{entry, index} <-
Enum.with_index(Ecto.Changeset.get_field(@form.source, :my_list, []))
}
value={entry}
name="my_thing[my_list][]"
type="checkbox"
/>
<:actions>
<.button phx-disable-with="Saving...">Save My Thing</.button>
</:actions>
</.simple_form>
</div>
"""
end
Is this a problem from using :for
on the checkbox input? I have tried a few things but they all felt hacky and did not work.