Showing Hiding Fields with Stimulus
Overviewâ
We can show and hide fields dynamically with stimulus html attributes. It works on simple fields and nested form fields.
Usageâ
We need to pass html attributes for using this.
Hiding a Field.â
- We need to specify a
data-action.
inputis event name.fieldsis controller name.hideis action name.
- We need to provide the
data-cm-hidden-id. These are ID's of target elements. This ID is added automatically fromfrom_object. - we can pass
data-cm-toggle-valuesa hash for hiding fields on particular values or we can passdata-cm-toggle-valuea string if all fields need to hidden on a single value. - On Target element we need to pass
data-fields-target, this is stimulus feature and it's value can be eithercmHiddenandcmVisible.
form_field :title, input_type: :string,
html_attrs: { 'data-action': 'input->fields#hide',
'data-cm-hidden-id': 'is_featured tag_ids',
'data-cm-toggle-values': '{ "is_featured": "hide", "tag_ids": "hides" }' }
form_field :is_featured, input_type: :switch, label: 'My Custom Switch Label',
html_attrs: { 'data-fields-target': 'cmHidden' }
Showing a Field.â
- It's similar to hiding field. There are some changes:
- action will be changed to
show. data-cm-hidden-idwill be changed todata-cm-visible-id.data-fields-targetvalue will be changed tocmVisible.
form_field :user_id, input_type: :single_select, helper_method: :select_options_for_users,
html_attrs: { 'data-action': 'change->fields#show',
'data-cm-visible-id': 'is_featured tag_ids',
'data-cm-toggle-value': ::User.first&.id.to_s }
form_field :tag_ids, input_type: :multi_select, helper_method: :select_options_for_tag,
html_attrs: { 'data-fields-target': 'cmVisible' }
Hiding a Nested Form Field.â
nested_form_field also accepts html_attrs. The attributes are applied to the nested section wrapper, so the whole nested section can be toggled. The wrapper automatically gets data-cm-id set to the association name and data-toggle-cm-class set to nested-field-wrapper, so only data-fields-target needs to be passed.
form_field :has_no_previous_addresses, label: 'I have no previous addresses', input_type: :switch,
html_attrs: { 'data-action': 'input->fields#hide',
'data-cm-hidden-id': 'addresses' }
nested_form_field :addresses, html_attrs: { 'data-fields-target': 'cmHidden' } do
form_field :address_type, label: 'Type', input_type: :single_select,
helper_method: :residential_address_type_option_for_select
form_field :street_address
end