Skip to main content

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.​

  1. We need to specify a data-action.
  • input is event name.
  • fields is controller name.
  • hide is action name.
  1. We need to provide the data-cm-hidden-id. These are ID's of target elements. This ID is added automatically from from_object.
  2. we can pass data-cm-toggle-values a hash for hiding fields on particular values or we can pass data-cm-toggle-value a string if all fields need to hidden on a single value.
  3. On Target element we need to pass data-fields-target, this is stimulus feature and it's value can be either cmHidden and cmVisible.
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.​

  1. It's similar to hiding field. There are some changes:
  • action will be changed to show.
  • data-cm-hidden-id will be changed to data-cm-visible-id.
  • data-fields-target value will be changed to cmVisible.
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