View source
<?php
namespace Drupal\workbench_access\Form;
use Drupal\workbench_access\Entity\AccessSchemeInterface;
use Drupal\workbench_access\RoleSectionStorageInterface;
use Drupal\workbench_access\WorkbenchAccessManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class WorkbenchAccessByRoleForm extends FormBase {
protected $manager;
protected $roleSectionStorage;
protected $scheme;
public function __construct(WorkbenchAccessManagerInterface $manager, RoleSectionStorageInterface $role_section_storage) {
$this->manager = $manager;
$this->roleSectionStorage = $role_section_storage;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.workbench_access.scheme'), $container
->get('workbench_access.role_section_storage'));
}
public function getFormId() {
return 'workbench_access_by_role';
}
public function buildForm(array $form, FormStateInterface $form_state, AccessSchemeInterface $access_scheme = NULL, $id = NULL) {
$this->scheme = $access_scheme;
$existing_roles = $this->roleSectionStorage
->getRoles($access_scheme, $id);
$potential_roles = $this->roleSectionStorage
->getPotentialRolesFiltered($id);
$form['existing_roles'] = [
'#type' => 'value',
'#value' => $existing_roles,
];
$form['section_id'] = [
'#type' => 'value',
'#value' => $id,
];
if (!$existing_roles) {
$text = $this
->t('There are no roles assigned to the %label section.', [
'%label' => $access_scheme
->label(),
]);
$form['help'] = [
'#type' => 'markup',
'#markup' => '<p>' . $text . '</p>',
];
}
if ($potential_roles) {
$form['roles'] = [
'#title' => $this
->t('Roles for the %label section.', [
'%label' => $access_scheme
->label(),
]),
'#type' => 'checkboxes',
'#options' => $potential_roles,
'#default_value' => $existing_roles,
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
}
if (count($potential_roles) == count($existing_roles)) {
$form['message'] = [
'#type' => 'markup',
'#markup' => '<p>' . $this
->t('There are no additional roles that can be added to the %label section', [
'%label' => $access_scheme
->label(),
]) . '</p>',
];
}
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$roles = $form_state
->getValue('roles');
$existing_roles = $form_state
->getValue('existing_roles');
$id = $form_state
->getValue('section_id');
foreach ($roles as $role_id => $value) {
if ($value === $role_id) {
$this->roleSectionStorage
->addRole($this->scheme, $role_id, [
$id,
]);
}
else {
$this->roleSectionStorage
->removeRole($this->scheme, $role_id, [
$id,
]);
}
}
\Drupal::messenger()
->addMessage($this
->t('Role assignments updated.'));
}
public function pageTitle(AccessSchemeInterface $access_scheme, $id) {
return $this
->t('Roles assigned to %label', [
'%label' => $access_scheme
->label(),
]);
}
}