function FormOperations::formAlter

Same name and namespace in other branches
  1. 10 core/modules/workspaces/src/FormOperations.php \Drupal\workspaces\FormOperations::formAlter()
  2. 9 core/modules/workspaces/src/FormOperations.php \Drupal\workspaces\FormOperations::formAlter()
  3. 8.9.x core/modules/workspaces/src/FormOperations.php \Drupal\workspaces\FormOperations::formAlter()

Implements hook_form_alter().

Attributes

#[Hook('form_alter')]

File

core/modules/workspaces/src/Hook/FormOperations.php, line 30

Class

FormOperations
Defines a class for reacting to form operations.

Namespace

Drupal\workspaces\Hook

Code

public function formAlter(array &$form, FormStateInterface $form_state, $form_id) : void {
  $active_workspace = $this->workspaceManager
    ->getActiveWorkspace();
  // Ensure that the form's initial workspace (if any) is used for the current
  // request.
  $form_workspace_id = $form_state->getUserInput()['active_workspace_id'] ?? NULL;
  $form_workspace = $form_workspace_id ? Workspace::load($form_workspace_id) : NULL;
  if ($form_workspace && (!$active_workspace || $active_workspace->id() != $form_workspace->id())) {
    $this->workspaceManager
      ->setActiveWorkspace($form_workspace, FALSE);
    $active_workspace = $form_workspace;
  }
  // No alterations are needed if we're not in a workspace context.
  if (!$active_workspace) {
    return;
  }
  // If a form hasn't already been marked as safe or not to submit in a
  // workspace, check the generic interfaces.
  if (!$form_state->has('workspace_safe')) {
    $form_object = $form_state->getFormObject();
    $workspace_safe = $form_object instanceof WorkspaceSafeFormInterface || $form_object instanceof WorkspaceDynamicSafeFormInterface && $form_object->isWorkspaceSafeForm($form, $form_state);
    $form_state->set('workspace_safe', $workspace_safe);
  }
  // Add a validation step for every other form.
  if ($form_state->get('workspace_safe') !== TRUE) {
    $form['workspace_safe'] = [
      '#type' => 'value',
      '#value' => FALSE,
    ];
    $this->addWorkspaceValidation($form);
  }
  else {
    // Persist the active workspace for the entire lifecycle of the form,
    // including AJAX requests.
    $form['active_workspace_id'] = [
      '#type' => 'hidden',
      '#value' => $active_workspace->id(),
    ];
    $url_query_options = $this->queryParameterNegotiator
      ->getQueryOptions($active_workspace->id());
    $this->setAjaxWorkspace($form, $url_query_options + [
      'persist' => FALSE,
    ]);
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.