kuzyn

kuzyn

Form rendering problems with field {:array, :boolean}

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:
2024-11-25 17-33-19

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.

Marked As Solved

kuzyn

kuzyn

Thanks Frank! My mistake was definitely not looking more into the limitations of the checkbox input in the core_component. See How to make checkbox work with form bindings Phoenix LV? - #2 by LostKobrakai.

For future reference, this thread is also related: How to wire up a Phoenix form for a field {:array, :string}?

What I ended up with is an ugly ass solution that works:

  • A :check_options assign initiated with existing my_list values (if present)
  • A handrolled vanilla <input type="checkbox" ...> inside of a :for div
  • A phx-change handler to handle the checkboxes on/off and sanitize them into my temporary checked_options in my assign
  • And finally a a Map.merge in my save handler that take this checked_options and put it into my params prior to generating the changeset

So in other words, I am binding the data manually with handlers and making sure it is merged into the params/changeset rather than relying on the field={@form[:my_list]} convenience. A whole lot uglier but at least I can move on :saluting_face:

Also Liked

frankdugan3

frankdugan3

This fly.io blog covers how to do it pretty well. Can vouch for it: I’ve based my checkbox group components on it.

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New

Other popular topics Top

joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44139 214
New

We're in Beta

About us Mission Statement