How to grant create and update permissions to a custom role?

by Aman Devrath   Last Updated September 11, 2019 07:07 AM - source

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"
Tags : users hooks


Answers 1


I'm guessing it's because you've formatted your .yml permissions incorrectly. They most likely need to be 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'

Make sure to clear your cache after making the changes.

Jaypan
Jaypan
September 11, 2019 06:47 AM

Related Questions


Drupal 6 login attempts user block

Updated August 20, 2017 22:07 PM

hook_user_insert not working

Updated May 10, 2016 08:03 AM

Login success but logout fails Drupal 7

Updated May 30, 2016 08:03 AM


Embed user edit form in block? Drupal 7

Updated January 07, 2019 13:07 PM