In Drupal 8, how do I give access to some nodes to users with specific roles, depending on a field value or a taxonomy value?
1 Answer
this is how i did it ( simplified for demo purpose )
function my_module_node_access(NodeInterface $node, $op, AccountInterface $account) {
global $user;
$user = \Drupal\user\Entity\User::load($account->id());
if ($node->bundle() == 'my_content_type') {
if ($op == 'view') {
$visibility=$node->field_visibilite->getString();
$target=$node->field_target->getString();
if ($visibility ==='all')
return \Drupal\Core\Access\AccessResult::allowed();
if ($visibility ==='restricted')
if (($target === 'group1') && ($user->hasRole('group1')))
return \Drupal\Core\Access\AccessResult::allowed();
}
return \Drupal\Core\Access\AccessResult::forbidden();
}