Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Conditional Form Fields (States)

By editor , 4 November, 2021

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' => ''],],
]

 

Tags

  • Drupal 8
  • Code
  • Drupal 9
  • Add new comment
Change the states of an element based on another element (field)

Comments1

Plain text

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

dave (not verified)

4 years 2 months ago

Not working for file fields

As the title says, this is working for file fields : Notice: Undefined index: #type in Drupal\Core\Form\FormHelper::processStates() (line 211 of core\lib\Drupal\Core\Form\FormHelper.php).

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer