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
. -
input
is event name. -
fields
is controller name. -
hide
is 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-values
a hash for hiding fields on particular values or we can passdata-cm-toggle-value
a 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 eithercmHidden
andcmVisible
.
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-id
will be changed todata-cm-visible-id
. -
data-fields-target
value 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' }