FormAlterHelper.php in Workbench Access 8
File
src/FormAlterHelper.php
View source
<?php
namespace Drupal\workbench_access;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FormAlterHelper implements ContainerInjectionInterface {
protected $entityTypeManager;
protected $currentUser;
public function __construct(EntityTypeManagerInterface $entityTypeManager, AccountInterface $currentUser) {
$this->entityTypeManager = $entityTypeManager;
$this->currentUser = $currentUser;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('current_user'));
}
public function alterForm(array &$element, array &$complete_form, FormStateInterface &$form_state, ContentEntityInterface $entity) {
$callback = FALSE;
if (empty($entity)) {
$entity = $form_state
->getFormObject()
->getEntity();
}
foreach ($this->entityTypeManager
->getStorage('access_scheme')
->loadMultiple() as $access_scheme) {
$scheme = $access_scheme
->getAccessScheme();
if (!$scheme
->applies($entity
->getEntityTypeId(), $entity
->bundle())) {
continue;
}
$callback = TRUE;
if (!$this->currentUser
->hasPermission('bypass workbench access')) {
$scheme
->alterForm($access_scheme, $element, $form_state, $entity);
if (!isset($complete_form['workbench_access_disallowed'])) {
$complete_form['workbench_access_disallowed'] = [
'#tree' => TRUE,
];
}
$fields = $scheme
->getApplicableFields($entity
->getEntityTypeId(), $entity
->bundle());
foreach ($fields as $info) {
if (isset($complete_form[$info['field']])) {
$lookup_element = $complete_form[$info['field']];
$options_diff = $scheme
->disallowedOptions($lookup_element);
if (!empty($options_diff) && !isset($complete_form['workbench_access_disallowed'][$info['field']])) {
$complete_form['workbench_access_disallowed'][$info['field']] = [
$access_scheme
->id() => [
'#type' => 'value',
'#value' => $options_diff,
],
];
}
}
}
}
}
if ($callback) {
$class = AccessControlHierarchyBase::class . '::submitEntity';
$buttons = [
'submit',
'publish',
'unpublish',
];
foreach ($buttons as $button) {
if (isset($complete_form['actions'][$button]['#submit'])) {
array_unshift($complete_form['actions'][$button]['#submit'], $class);
}
}
}
return $element;
}
}