Is there a way in Drupal 10 to programmatically check to see if the current logged in user can access the edit/create/view for each content type.
2 Answers
Use the the access manager service:
$access_manager = \Drupal::service('access_manager');
To check if the current user can edit a specific node:
$has_access = $access_manager->checkNamedRoute('entity.node.edit_form', ['node' => '1']);
Or can create a node for a specific content type:
$has_access = $access_manager->checkNamedRoute('node.add', ['node_type' => 'article']);
If you have the entity object you can use access method:
$currentUSer = \Drupal::currentUser();
// Check different access.
$hasEditAccess = $entity->access('edit', $currentUSer);
$hasViewAccess = $entity->access('view', $currentUSer);
$hasCreateAccess = $entity->access('create', $currentUSer);
Otherwise you can create your own access check function that takes entity type and bundle to, something like:
/**
* Check user access.
*
* @param string $operation
* The operation eg view|edit|create.
* @param string $bundle
* Bundle.
* @param string $entity_type_id
* Entity type.
* @param \Drupal\Core\Session\AccountInterface|NULL $account
* User account to check access.
*
* @return bool
*/
function checkUserAccess(string $operation = 'view', string $bundle = 'article', string $entity_type_id = 'node', AccountInterface $account = NULL): bool {
$account = $account ?: \Drupal::currentUser();
// Check if the user has the permission to apply operation of this type.
return $account->hasPermission("$operation any $bundle $entity_type_id");
}
and then you can check with something like:
checkUserAccess('create', 'page','node', account: $this->currentUser());
-
checkUserAccess()
assumes all entity types use permissions in the style of\Drupal\entity\EntityPermissionProvider
, it ignores admin permissions, and it ignores custom access alters.– AndyCommented Apr 29 at 19:12