You are here

public function ShipmentForm::validateForm in Commerce Shipping 8.2

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 validation handler, otherwise an exception will be thrown.

Overrides ContentEntityForm::validateForm

File

src/Form/ShipmentForm.php, line 243

Class

ShipmentForm
Defines the shipment add/edit form.

Namespace

Drupal\commerce_shipping\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  parent::validateForm($form, $form_state);
  $triggering_element = $form_state
    ->getTriggeringElement();
  $recalculate = !empty($triggering_element['#recalculate']);
  if ($recalculate) {
    $form_state
      ->set('recalculate_shipping', TRUE);

    /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
    $shipment = $this->entity;
    $shipment
      ->setTitle($form_state
      ->getValue('title'));
    $base_form_key = [
      'shipping_profile',
      '0',
      'profile',
    ];
    $selected_profile_key = array_merge($base_form_key, [
      'select_address',
    ]);
    $selected_profile_id = $form_state
      ->getValue($selected_profile_key);
    $address_key = array_merge($base_form_key, [
      'address',
      '0',
      'address',
    ]);
    $address = $form_state
      ->getValue($address_key);

    // If an address was input, use that as an address override.
    if ($address !== NULL) {
      $shipment
        ->getShippingProfile()
        ->get('address')
        ->setValue($address);
    }
    elseif ($selected_profile_id !== '_original') {
      $profile_storage = $this->entityTypeManager
        ->getStorage('profile');
      $selected_profile = $profile_storage
        ->load($selected_profile_id);
      assert($selected_profile instanceof ProfileInterface);
      $shipment
        ->getShippingProfile()
        ->set('address', $selected_profile
        ->get('address'));
    }

    // Add the shipping items.
    $this
      ->addShippingItems($form, $form_state);
    if (empty($form_state
      ->getValue('package_type'))) {
      return;
    }
    $package_type = $this->packageTypeManager
      ->createInstance($form_state
      ->getValue('package_type'));
    $shipment
      ->setPackageType($package_type);
  }
}