David Lohmeyer's Blog

How to check a user role inside a custom module in Drupal 8

If you need to check for a specific role such as 'administrator' in Drupal 8, the process is changed from past versions. The following is an example of how you'd check for an administrator role when rendering the user edit form. You might do this if you were unsetting form variables based on role:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 * Demo functionality gives non-admins no permission to update their username/password
 * by unsetting it when they view their profile edit screen.
 */
function check_user_role_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser()->getRoles();
  if(!in_array("administrator", $user) && $form_id == 'user_form') {
  	unset($form['account']);
  }
}

Get the full demo module on Github.

Related Posts