Form containing a list of checkboxes: is this the right way?

I want to produce a list of checkboxes that looks like this:

The following works, but is the explicit calculation of a checkbox’s name the Right Way™ to do it?

<%= for a <- @animals do %>
  <div class="field">
    <div class="ui checkbox">
      <%= checkbox(f, :animal_ids,
          name: "#{input_name(:after_the_fact_form, :animal_ids)}[#{a.id}]") %>
      <label><%=a.name%></label>
    </div>
  </div>
<% end %>

I have a similar code, but in helper, using content_tag instead.

I use name like this…

          tag(:input,
            name: input_name(form, field) <> "[]",
            id: id,
            class: "form-check-input",
            type: "checkbox",
            value: key,
            checked: Enum.member?(selected_as_strings, "#{key}"),
            disabled: disabled
          ),
3 Likes

Thanks. Where does selected_as_strings come from?

It’s just a list of association ids, turned to string…

selected_as_strings = Enum.map(selected, &"#{&1}")

# selected is the ids of preloaded association

I pass this list to my helper, to check if the checkbox is active or not…

1 Like