FormOperations.php in Drupal 9
File
core/modules/workspaces/src/FormOperations.php
View source
<?php
namespace Drupal\workspaces;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\views\Form\ViewsExposedForm;
use Drupal\workspaces\Form\WorkspaceFormInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FormOperations implements ContainerInjectionInterface {
protected $workspaceManager;
public function __construct(WorkspaceManagerInterface $workspace_manager) {
$this->workspaceManager = $workspace_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('workspaces.manager'));
}
public function formAlter(array &$form, FormStateInterface $form_state, $form_id) {
if (!$this->workspaceManager
->hasActiveWorkspace()) {
return;
}
$this
->addWorkspaceValidation($form);
if ($form_state
->has('workspace_safe')) {
return;
}
$workspace_safe = FALSE;
$form_object = $form_state
->getFormObject();
$is_workspace_form = $form_object instanceof WorkspaceFormInterface;
$is_search_form = in_array($form_object
->getFormId(), [
'search_block_form',
'search_form',
], TRUE);
$is_views_exposed_form = $form_object instanceof ViewsExposedForm;
if ($is_workspace_form || $is_search_form || $is_views_exposed_form) {
$workspace_safe = TRUE;
}
$form_state
->set('workspace_safe', $workspace_safe);
}
protected function addWorkspaceValidation(array &$element) {
foreach (Element::children($element) as $key) {
if (isset($element[$key]) && $element[$key]) {
$this
->addWorkspaceValidation($element[$key]);
}
}
if (isset($element['#validate'])) {
$element['#validate'][] = [
static::class,
'validateDefaultWorkspace',
];
}
}
public static function validateDefaultWorkspace(array &$form, FormStateInterface $form_state) {
if ($form_state
->get('workspace_safe') !== TRUE) {
$form_state
->setError($form, new TranslatableMarkup('This form can only be submitted in the default workspace.'));
}
}
}