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