You are here

public function ShipmentForm::save in Commerce Shipping 8.2

Form submission handler for the 'save' action.

Normally this method should be overridden to provide specific messages to the user and redirect the form after the entity has been saved.

Parameters

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

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

Return value

int Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.

Overrides EntityForm::save

File

src/Form/ShipmentForm.php, line 284

Class

ShipmentForm
Defines the shipment add/edit form.

Namespace

Drupal\commerce_shipping\Form

Code

public function save(array $form, FormStateInterface $form_state) {

  /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
  $shipment = $this
    ->getEntity();
  $this
    ->addShippingItems($form, $form_state);
  $shipment
    ->setData('owned_by_packer', FALSE);
  $shipment
    ->save();

  // Make sure the shipment gets added to the order.
  $order = $shipment
    ->getOrder();
  $order_shipments = $order
    ->get('shipments');
  $shipment_exists = FALSE;
  $save_order = FALSE;

  // Loop over the order shipments to make sure this
  // shipment exists.
  foreach ($order_shipments
    ->getValue() as $order_shipment) {
    if ($order_shipment['target_id'] == $shipment
      ->id()) {
      $shipment_exists = TRUE;
    }
  }

  // Check if the shipment amount has changed, if so we need to trigger
  // an order refresh so that the shipping adjustment gets adjusted.
  if ($form_state
    ->get('original_amount') != $shipment
    ->getAmount()) {
    $order
      ->setRefreshState(OrderInterface::REFRESH_ON_SAVE);
    $save_order = TRUE;
  }

  // Add the shipment to the order if it doesn't exist.
  if (!$shipment_exists) {
    $order_shipments
      ->appendItem($shipment);
    $save_order = TRUE;
  }

  // Save the parent order if the shipment amount has changed or if the
  // shipment was appended to the order.
  if ($save_order) {
    $order
      ->save();
  }
  $this
    ->messenger()
    ->addMessage($this
    ->t('Shipment for order @order created.', [
    '@order' => $order
      ->getOrderNumber(),
  ]));
  $form_state
    ->setRedirect('entity.commerce_shipment.collection', [
    'commerce_order' => $order
      ->id(),
  ]);
}