Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested_form/cocoon: is it okay to use table rows for nested fields?

I normally don't use tables for forms, but when having a nested form (when using nested_form or cocoon gem), is it okay then to put each set of form elements inside a table row?

To me, this seems pretty intuitive: every row in the table represents an object. But neither the nested_form nor the cocoon gem add tables in their examples by default, so I wonder whether using forms isn't the best way to go?

like image 403
Joshua Muheim Avatar asked Sep 11 '13 07:09

Joshua Muheim


1 Answers

Yes. If you are inputting tabular data then you should use a table.

I haven't tested the following examples but I think it should work. Assuming you are building a receipt with a bunch of line items, each with a description and price. In your view do:

%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 controls where to insert the new line_item. In the example I use the table body.

association-insertion-method: The jQuery method used to insert the new line_item. In the example I append 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 as it tells cocoon which element to delete when the "Remove" link is clicked.

like image 61
Steve Avatar answered Sep 30 '22 19:09

Steve