Skip to content

Instantly share code, notes, and snippets.

@mattschaff
Last active April 4, 2019 13:56
Show Gist options
  • Save mattschaff/aa0ce42f9de48fffbe06bcb784f61f89 to your computer and use it in GitHub Desktop.
Save mattschaff/aa0ce42f9de48fffbe06bcb784f61f89 to your computer and use it in GitHub Desktop.
Drupal 8: Access view fields based on user role
<?php
use Drupal\views\ViewExecutable;
/**
* Implements hook_views_pre_view().
*/
function my_module_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
// Control access to specific view fields based on user role.
if ($view->id() == 'view_machine_name') {
if (\Drupal::currentUser()->isAnonymous() || !in_array('desired_role_name', \Drupal::currentUser()->getRoles()) {
$view->removeHandler($display_id, 'field', 'field_machine_name');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment