Nested_form / cocoon: is it possible to use table rows for nested fields?

I usually don’t use tables for forms, but if there is a nested form (when using nested_form or a cocoon gem), is it good to put each set of form elements inside the table row?

This seems pretty intuitive to me: every row in the table represents an object. But neither nested_form nor the cocoon gem adds tables to their examples by default, so I wonder if using forms is not the best way?

+7
html nested-forms table cocoon-gem
source share
1 answer

Yes. If you enter tabular data, you must use a table.

I have not tested the following examples, but I think it should work. Assuming that you are creating a receipt with a bunch of items, each of which has a description and price. In your opinion:

%table %thead %tr %th Description %th Price %tbody.line_items = f.simple_fields_for :line_items do |f| = render 'line_item_fields', f: f .links = link_to_add_association "Add", f, :line_items, data: {"association-insertion-node" => "tbody.line_items", "association-insertion-method" => "append"} 

association-insertion- node . This determines where to insert the new line_item element. In this example, I use the body of the table.

association-insertion method . The jQuery method used to insert a new line_item element. In the example, I add it to the end of the table body.

In _line_item_fields.html.haml:

 %tr.nested-fields %td= f.input :description, label: false %td= f.input :price, label: false %td= link_to_remove_association "Remove" 

The .nested-fields class is important because it tells the cocoon which item to remove when the Delete link is clicked.

+16
source share

All Articles