5 * Dummy module implementing hook_user_access() to test if entity access is respected.
8 use Drupal\Core\Access\AccessResult;
9 use Drupal\Core\Field\FieldDefinitionInterface;
10 use Drupal\Core\Field\FieldItemListInterface;
11 use Drupal\Core\Session\AccountInterface;
12 use Drupal\user\Entity\User;
15 * Implements hook_ENTITY_TYPE_access() for entity type "user".
17 function user_access_test_user_access(User $entity, $operation, $account) {
18 if ($entity->getUsername() == "no_edit" && $operation == "update") {
20 return AccessResult::forbidden();
22 if ($entity->getUsername() == "no_delete" && $operation == "delete") {
23 // Deny delete access.
24 return AccessResult::forbidden();
26 return AccessResult::neutral();
30 * Implements hook_entity_field_access().
32 function user_access_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
33 // Account with role sub-admin can view the status, init and mail fields for user with no roles.
34 if ($operation === 'view' && in_array($field_definition->getName(), ['status', 'init', 'mail'])) {
35 if (($items == NULL) || (count($items->getEntity()->getRoles()) == 1)) {
36 return AccessResult::allowedIfHasPermission($account, 'sub-admin');
39 return AccessResult::neutral();