You are here

public function XquantityEditQuantity::viewsFormSubmit in Commerce Extended Quantity 8

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.

Overrides EditQuantity::viewsFormSubmit

File

src/Plugin/views/field/XquantityEditQuantity.php, line 120

Class

XquantityEditQuantity
Overrides a form element for editing the order item quantity.

Namespace

Drupal\commerce_xquantity\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;
  $form_object = $form_state
    ->getFormObject();
  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) {
      if ($purchased_entity = $order_item
        ->getPurchasedEntity()) {
        $order_item
          ->setQuantityPrices($form_object, $this, $form_state);
        if ($price = $order_item
          ->getQuantityPrice($form_object, $purchased_entity, $quantity)) {
          if (!$price
            ->equals($order_item
            ->getUnitPrice())) {
            $order_item
              ->setUnitPrice($price, TRUE);
          }
        }
      }
      $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.'));
    }
  }
}