You are here

public function LogAssignActionForm::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/owner/src/Form/LogAssignActionForm.php, line 184

Class

LogAssignActionForm
Provides a log assign confirmation form.

Namespace

Drupal\farm_owner\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 user assignment on accessible entities.
  $total_count = 0;
  foreach ($accessible_entities as $entity) {

    /** @var \Drupal\Core\Field\FieldItemListInterface $owner_field */
    if ($owner_field = $entity
      ->get('owner')) {

      // Save existing users if appending.
      $existing_owners = [];
      if ($form_state
        ->getValue('operation') === 'append') {
        $existing_owners = array_column($owner_field
          ->getValue(), 'target_id');
      }

      // Empty the owner field.
      $owner_field
        ->setValue([]);

      // Build list of owners.
      $new_owners = array_unique(array_merge($existing_owners, $form_state
        ->getValue('users')));
      foreach ($new_owners as $owner) {
        $owner_field
          ->appendItem($owner);
      }
      $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 update assignment of @count @item because you do not have the necessary permissions.', 'Could not update assignment of @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, 'Updated assignment of @count @item.', 'Updated assignment of @count @items', [
      '@item' => $this->entityType
        ->getSingularLabel(),
      '@items' => $this->entityType
        ->getPluralLabel(),
    ]));
  }
  $this->tempStore
    ->delete($this
    ->currentUser()
    ->id());
  $form_state
    ->setRedirectUrl($this
    ->getCancelUrl());
}