How to assign content to a specific user role Drupal 8 in a custom module programmatically

You are here

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 _<module-name>_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 <module-name>_preprocess_html(&$vars) {

  if (_<module-name>_check_user_access() != FALSE) {
    $block = \Drupal\block\Entity\Block::load('<load_custom_block>');
    $vars['<add_me_to_the_twig_template>'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
  
}