Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

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



Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

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

Web Posts


Page Facebook