Drupal - How do I hide a view's field based on role?

The most efficient way would be using hook_views_pre_view(), which allows you to alter a View at the very beginning of the process i.e. before any query is built/run and before any rendering takes place. You can remove the 'name' field handler from the View based on the desired logic.

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() !== 'user_admin_people') {
    return;
  }

  $user_roles = \Drupal::currentUser()->getRoles();
  if (!in_array('my-special-role', $user_roles)) {
    $view->removeHandler($display_id, 'field', 'name');
  }
}

This solution assumes that you are only interested to serve this very specific use case - remove the field only from this specific View. Users might still be able to see the Display Names of users in other areas of the website.


You can hide fields using hook_entity_field_access, you can hide field based on user account (role is one of its properties), operation and entity which contain the field.

You also can use Field Permissions module to hide a field from certain roles.

Tags:

Views

Users

8