How to Use Drupal Form API #states for Conditional Fields Safely
When building custom configuration forms or user workflows in Drupal, you often want a secondary field—such as a custom webhook URL or tax ID—to appear only when a checkbox is ticked or a specific radio option is selected. Reaching for custom jQuery toggle scripts adds brittle selectors and breaks whenever Drupal’s markup changes. Drupal’s built-in Form API #states property handles conditional visibility and state changes declaratively, as long as you remember where client-side #states ends and server-side validation begins.
Editorial illustration: #states updates the browser UI via JavaScript, while validateForm() enforces conditional requirements on the server.
Summary
- Per Drupal’s Conditional Form Fields (
#states) documentation,#stateslets you show, hide, enable, disable, require, or collapse form elements based on the values of other fields on the page. #statesruns entirely in the browser via Drupal’sstates.jslibrary—using'required'inside#statesadds the visual asterisk and client-side behavior, not server-side enforcement.- Always pair conditional
'required'rules in#stateswith explicit checks inside your form’svalidateForm()method so empty values cannot slip through via craftedPOSTrequests or disabled JavaScript. - For complex server-driven updates (such as dynamically querying options from a database), use Drupal’s AJAX Forms API instead of overloading
#states.
How #states works in a Drupal Form API render array
Inside buildForm(), attach #states to the dependent element and target the controlling input using a jQuery-style selector (most commonly :input[name="..."]):
$form['delivery_mode'] = [
'#type' => 'radios',
'#title' => $this->t('Notification method'),
'#options' => [
'email' => $this->t('Email'),
'webhook' => $this->t('Custom webhook'),
],
'#default_value' => 'email',
];
$form['webhook_url'] = [
'#type' => 'url',
'#title' => $this->t('Webhook URL'),
'#states' => [
'visible' => [
':input[name="delivery_mode"]' => ['value' => 'webhook'],
],
'required' => [
':input[name="delivery_mode"]' => ['value' => 'webhook'],
],
],
];
Common states supported by FormHelper::processStates() (documented in Form Render Elements) include:
visible/invisibleenabled/disabledrequired/optionalchecked/uncheckedexpanded/collapsed
You can combine multiple conditions using 'and' (default when listing multiple selectors in an array) or 'or' / 'xor' arrays.
The #1 pitfall: #states 'required' is NOT server-side validation
Many developers assume setting 'required' => [...] inside #states works the same way as '#required' => TRUE. It does not.
As highlighted in Drupal core discussions (issue #2855139), #states only manipulates the DOM in the browser. If a visitor submits the form with JavaScript disabled or alters the request, Drupal’s Form API on the server does not automatically enforce conditional #states requirements.
Always enforce conditional requirements in validateForm():
public function validateForm(array &$form, FormStateInterface $form_state): void {
parent::validateForm($form, $form_state);
if ($form_state->getValue('delivery_mode') === 'webhook'
&& empty($form_state->getValue('webhook_url'))) {
$form_state->setErrorByName(
'webhook_url',
$this->t('Webhook URL is required when Custom webhook is selected.')
);
}
}
When to use #states vs. AJAX Forms
- Use
#stateswhen all options already exist on the page and you only need to show, hide, enable, or disable fields instantly in the browser with zero server round-trips. - Use Drupal AJAX Forms when changing Field A must fetch brand-new
<select>options or computed markup from the server (for example, Country → State/City dropdowns). Note that combining#statesinside elements that get replaced via AJAX can occasionally cause state-listener quirks—test those forms carefully on staging.
Also remember: if you are building a configuration form, store deployable settings via the Config API while keeping runtime timestamps in Drupal’s State API, and keep environment-specific tools separated with Configuration Split.
Common mistakes
- Putting
#required => TRUEon a field that#stateshides. If a field has#required => TRUEin PHP while#stateshides it in the browser, users cannot submit the form when the field is hidden because PHP still demands a value! Always use#states['required']+validateForm()for conditionally required fields. - Using fragile CSS class selectors instead of
:input[name="field_name"]. Selectors targeting wrapper<div>IDs break when themes or fieldgroups change;:input[name="..."]targets the actual form control reliably. - Expecting
#statesto clear an old value when a field is hidden. Hidingwebhook_urldoes not erase a value the user typed before switching back toemail. InsubmitForm(), ignore or clear dependent values based on the controlling field’s state.
Why this matters
Declarative #states keeps custom Drupal forms accessible, consistent with core admin UI conventions, and free of ad-hoc jQuery scripts—while pairing it with validateForm() ensures your data validation never depends solely on browser JavaScript.
My Take
Use #states for every simple show/hide or enable/disable interaction in Drupal forms, never combine #required => TRUE with conditional visibility, and make writing the matching validateForm() check an automatic habit whenever you use 'required' inside #states.
Conclusion
Use Drupal Form API #states with :input[name="..."] selectors for instant client-side conditional fields, enforce conditional requirements on the server inside validateForm(), sanitize or ignore hidden dependent values in submitForm(), and switch to AJAX callbacks when options must be loaded dynamically from the server.