Using #states ['visible'] based on conditionsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Continuing our journey into using #states in Drupal's Form API, we will now explore how to implement visibility logic based on multiple conditions. This allows you to manage more complex user interactions by determining when certain form elements should be shown or hidden, depending on multiple factors or form elements.

Recap: The Power of #states

Previously, we learned how #states could control the visibility of form elements using basic conditions. This time, we'll expand this logic by utilizing multiple form inputs as triggers for visibility, providing a richer and more interactive user experience.

Why Use Multiple Conditions for Visibility?

  • Complex Interactions: Reflects real-world scenarios where visibility hinges on various user inputs.
  • Improved User Focus: Directs user attention by dynamically showing relevant fields based on their actions.
  • Reduced Confusion: Hiding irrelevant options clarifies user choices.
  • Highly Customizable: Adapts your form interface to better suit the needs of specific workflows.

Example: Implementing Multiple Conditions

Imagine a form allowing users to apply for an event. We want a special dietary requirements field to appear only if the user indicates attendance and confirms they have dietary needs.

 


function mymodule_event_form(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form['attending'] = [
        '#type' => 'checkbox',
        '#title' => t('Attending the event?'),
    ];

    $form['dietary_needs'] = [
        '#type' => 'checkbox',
        '#title' => t('Special dietary requirements?'),
        '#states' => [
            'visible' => [
                ':input[name="attending"]' => ['checked' => TRUE],
            ],
        ],
    ];

    $form['dietary_details'] = [
        '#type' => 'textfield',
        '#title' => t('Please specify your dietary requirements'),
        '#states' => [
            'visible' => [
                ':input[name="attending"]' => ['checked' => TRUE],
                ':input[name="dietary_needs"]' => ['checked' => TRUE],
            ],
        ],
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('Apply'),
    ];

    return $form;
}

 

Explanation of the Code

Here's how the example operates:

  • The attending checkbox determines whether a user plans to attend the event.
  • The dietary_needs checkbox becomes visible only if the user has confirmed attendance. This encourages users to specify if they have any special dietary requirements.
  • The dietary_details text field is visible when both the attending and dietary_needs checkboxes are checked, asking for specific dietary information.
  • This configuration demonstrates the versatility of #states, allowing you to connect visibility rules to multiple conditions seamlessly.

The Advantages of Conditional Visibility

Implementing #states['visible'] based on conditions helps you design forms that are not only smarter but also more conducive to user needs. This leads to higher conversion rates, as users are more likely to fill out forms that adapt to their input context.

What's Next?

As we continue to enhance our forms' interactivity, our next lesson will focus on utilizing #states['disabled'] for dynamic behavior, allowing you to enable or disable form elements based on specific conditions. This is an essential skill for crafting truly dynamic forms in Drupal.