2

This one feels like it should be obvious, but after some searching I'm having trouble finding a code example for checking whether a user has create access for an arbitrary entity.

In this case, I'm looking to pass an arbitrary entity type and bundle, in order to check whether a user has create access. This can be any entity type, including custom entities.

I have a sense that the end of the expression will be ->createAccess() , based on what I've read for the entity access interface classes, but where I'm stuck is finding the right class to call first, in order to get the entity information.

5
  • The permissions are stored on the user object so for example you propably want to do something like that. $user = \Drupal::currentUser(); $user->hasPermission('<permission name>');
    – DiDebru
    Sep 27, 2018 at 6:03
  • This is true, but different entities may have different permission names, and may have different permission nomenclature for bundles. I know that nodes have "create X content" format, but what about custom entities? For the module application (drupal.org/project/views_add_button), I don't think it will be practical to ask every developer to make a plugin to ensure compatibility.
    – Mike Nolan
    Sep 27, 2018 at 14:43
  • Have you tried api.drupal.org/api/drupal/… ?
    – DiDebru
    Sep 28, 2018 at 8:39
  • @Insasse I'm looking at the docs, and it looks like it might be possible to instantiate a base Entity class,and run ::access() on that. I'll try it.
    – Mike Nolan
    Sep 29, 2018 at 14:46
  • Making a note to reread this page, as it is relevant to the topic at hand: api.drupal.org/api/drupal/…
    – Mike Nolan
    Sep 29, 2018 at 16:26

1 Answer 1

3

OK, I have figured it out. Here's what I am using to get access for the current user (in the createAccess() step the second parameter can be an account, if you need to pass an account):

// Before this, you need to get the entity type and bundle,
// shown here as $entity_type and $bundle .
$entity_manager = \Drupal::entityTypeManager();
$access_handler = $entity_manager->getAccessControlHandler($entity_type);
$access = FALSE;
if ($bundle) {
  $access = $access_handler->createAccess($bundle);
}
else {
  $access = $access_handler->createAccess();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.