Writing in here, since its a faux paux to link to blog articles.
In your permissions.yml file of your module, you can define a permissions callback like so:
permission_callbacks:
- Drupal\mymodule\MyModulePermissions::permissions
Then in your MyModulePermissions
class:
namespace Drupal\mymodule;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyModulePermissions implements ContainerInjectionInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructor for MyModulePermissions.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('entity_type.manager'));
}
/**
* Get permissions for MyModule.
*
* @return array
* Permissions array.
*/
public function permissions() {
$permissions = [];
foreach ($this->entityTypeManager->getStorage('myentity')->loadMultiple() as $type) {
$permissions += [
'create ... ' . $type->bundle() => [
'title' => $this->t('Allow creation of %type', array('%type' => $type->label())),
]
];
$permissions += [
'update ... ' . $type->bundle() => [
'title' => $this->t('Allow update of %type', array('%type' => $type->label())),
]
];
$permissions += [
'delete ... ' . $type->bundle() => [
'title' => $this->t('Allow deletion of %type', array('%type' => $type->label())),
]
];
}
return $permissions;
}
}
Something like that. Code is untested. This will loop through and create CRUD permissions for each bundle.