Skip to main content
Category:

Code snippet that can be used to Conditionally hide/enable a form field programmatically in Drupal 8.

if you want to visually hide/show a form field, based on a specific value from another field, Form API #states property allows to easily show or hide, enable or disable, require or collapse form fields based on values selected or entered in other fields.

Conditional Fields Example

enable the radios only if the custom cms textbox is empty

$form['cms'] = [
  '#type' => 'radios',
  '#title' => $this->t('Select a cms'),
  '#options' => [
    'drupal' => $this->t('Drupal'),
    'wordpress' => $this->t('Wordpress'),
    'joomla' => $this->t('Joomla'),
    'other' => $this->t('Other'),
  ],
  '#attributes' => [
    'name' => 'field_select_cms',
  ],
  '#states' => [
    'enabled' => [
      ':input[name="field_other_cms"]' => ['value' => ''],
    ],
  ],
];

 

status form api

 

show this textfield only if the radio 'other' is selected


$form['other_cms'] = [
  '#type' => 'textfield',
  '#placeholder' => 'Enter your cms',
  '#attributes' => [
    'name' => 'field_other_cms',
  ],
  '#states' => [
    'visible' => [
      ':input[name="field_select_cms"]' => ['value' => 'other'],
    ],
  ],
];

 

status form api

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook