How do I hide a view's field based on role? In /admin/people, I want to hide the display name (i.e. the Display name must not appear in the user list), but only for a specific role.

In my .module file, I have tried following hooks:

function hook_views_data_alter(array &amp;$data) {
  kint($data['users']);die;
}

function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view-&gt;id() == 'myview'){
    print_r($view-&gt;result);die;
      // kint($value-&gt;_entity-&gt;get('title')-&gt;value);
  }
}

function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view-&gt;id() == 'viewid') {
    // Set the view title.
    $field_name = $view-&gt;getFields();
  }
}

function hook_field_views_data_views_data_alter(array &amp;$data, \Drupal\field\FieldStorageConfigInterface $field) {
  $field_name = $field-&gt;getName();
  echo 'hjsjhwd';
  print_r($field_name);die;
  }


None of them helped me. I thought of getting fields of the view "user" and after that I will unset it for particular role. But in views listing, Name field is still appearing. How can I hide it for a particular role?

Is there any way to achieve this?
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 &amp;$args) {
  if ($view-&gt;id() !== 'user_admin_people') {
    return;
  }

  $user_roles = \Drupal::currentUser()-&gt;getRoles();
  if (!in_array('my-special-role', $user_roles)) {
    $view-&gt;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.