You are here

public function EditQuantity::viewsFormSubmit in Commerce Core 8.2

Submit handler for the views form.

Parameters

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

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

File

modules/cart/src/Plugin/views/field/EditQuantity.php, line 238

Class

EditQuantity
Defines a form element for editing the order item quantity.

Namespace

Drupal\commerce_cart\Plugin\views\field

Code

public function viewsFormSubmit(array &$form, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();
  if (empty($triggering_element['#update_cart'])) {

    // Don't run when the "Remove" or "Empty cart" buttons are pressed.
    return;
  }
  $order_storage = $this->entityTypeManager
    ->getStorage('commerce_order');

  /** @var \Drupal\commerce_order\Entity\OrderInterface $cart */
  $cart = $order_storage
    ->load($this->view->argument['order_id']
    ->getValue());
  $quantities = $form_state
    ->getValue($this->options['id'], []);
  $save_cart = FALSE;
  foreach ($quantities as $row_index => $quantity) {
    if (!is_numeric($quantity) || $quantity < 0) {

      // The input might be invalid if the #required or #min attributes
      // were removed by an alter hook.
      continue;
    }

    /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
    $order_item = $this
      ->getEntity($this->view->result[$row_index]);
    if ($order_item
      ->getQuantity() == $quantity) {

      // The quantity hasn't changed.
      continue;
    }
    if ($quantity > 0) {
      $order_item
        ->setQuantity($quantity);
      $this->cartManager
        ->updateOrderItem($cart, $order_item, FALSE);
    }
    else {

      // Treat quantity "0" as a request for deletion.
      $this->cartManager
        ->removeOrderItem($cart, $order_item, FALSE);
    }
    $save_cart = TRUE;
  }
  if ($save_cart) {
    $cart
      ->save();
    if (!empty($triggering_element['#show_update_message'])) {
      $this->messenger
        ->addMessage($this
        ->t('Your shopping cart has been updated.'));
    }
  }
}