0

I have a new role as "Publisher". I want to grant Publisher 'create' and 'update' permission using code.

My .permissions.yml file looks like this :

'delete contact entity':
  title: Delete entity content.
'add contact entity':
  title: Add entity content
'view contact entity':
  title: View entity content
'edit contact entity':
  title: Edit entity content
'administer contact entity':
  title: Administer settings
'publisher contact entity':
  title: Publisher settings


I've used 2 functions to allow permissions. The functions are:

 protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
// Check the admin_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
switch ($operation) {
  case 'edit':
    return AccessResult::allowedIfHasPermission($account, 'edit contact entity');

  case 'update':
    return AccessResult::allowedIfHasPermission($account, 'update contact entity');
}
return AccessResult::neutral();  }


protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Check the publisher_permission as defined in your @ContentEntityType
// annotation.
$publisher_permission = $this->entityType->getPublisherPermission();
if ($account->hasPermission($publisher_permission)) {
  return AccessResult::allowed();
}
return AccessResult::allowedIfHasPermission($account, 'edit contact entity');   }

Now, If check sitename/admin/people/permissions, the role is created by it doesn't have a tick in the checkbox for edit contact entity.

PS: In @ContentEntityType, I've defined publisher permission as:

publisher_permission = "publisher contact entity"
0

You may grant your permissions on install time of your module with a simple config in config/install/user.role.publisher.yml (about this):

langcode: en
status: true
dependencies: {  }
id: publisher
label: Publisher
weight: 3
is_admin: null
permissions:
  - 'add contact entity'
  - 'edit contect entity'

Your code above is not a "grant", it's a runtime-check of users permissions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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