Multiple select form with checkboxes

I know it is possible because I have done that before with Rails and SimpleForm…

This example is a many_to_many relationship between User and Role. The point is to use simple input and specify the name of the checkbox as user[roles_ids][] with square brackets at the end.

    <%= for role <- @roles do %>
      <label>
        <%= role.name %>:
        <input name="user[roles_ids][]" type="checkbox" value="<%= role.id %>">
      </label>
    <% end %>

And that is the log from the request (with stripped csrf token) when I select roles 1 and 2.

[debug] Processing with DemoWeb.UserController.create/2
  Parameters: %{"_utf8" => "✓", "user" => %{"name" => "hello", "roles_ids" => ["1", "2"]}}
  Pipelines: [:browser]

As You can see, I get a list of ids :slight_smile:

As a side note, it’s possible to add a check value to checkbox like this…

checked="<%= user_has_role?(@user, role)%>"

… as mentionned in this old post Many to many checkbox form

14 Likes