Skip to content

Instantly share code, notes, and snippets.

@jkcox
Last active June 30, 2021 22:51
Show Gist options
  • Save jkcox/e44be6b0a564924dc3b1518957217d7e to your computer and use it in GitHub Desktop.
Save jkcox/e44be6b0a564924dc3b1518957217d7e to your computer and use it in GitHub Desktop.
Drupal 8 Webform custom module: create hook: Apply webform creator roles to webform
<?php
use Drupal\webform\WebformInterface;
function my_module_name_webform_create(WebformInterface $webform) {
$user = \Drupal::currentUser();
$roles = $user->getRoles();
//remove global roles
if (($role = array_search('role_to_remove', $roles)) !== false) {
unset($roles[$role]);
}
//see if user still has roles to apply
//if array not empty apply webform acesss settings
if ($roles) {
//reset array values, PHP to YAML will break syntax if array is not index 0
$roles = array_values($roles);
$access = [
'create' => ['roles' => [0 => 'anonymous', 1 => 'authenticated'],'users' => [],'permissions' => [],],
'view_any' => ['roles' => [],'users' => [],'permissions' => [],],
'update_any' => ['roles' => [],'users' => [],'permissions' => [],],
'delete_any' => ['roles' => [],'users' => [],'permissions' => [],],
'purge_any' => ['roles' => [],'users' => [],'permissions' => [],],
'view_own' => ['roles' => [],'users' => [],'permissions' => [],],
'update_own' => ['roles' => [],'users' => [],'permissions' => [],],
'delete_own' => ['roles' => [],'users' => [],'permissions' => [],],
'administer' => ['roles' => [],'users' => [],'permissions' => [],],
'test' => ['roles' => [],'users' => [],'permissions' => [],],
'configuration' => ['roles' => [],'users' => [],'permissions' => [],],
];
foreach($roles as $key => $remaining_roles) {
//apply user role to administer
$access['administer']['roles'][$key] = $remaining_roles;
}
$webform_set_access_rules = $webform->setAccessRules($access);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment