Showing Hiding Fields with Stimulus

Overview

We can show and hide fields dynamically with stimulus html attributes. It works on simple fields as of now.

Usage

We need to pass html attributes for using this.

Hiding a Field.

  1. We need to specify a data-action.

  2. input is event name.

  3. fields is controller name.

  4. hide is action name.

  5. We need to provide the data-cm-hidden-id. These are ID's of target elements. This ID is added automatically from from_object.

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

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

  2. action will be changed to show.

  3. data-cm-hidden-id will be changed to data-cm-visible-id.

  4. 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' }