Advertising sustains the DA. Ads are hidden for members. Join today

Webform Cookbook

How to programmatically hide and show webform elements

Last updated on
15 December 2023

Below is a recipe for hiding and showing webform elements using a form_alter hook with the #access property.

Generally, you can use the Webform module's built-in element access controls via the UI for hiding and showing elements. Occasionally, you might want to use custom code and business logic to hide and show elements based on different user properties or even fields.

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Utility\WebformFormHelper;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function CUSTOM_MODULE_form_webform_submission_contact_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  // Flattening the elements makes it much easier to access nested elements.
  $elements = &WebformFormHelper::flattenElements($form['elements']);

  // Only display this element if user preferred language is English (en).
  if (isset($elements['ENGLISH_ONLY_ELEMENT']) && (\Drupal::currentUser()->getAccount()->getPreferredLangcode() != 'en')) {
    $elements['ENGLISH_ONLY_ELEMENT']['#access'] = FALSE;
  }

  // Hide email element for authenticated users.
  if (isset($elements['email']) && \Drupal::currentUser()->isAuthenticated()) {
    $elements['email']['#access'] = FALSE;
  }
}

Help improve this page

Page status: No known problems

You can: