You are here

public function EntityReferenceActionsHandler::submitForm in Entity reference actions 1.x

Submit function to call the action.

Parameters

array $form: The form.

\Drupal\Core\Form\FormStateInterface $form_state: The form state.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

src/EntityReferenceActionsHandler.php, line 226

Class

EntityReferenceActionsHandler
Provides the form functions to call actions on referenced entities.

Namespace

Drupal\entity_reference_actions

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $button = $form_state
    ->getTriggeringElement();
  $parents = array_slice($button['#array_parents'], 0, -2);

  // The field name we are acting on, deep from the form structure.
  $field_name = end($parents);
  $parents = array_slice($parents, 0, -1);
  $values = NestedArray::getValue($form, $parents);
  $context = $form_state
    ->get($values[$field_name]['entity_reference_actions']['#uuid']);

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  $items = $context['items'];
  $context['widget']
    ->extractFormValues($items, $values, $form_state);
  $action = $this->actions[end($button['#array_parents'])];
  $ids = array_filter(!$items
    ->isEmpty() ? array_column($items
    ->getValue(), 'target_id') : []);
  $entities = $this->entityTypeManager
    ->getStorage($items
    ->getSettings()['target_type'])
    ->loadMultiple($ids);
  $commands = [];
  $entities = array_filter($entities, function ($entity) use ($action, &$commands) {
    if (!$action
      ->getPlugin()
      ->access($entity, $this->currentUser)) {
      $commands[] = new MessageCommand($this
        ->t('No access to execute %action on the @entity_type_label %entity_label.', [
        '%action' => $action
          ->label(),
        '@entity_type_label' => $entity
          ->getEntityType()
          ->getLabel(),
        '%entity_label' => $entity
          ->label(),
      ]), '[data-entity-reference-actions-messages]', [
        'type' => 'warning',
      ], FALSE);
      return FALSE;
    }
    return TRUE;
  });
  $response = new AjaxResponse();
  if ($entities) {
    $dialog_options = [
      'minHeight' => '75%',
      'maxHeight' => '75%',
      'width' => '75%',
    ];
    $operation_definition = $action
      ->getPluginDefinition();
    if (!empty($operation_definition['confirm_form_route_name'])) {
      $action
        ->getPlugin()
        ->executeMultiple($entities);
      $request = $this->requestStack
        ->getCurrentRequest();
      $dialog_url = Url::fromRoute($operation_definition['confirm_form_route_name'], [
        MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_modal',
      ])
        ->toString(TRUE);
      $parameter = [
        'ajax_page_state' => $request->request
          ->get('ajax_page_state'),
        'dialogOptions' => $dialog_options,
      ];
      $sub_request = Request::create($dialog_url
        ->getGeneratedUrl(), 'POST', $parameter, [], [], $request->server
        ->all());
      if ($request
        ->getSession()) {
        $sub_request
          ->setSession($request
          ->getSession());
      }

      /** @var \Drupal\Core\Ajax\AjaxResponse $response */
      $response = $this->httpKernel
        ->handle($sub_request, HttpKernelInterface::SUB_REQUEST);

      // We have to clear the response data, otherwise the new commands will
      // not be returned.
      $response
        ->setContent("{}");
    }
    else {
      $batch_builder = (new BatchBuilder())
        ->setTitle($this
        ->getActionLabel($action))
        ->setFinishCallback([
        __CLASS__,
        'batchFinish',
      ]);
      foreach ($entities as $entity) {
        $batch_builder
          ->addOperation([
          __CLASS__,
          'batchCallback',
        ], [
          $entity
            ->id(),
          $entity
            ->getEntityTypeId(),
          $action
            ->id(),
        ]);
      }
      batch_set($batch_builder
        ->toArray());
      batch_process();
      require_once DRUPAL_ROOT . '/core/includes/batch.inc';
      $batch_page = _batch_progress_page();
      $batch_page['#attached']['library'] = [
        'entity_reference_actions/batch',
      ];
      $response
        ->addCommand(new OpenModalDialogCommand($this
        ->getActionLabel($action), $batch_page, $dialog_options));
    }
  }
  else {
    $entity_type = $this->entityTypeManager
      ->getDefinition($this->entityTypeId);
    $commands[] = new MessageCommand($this
      ->t('No @entity_type_label selected.', [
      '@entity_type_label' => $entity_type
        ->getPluralLabel(),
    ]), '[data-entity-reference-actions-messages]', [
      'type' => 'warning',
    ]);
  }

  // Attach existing commands.
  foreach ($commands as $command) {
    $response
      ->addCommand($command);
  }
  return $response;
}