Disable elements on drupal webform

Drupal 8 provides an easy way to simply edit the component or element on the drupal webform and disable elements using the checkbox displayed on the form.

 

disable elements

However, there could be different scenarios where we might need to disable few elements on specific cases that might not available on drupal webform conditional. Eg - Disable elements for certain user roles.

In such cases, it is better to simply implement the required change in a custom hook and disable the elements on the form. This could be done using form_alter hook available in all versions of drupal.

Disable Elements in hook_form_alter

function my_module_form_webform_client_form_<form_id>_alter(&$form, &$form_state, $form_id) {
  //Insert specific condition eg user role != admin, etc.
  //Freeze all elements
  foreach ($form['submitted'] as &$components) {
    $components['#attributes']['disabled'] = 1;
  }

  //Optionally, remove the submit button if don't want the user/role to submit the form.
  unset($form['actions']['submit']);
}