Nested Form Fields
nested_form_field lets users add, remove, clone and reorder associated records inside the parent form. It renders as a table, cards or a table with a grid, and is powered by Stimulus.
Quick exampleβ
app/models/job.rb
has_many :job_questions, dependent: :destroy
accepts_nested_attributes_for :job_questions, allow_destroy: true
cm_new page_title: "Add Job" do
cm_section "Questions" do
nested_form_field :job_questions, submit_text: "+ Add Question" do
form_field :question
form_field :is_required, input_type: :switch
end
end
end
Optionsβ
| Name | Type | Default | Description |
|---|---|---|---|
display_type | Symbol | :table | :table, :card or :table_with_grid. |
submit_text | String | "+ Add <Field Name>" | Label of the add button. |
is_creatable | Proc | ->(_) { true } | Whether new rows can be added. |
is_deletable | Proc | ->(_) { true } | Lambda receiving the row record; whether it can be removed. |
is_clonable | Proc | ->(_) { false } | Lambda receiving the row record; whether it can be cloned. |
is_positionable | Proc | ->(_) { false } | Enables drag-and-drop ordering. Saves to a position column when the model has one. |
show_serial_numbers | Proc | ->(_) { false } | Shows a serial number column. |
display_if | Proc | ->(_) { true } | Whether the nested field is shown. |
allowed_grid_fields | Array | [] | Fields shown in grid view (:table_with_grid), in this order. |
grid_column_count | Integer | 6 | Grid columns for :table_with_grid (1β12). |
default_view_type | Symbol | :table | Initial view for :table_with_grid: :table or :grid. |
enable_floating_label | Boolean | true | Use floating labels for inputs. |
header, label | String | nil | Header and label of the nested field. |
html_attrs | Hash | {} | HTML attributes for the container. |
Recipesβ
List the records on a show pageβ
nested_form_field works inside cm_show too β declare fields in the block instead of form_fields and the association renders read-only, as a table by default or a card per record with display_type: :card. The add/remove/clone options only apply to forms.
cm_show page_title: :title do
tab :profile, "" do
cm_section "Questions", display_if: ->(job) { job.job_questions.any? } do
nested_form_field :job_questions do
field :question
field :is_required
end
end
end
end
Sortable media gridβ
nested_form_field :media_items_by_position,
display_type: :table_with_grid, default_view_type: :grid,
allowed_grid_fields: %i[attachment name external_name], grid_column_count: 4,
is_positionable: ->(_obj) { true }, submit_text: "Add Media Items" do
form_field :name, label: "Internal Name", placeholder: "Enter internal name"
form_field :external_name, placeholder: "Enter external name"
form_field :attachment, input_type: :single_file_upload, image_preview: true
form_field :media_item_type, input_type: :single_select, helper_method: :media_item_type_list
form_field :notes
end