class PermissionsForm in Filter Permissions 8
Provides an enhanced user permissions administration form.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\user\Form\UserPermissionsForm
- class \Drupal\filter_perms\Form\PermissionsForm
- class \Drupal\user\Form\UserPermissionsForm
Expanded class hierarchy of PermissionsForm
File
- src/
Form/ PermissionsForm.php, line 16
Namespace
Drupal\filter_perms\FormView source
class PermissionsForm extends UserPermissionsForm {
/**
* Indicates that all options should be user for filter.
*/
const ALL_OPTIONS = '-1';
/**
* The expirable key value store.
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
*/
protected $keyValueExpirable;
/**
* Constructs a new PermissionsForm.
*
* @param \Drupal\user\PermissionHandlerInterface $permission_handler
* The permission handler.
* @param \Drupal\user\RoleStorageInterface $role_storage
* The role storage.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface $key_value_expirable
* The key value expirable factory.
*/
public function __construct(PermissionHandlerInterface $permission_handler, RoleStorageInterface $role_storage, ModuleHandlerInterface $module_handler, KeyValueStoreExpirableInterface $key_value_expirable) {
parent::__construct($permission_handler, $role_storage, $module_handler);
$this->keyValueExpirable = $key_value_expirable;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('user.permissions'), $container
->get('entity_type.manager')
->getStorage('user_role'), $container
->get('module_handler'), $container
->get('keyvalue.expirable')
->get('filter_perms_list'));
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Render role/permission overview:
$hide_descriptions = system_admin_compact_mode();
$form['system_compact_link'] = [
'#id' => FALSE,
'#type' => 'system_compact_link',
];
$permissions = $this->permissionHandler
->getPermissions();
$providers = [];
foreach ($permissions as $permission) {
$providers[$permission['provider']] = $permission['provider'];
}
$roles = $this
->getRoles();
$defined_roles = [];
foreach ($roles as $role_name => $role) {
$defined_roles[$role_name] = $role
->label();
}
$filter = $this
->getFilterSettings();
$form['filters'] = [
'#type' => 'details',
'#title' => $this
->t('Permission Filters'),
'#open' => TRUE,
];
$form['filters']['container'] = [
'#type' => 'container',
'#attributes' => [
'class' => [
'form--inline',
'clearfix',
],
],
];
// Displays all user roles.
$form['filters']['container']['roles'] = [
'#title' => $this
->t('Roles to display'),
'#type' => 'select',
'#options' => [
self::ALL_OPTIONS => '--All Roles',
] + $defined_roles,
'#default_value' => $filter['roles'],
'#size' => 8,
'#multiple' => TRUE,
];
// Displays all modules which define permissions.
$form['filters']['container']['modules'] = [
'#title' => $this
->t('Modules to display'),
'#type' => 'select',
'#options' => [
self::ALL_OPTIONS => '--All Modules',
] + $providers,
'#default_value' => $filter['modules'],
'#size' => 8,
'#multiple' => TRUE,
];
$form['filters']['action'] = [
'#type' => 'actions',
];
$form['filters']['action']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Filter Permissions'),
'#submit' => [
'::submitFormFilter',
],
];
$role_names = $role_permissions = $admin_roles = [];
foreach ($roles as $role_name => $role) {
if (in_array(self::ALL_OPTIONS, $filter['roles']) || in_array($role_name, $filter['roles'])) {
// Retrieve role names for columns.
$role_names[$role_name] = $role
->label();
// Fetch permissions for the roles.
$role_permissions[$role_name] = $role
->getPermissions();
$admin_roles[$role_name] = $role
->isAdmin();
}
}
// Store $role_names for use when saving the data.
$form['role_names'] = [
'#type' => 'value',
'#value' => $role_names,
];
$permissions_by_provider = [];
foreach ($permissions as $permission_name => $permission) {
if (in_array(self::ALL_OPTIONS, $filter['modules']) || in_array($permission['provider'], $filter['modules'])) {
$permissions_by_provider[$permission['provider']][$permission_name] = $permission;
}
}
$form['permissions'] = [
'#type' => 'table',
'#header' => [
$this
->t('Permission'),
],
'#id' => 'permissions',
'#attributes' => [
'class' => [
'permissions',
'js-permissions',
],
],
'#sticky' => TRUE,
'#empty' => $this
->t('Please select at least one value from both the Roles and Modules select boxes above and then click the "Filter Permissions" button.'),
];
// Only build the rest of the form if there are any filter settings.
if (empty($role_names) || empty($permissions_by_provider)) {
return $form;
}
foreach ($role_names as $role_id => $role_name) {
$form['permissions']['#header'][] = [
'data' => $role_name,
'class' => [
'checkbox',
],
];
// Handles problems with $form_state losing track of roles when multiple tabs are loaded and submitted
$form['permissions']['displayed_roles'][$role_id] = [
'#type' => 'hidden',
'#value' => $role_name,
];
}
// Count inputs to avoid exceeding max_input_vars.
$input_count = count($form['filters']['container']['modules']['#options']) + count($form['filters']['container']['roles']['#options']);
foreach ($permissions_by_provider as $provider => $permissions) {
// Module name.
$form['permissions'][$provider] = [
[
'#wrapper_attributes' => [
'colspan' => count($role_names) + 1,
'class' => [
'module',
],
'id' => 'module-' . $provider,
],
'#markup' => $this->moduleHandler
->getName($provider),
],
];
foreach ($permissions as $perm => $perm_item) {
// Fill in default values for the permission.
$perm_item += [
'description' => '',
'restrict access' => FALSE,
'warning' => !empty($perm_item['restrict access']) ? $this
->t('Warning: Give to trusted roles only; this permission has security implications.') : '',
];
$form['permissions'][$perm]['description'] = [
'#type' => 'inline_template',
'#template' => '<div class="permission"><span class="title">{{ title }}</span>{% if description or warning %}<div class="description">{% if warning %}<em class="permission-warning">{{ warning }}</em> {% endif %}{{ description }}</div>{% endif %}</div>',
'#context' => [
'title' => $perm_item['title'],
],
];
// Show the permission description.
if (!$hide_descriptions) {
$form['permissions'][$perm]['description']['#context']['description'] = $perm_item['description'];
$form['permissions'][$perm]['description']['#context']['warning'] = $perm_item['warning'];
}
foreach ($role_names as $rid => $name) {
$form['permissions'][$perm][$rid] = [
'#title' => $name . ': ' . $perm_item['title'],
'#title_display' => 'invisible',
'#wrapper_attributes' => [
'class' => [
'checkbox',
],
],
'#type' => 'checkbox',
'#default_value' => in_array($perm, $role_permissions[$rid]) ? 1 : 0,
'#attributes' => [
'class' => [
'rid-' . $rid,
'js-rid-' . $rid,
],
],
'#parents' => [
$rid,
$perm,
],
];
// Show a column of disabled but checked checkboxes.
if ($admin_roles[$rid]) {
$form['permissions'][$perm][$rid]['#disabled'] = TRUE;
$form['permissions'][$perm][$rid]['#default_value'] = TRUE;
}
else {
$input_count++;
}
}
}
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Save permissions'),
'#button_type' => 'primary',
];
// Count the form token, id, and build_id, as well as the two submits.
$input_count += 5;
if (empty($form_state
->getUserInput()) && $input_count > ini_get('max_input_vars')) {
$form['actions']['submit']['#disabled'] = TRUE;
$form['actions']['submit']['#value'] = $this
->t('Saving permissions disabled');
$this
->messenger()
->addError($this
->t('There are too many permissions to be saved safely with your current PHP configuration. Please filter the permissions.'));
}
$form['#attached']['library'][] = 'user/drupal.user.permissions';
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$submit_button = $form_state
->getTriggeringElement();
// no need to run this validation when submitting filter changes
if ($submit_button['#value']
->render() == 'Save permissions') {
$submitted_roles = $form_state
->getValue('role_names');
$permissions_form = $form_state
->getValue('permissions');
// check that the $form_state has not been updated since creation of this submitted form
if (count(array_diff($permissions_form['displayed_roles'], $submitted_roles))) {
$form_state
->setError($form['filters']['container']['roles'], t('The submitted form contains outdated permissions checkboxes and has not been saved. Please re-filter and try again.'));
}
}
}
/**
* Saves the roles and modules selection.
*/
public function submitFormFilter(array &$form, FormStateInterface $form_state) {
$this
->saveFilterSettings($form_state
->getValue('roles'), $form_state
->getValue('modules'));
}
/**
* Saves the filter settings for the current user.
*
* @param array $roles
* The roles to filter by.
* @param array $modules
* The modules to filter by.
*/
protected function saveFilterSettings(array $roles, array $modules) {
$values = [
'roles' => $roles,
'modules' => $modules,
];
$this->keyValueExpirable
->setWithExpire($this
->currentUser()
->id(), $values, 3600);
}
/**
* Retrieve the filter settings for the current user.
*
* @return array
* The filter setting for the current user.
*/
protected function getFilterSettings() {
$default = [
'roles' => [],
'modules' => [],
];
return $this->keyValueExpirable
->get($this
->currentUser()
->id(), $default);
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PermissionsForm:: |
protected | property | The expirable key value store. | |
PermissionsForm:: |
constant | Indicates that all options should be user for filter. | ||
PermissionsForm:: |
public | function |
Form constructor. Overrides UserPermissionsForm:: |
1 |
PermissionsForm:: |
public static | function |
Instantiates a new instance of this class. Overrides UserPermissionsForm:: |
|
PermissionsForm:: |
protected | function | Retrieve the filter settings for the current user. | |
PermissionsForm:: |
protected | function | Saves the filter settings for the current user. | |
PermissionsForm:: |
public | function | Saves the roles and modules selection. | |
PermissionsForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
PermissionsForm:: |
public | function |
Constructs a new PermissionsForm. Overrides UserPermissionsForm:: |
|
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. | |
UserPermissionsForm:: |
protected | property | The module handler. | |
UserPermissionsForm:: |
protected | property | The permission handler. | |
UserPermissionsForm:: |
protected | property | The role storage. | |
UserPermissionsForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
UserPermissionsForm:: |
protected | function | Gets the roles to display in this form. | 1 |
UserPermissionsForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |