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

℡╲_俬逩灬. 提交于 2019-12-03 09:27:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18734783/nested-form-cocoon-is-it-okay-to-use-table-rows-for-nested-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!