How to create a nested param for checkbox elements in the form?

I’ve got a schema called Project and it has a field named subcategories and that field is an array of strings in the DB (Postgres).

Schema I have:

  schema "projects" do
    field :subcategories, {:array, :string}
    field(:name, :string)


For that reason in my project/edit.html.eex form I would like to have checkboxes for a user to select subcategories and I am planning to keep those subcategories in the DB in my subcategories column as an array of strings. I’ve tried to use inputs_for/2 but that didn’t really help.

I get this error below:

could not generate inputs for :subcategories from Projects.Project. Check the field exists and it is one of embeds_one, embeds_many, has_one, has_many, belongs_to or many_to_many

For this snippet from project/edit.html.eex:

    <div class="row">
      <div class="col">
        <div class="form-group">
          <%= label f, :subcategories, "Choose subcategories"%>
          <%= for checkbox_form <- inputs_for(f, :subcategories) do %>
            <%= for subcategory <- @subcategories do %>
              <div class="form-check">
                <%= checkbox f, subcategory, class: "form-check-input"%>
                <%= label f, subcategory, subcategory, class: "form-check-label" %>
            <% end %>
          <% end %>

After submitting the edit form what I expect to see in params is:

"project" => %{"name" => "foo", "subcategories" => %{"foo" => "true", "bar" => "false", "baz" => "true"}}

A similar question on SO though for reference.

Would it be possible to change your schema definition, to use embeds like in the example?

If not, inputs_for accepts a string, so you might try using that to build the form manually.

1 Like

That’s actually how I’ve overcome this. I was planning to write an answer here as an example but been kinda lazy. :slight_smile: Hopefully I will do it soon. Thank you for the help and reminding me of this question!

1 Like