簡體   English   中英

如何在 Drupal 8 中以編程方式創建角色?

[英]How to create a role programmatically in Drupal 8?

如何在 Drupal 8 中以編程方式創建角色?

我在這里做錯了什么?

$role = \Drupal\user\Entity\Role::create(['id' => 'client', 'name' => 'Client']);
$role->save(); 

問題在於數據數組按標簽更改名稱

$role = \Drupal\user\Entity\Role::create(array('id' => 'client', 'label' => 'Client'));
$role->save(); 

或者您可以使用:

//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

就我而言,我希望能夠自動創建多個角色(“客戶”、“經理”、“銷售代表”)來使用我的自定義模塊。

這就是我在 Drupal 9 中以編程方式自動創建角色的方式。

mycustommodule/mycustommodule.module

use Drupal\user\Entity\Role;

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 上測試通過

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM