Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

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

Parent Feed: 

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.

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web