bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 115 forks source link

Select all and row checkboxes #293

Closed noctivityinc closed 3 years ago

noctivityinc commented 3 years ago

Thanks for the amazing gem. I've been trying to figure out something that I think may be included in the gem but I'm just missing it.

I need a way to display a checkbox as the first column in every row and then a "select all" checkbox in the header. This is pretty standard stuff, so I'm hoping it's built in but I can't seem to find any info or issues about how to do this.

Thanks.

bogdan commented 3 years ago

See, the feature like this one is pretty personal: I had ~10 projects with datagrid and none of them required that. Also this feature is layout sensitive: some people would want to lay it out one way or the other. So I can not implement it in the core.

Here is how you can do it for specific project:

Run:

rake datagrid:copy_partials

Modify app/views/datagrid/_head.html.erb:

<tr>
  <% grid.html_columns(*options[:columns]).each do |column| %>
    <th class="<%= datagrid_column_classes(grid, column) %>">
+     <% if column.options[:selection] -%>
+        <%= check_box_tag :row_selector, 'ALL', params[:row_selector]&.include?('ALL'), multiple: true, class: 'selection_checkbox' -%>
+     <% end -%>
      <%= column.header %>
      <%= datagrid_order_for(grid, column, options) if column.supports_order? && options[:order]%>
    </th>
  <% end %>
</tr>

Modify app/views/datagrid/_row.html.erb:

<tr>
  <% grid.html_columns(*options[:columns]).each do |column| %>
    <td class="<%= datagrid_column_classes(grid, column) %>">
+    <% if column.options[:selection] %>
+      <%= check_box_tag 'row_selector', asset.id, params[:row_selector]&.includes?(asset.id.to_s), multiple: true, class: 'selection_checkbox' %>
+    <% end %>
      <%= datagrid_value(grid, column, asset) %>
    </td>
  <% end %>
</tr>
column(:first, selection: true) do |model|
   model.name
end

Feel free to follow up on any questions.

noctivityinc commented 3 years ago

@bogdan - that's pretty fantastic, thank you. I changed the above slightly to else statements so I can just include:

column(:first, selection: true)

to get the first column with checkboxes but still, perfect.