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"
$role->grantPermission()
? See drupal.stackexchange.com/questions/267623/…