Conditional Form Fields (States) | Drupal 8

Conditional Form Fields (States)

Submitted by editor on Thu, 11/04/2021 - 14:03

Doc : https://www.drupal.org/docs/drupal-apis/form-api/conditional-form-fields

States that can be applied to a form field element:

  • enabled
  • disabled
  • required
  • optional
  • visible
  • invisible
  • checked
  • unchecked
  • expanded
  • collapsed
     

The following states may be used when checking values of other fields:

  • empty
  • filled
  • checked
  • unchecked
  • expanded
  • collapsed
  • value
     

The following states exist for both elements and remote conditions. 
Those might not be implemented in all browsers and may not change anything on the element:

  • relevant
  • irrelevant
  • valid
  • invalid
  • touched
  • untouched
  • readwrite
  • readonly

 

Examples :

Disable submit button until email field is empty

$form['submit'] = [
'#type' => 'submit',
  '#states' => [
    'disabled' => [':input[name="email"]' => ['value' => ''],]
  ]
];

OR, AND, XOR Conditions

'disabled' => [
  [':input[name="email"]' => ['value' => ''],],
  'and',
  [':input[name="zip_code"]' => ['value' => ''],],
]

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.