You are here

public function EntityFlagActionForm::submitForm in farmOS 2.x

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

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

Overrides FormInterface::submitForm

File

modules/core/flag/src/Form/EntityFlagActionForm.php, line 203

Class

EntityFlagActionForm
Provides an entity flag action form.

Namespace

Drupal\farm_flag\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {

  // Filter out entities the user doesn't have access to.
  $inaccessible_entities = [];
  $accessible_entities = [];
  foreach ($this->entities as $entity) {
    if (!$entity
      ->access('update', $this
      ->currentUser())) {
      $inaccessible_entities[] = $entity;
      continue;
    }
    $accessible_entities[] = $entity;
  }

  // Update flags on accessible entities.
  $total_count = 0;
  foreach ($accessible_entities as $entity) {

    /** @var \Drupal\Core\Field\FieldItemListInterface $flag_field */
    if ($flag_field = $entity
      ->get($this->flagFieldName)) {

      // Save existing flags if appending.
      $existing_flags = [];
      if ($form_state
        ->getValue('operation') === 'append') {
        $existing_flags = array_column($flag_field
          ->getValue(), 'value');
      }

      // Empty the flag field.
      $flag_field
        ->setValue([]);
      $new_flags = array_unique(array_merge($existing_flags, $form_state
        ->getValue('flags')));
      foreach ($new_flags as $flag) {
        $flag_field
          ->appendItem($flag);
      }
      $entity
        ->save();
      $total_count++;
    }
  }

  // Add warning message for inaccessible entities.
  if (!empty($inaccessible_entities)) {
    $inaccessible_count = count($inaccessible_entities);
    $this
      ->messenger()
      ->addWarning($this
      ->formatPlural($inaccessible_count, 'Could not flag @count @item because you do not have the necessary permissions.', 'Could not flag @count @items because you do not have the necessary permissions.', [
      '@item' => $this->entityType
        ->getSingularLabel(),
      '@items' => $this->entityType
        ->getPluralLabel(),
    ]));
  }

  // Add confirmation message.
  if (!empty($total_count)) {
    $this
      ->messenger()
      ->addStatus($this
      ->formatPlural($total_count, 'Flagged @count @item.', 'Flagged @count @items', [
      '@item' => $this->entityType
        ->getSingularLabel(),
      '@items' => $this->entityType
        ->getPluralLabel(),
    ]));
  }
  $this->tempStore
    ->delete($this
    ->currentUser()
    ->id() . ':' . $this->entityType
    ->id());
  $form_state
    ->setRedirectUrl($this
    ->getCancelUrl());
}