如何在Drupal 8中以编程方式创建角色?
我在这里做错了什么?
$role = DrupaluserEntityRole::create(['id' => 'client', 'name' => 'Client']);
$role->save();
问题在于数据数组通过标签更改名称:
$role = DrupaluserEntityRole::create(array('id' => 'client', 'label' => 'Client'));
$role->save();
或者你可以使用:
//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = DrupaluserEntityRole::create($data);
//saving your role
$role->save();
在我的案例中,我希望能够自动创建多个角色("客户"、"经理"、"销售代表")来使用我的自定义模块。
这就是我在Drupal9中以编程方式自动创建角色的方式。
mycustommodule/mycustommodule.module
use DrupaluserEntityRole;
function mycustommodule_install() {
//Get all available roles
$get_all_roles=Role::loadMultiple();
//these are the required roles
$required_roles=array("clients","managers","salesrep");
//check if is not already created , create each role
foreach($required_roles as $the_role){
if(!isset($get_all_roles[$the_role])){
$role = Role::create(array('id' => $the_role, 'label' => ucwords($the_role)));
$role->save();
}
}
//
}
Drupal 9.4.2版测试通过