Skip to main content

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​

NameTypeDefaultDescription
display_typeSymbol:table:table, :card or :table_with_grid.
submit_textString"+ Add <Field Name>"Label of the add button.
is_creatableProc->(_) { true }Whether new rows can be added.
is_deletableProc->(_) { true }Lambda receiving the row record; whether it can be removed.
is_clonableProc->(_) { false }Lambda receiving the row record; whether it can be cloned.
is_positionableProc->(_) { false }Enables drag-and-drop ordering. Saves to a position column when the model has one.
show_serial_numbersProc->(_) { false }Shows a serial number column.
display_ifProc->(_) { true }Whether the nested field is shown.
allowed_grid_fieldsArray[]Fields shown in grid view (:table_with_grid), in this order.
grid_column_countInteger6Grid columns for :table_with_grid (1–12).
default_view_typeSymbol:tableInitial view for :table_with_grid: :table or :grid.
enable_floating_labelBooleantrueUse floating labels for inputs.
header, labelStringnilHeader and label of the nested field.
html_attrsHash{}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