ruby-on-railsrubyhaml

Method to create a dropdown of checkboxes in HAML ruby on rails


I have a simple form I'm using to filter a table of students. By using f.collection_check_boxes I get an ugly paragraph of checkboxes. I would like to have a dropdown of these allowing me to select multiple at once.

My current code is

.card-header.d-flex.align-items-center
    %span Listing Students

    = link_to 'New Student', new_student_path, class: 'btn btn-outline-secondary ms-auto'
    %button.btn.btn-outline-secondary.dropdown-toggle.mr-2#filter-button{"type": "button", "data-bs-toggle": "dropdown", "aria-expanded": "false"}
      Filter
    %ul.dropdown-menu{"aria-labelledby": "filter-button"}
      %li
        = simple_form_for :filter, url: filter_students_path, method: :post do |f|
          = f.input :givenname
          %div
            = f.collection_check_boxes(:course_ids, Course.all, :id, :course_code)
            = button_tag 'SELECT', type: 'button', class: 'select_btn'
            %br
          %div
            = f.collection_select(:location_ids, Location.all, :id, :location_name, multiple :true)
            = button_tag 'SELECT', type: 'button', class: 'select_btn'
            %br
          %div
            = f.collection_check_boxes(:sector_ids, Sector.all, :id, :sector_name)
            = button_tag 'SELECT', type: 'button', class: 'select_btn'
            %br
          = f.submit 'Search'
          = link_to 'Reset', students_path

It produces a button that when clicked has a dropdown menu of multiple sets of options to filter by Im testing different methods on just the one option for now so collection_select results in a list that allows me to check multiple when I click + shift key, but i would like these to be a drop down of checkboxes rather than a list.


Solution

  • Per this answer I would use list inside your dropdown: Rails collection_check_boxes - wrap each checkbox with <li>

    I don't use HAML so I can't give you an explicit example but something like:

    <ul style="list-style-type: none;">
    <%= f.collection_check_boxes :course_ids, Course.all, :id, :course_code do |b| %>
      <li>
       <%= b.label { b.check_box } %>
      </li>
    <% end %>
    </ul>
    

    Note the style applied to the to prevent bullets from being added to the <li> elements.