You are here

protected function ShipmentForm::addShippingItems in Commerce Shipping 8.2

Creates new shipping items from the form and adds them to the shipment.

Parameters

array $form: A nested array of form elements comprising the form.

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

2 calls to ShipmentForm::addShippingItems()
ShipmentForm::save in src/Form/ShipmentForm.php
Form submission handler for the 'save' action.
ShipmentForm::validateForm in src/Form/ShipmentForm.php
Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level…

File

src/Form/ShipmentForm.php, line 336

Class

ShipmentForm
Defines the shipment add/edit form.

Namespace

Drupal\commerce_shipping\Form

Code

protected function addShippingItems(array &$form, FormStateInterface $form_state) {

  /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
  $shipment = $this->entity;

  // Clear the shipping items to make sure the list is fresh when we add them.
  $shipment
    ->setItems([]);

  /** @var \Drupal\commerce_shipping\ShipmentItem $shipment_item */
  foreach ($form_state
    ->getValue('shipment_items') as $key => $value) {
    if ($value == 0) {

      // The item was not included in the shipment.
      continue;
    }

    /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
    $order_item = $this->entityTypeManager
      ->getStorage('commerce_order_item')
      ->load($key);
    $quantity = $order_item
      ->getQuantity();
    $purchased_entity = $order_item
      ->getPurchasedEntity();
    if ($purchased_entity
      ->get('weight')
      ->isEmpty()) {
      $weight = new Weight(1, WeightUnit::GRAM);
    }
    else {

      /** @var \Drupal\physical\Plugin\Field\FieldType\MeasurementItem $weight_item */
      $weight_item = $purchased_entity
        ->get('weight')
        ->first();
      $weight = $weight_item
        ->toMeasurement();
    }
    $shipment_item = new ShipmentItem([
      'order_item_id' => $order_item
        ->id(),
      'title' => $purchased_entity
        ->label(),
      'quantity' => $quantity,
      'weight' => $weight
        ->multiply($quantity),
      'declared_value' => $order_item
        ->getTotalPrice(),
    ]);
    $shipment
      ->addItem($shipment_item);
  }
}