Using #access to control element visibilityfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Following our exploration of using the #disabled property to prevent input, we now turn to the #access property, a powerful feature in Drupal’s Form API. This functionality allows you to determine the visibility of form elements based on user roles, permissions, or other conditions, increasing both security and user experience.

Understanding the #access Property

The #access property is a boolean flag that determines whether a form element should be rendered and displayed to the user. When set to FALSE, the element is neither visible on the form page nor included in form submissions, unlike the #disabled property, which makes fields non-interactive but still viewable.

When to Use #access

Deploying the #access attribute is suitable in numerous scenarios:

  • Role-Based Access Control: Display or hide elements based on user roles or permissions.
  • Conditional Visibility: Hide certain inputs or sections until prerequisites are met.
  • Streamlined User Experience: Simplify the interface by hiding elements irrelevant to specific user interactions.

Implementing #access

Below is an example implementation of a form where an "Admin Notes" field is only visible to users with administrative access:


$form['admin_notes'] = [
    '#type' => 'textarea',
    '#title' => t('Admin Notes'),
    '#access' => \Drupal::currentUser()->hasPermission('administer site configuration'), // Conditional visibility for admins
];

$form['username'] = [
    '#type' => 'textfield',
    '#title' => t('Username'),
];

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

        

In this form, "Admin Notes" will only be visible and accessible to users with the permission "administer site configuration". Others won’t see or interact with this field, ensuring information confidentiality and simplifying the user interface.

Advanced Visibility Controls

Utilize #access to dynamically hide or show elements based on custom logic. For example, based on a user-selected option:

Conditional Example

Here's how you might show a specific field based on a user's choice in another field:


function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'my_custom_form') {
        $form['company'] = [
            '#type' => 'textfield',
            '#title' => t('Company Name'),
        ];

        $form['company_type'] = [
            '#type' => 'select',
            '#title' => t('Company Type'),
            '#options' => [
                'none' => t('- Select -'),
                'private' => t('Private'),
                'public' => t('Public'),
            ],
            '#default_value' => 'none',
        ];

        $form['additional_public_info'] = [
            '#type' => 'textfield',
            '#title' => t('Additional Info for Public Companies'),
            '#access' => $form_state->getValue('company_type') == 'public',
        ];
    }
}

        

In this form handling example, "Additional Info for Public Companies" only appears when the "Company Type" selected is "Public", using #access for dynamic control.

Considerations for #access

  • Performance Optimization: Exclude non-permissible elements from rendering, optimizing form performance and user experience.
  • Logical Conditions: Ensure all logic checks (role, permission) are ironclad to prevent accidental visibility.
  • User Feedback: Provide informative messages when access is denied, if applicable, to promote transparency.

Conclusion

The #access property in Drupal’s Form API is an essential tool for crafting user-centric forms, tailored to security protocols and role-specific needs. By judiciously controlling element visibility, you foster a clean, targeted user experience while safeguarding sensitive data.

What’s Next?

Stay tuned as we explore using the #type 'details' element to organize form content with collapsible sections, enhancing both user navigation and interface intuitiveness.