This function in Drupal 8 allows you to test the user's current role and give them access to some sort of data programmatically. For example, you might have a custom block that you want only a certain role to see. This function below will give you that functionality. Add the code to your .module file in your module .theme in your custom theme.
/** * Tests the current user role allowing it to access the something in the module * * False: means no access to the software * True: means you are able to access the software * * * @return bool */ function __check_user_access() { $roles = [ 'editor', 'admin', ]; $current_role = \Drupal::currentUser()->getRoles(); foreach($roles as $role) { if($role == $current_role[1]) { return TRUE; } } return FALSE; }
This is an example on how to use it. If the user was an 'Admin' or 'Editor' they will be able to see the custom block in the theme. Once it has been added in the twig layer by the developer.
/** * Implements hook_preprocess_html(). */ function_preprocess_html(&$vars) { if (_ _check_user_access() != FALSE) { $block = \Drupal\block\Entity\Block::load(' '); $vars[' '] = \Drupal::entityTypeManager() ->getViewBuilder('block') ->view($block); } }
