You are here

public function CouponRedemption::validateInlineForm in Commerce Core 8.2

Validates the inline form.

Parameters

array $inline_form: The inline form, containing the following basic properties:

  • #parents: Identifies the location of the field values in $form_state.

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

Overrides InlineFormBase::validateInlineForm

File

modules/promotion/src/Plugin/Commerce/InlineForm/CouponRedemption.php, line 169

Class

CouponRedemption
Provides an inline form for redeeming a coupon.

Namespace

Drupal\commerce_promotion\Plugin\Commerce\InlineForm

Code

public function validateInlineForm(array &$inline_form, FormStateInterface $form_state) {
  parent::validateInlineForm($inline_form, $form_state);

  // Runs if the 'Apply coupon' button was clicked, or the main form
  // was submitted by the user clicking the primary submit button.
  $triggering_element = $form_state
    ->getTriggeringElement();
  $button_type = isset($triggering_element['#button_type']) ? $triggering_element['#button_type'] : NULL;
  if ($triggering_element['#name'] != 'apply_coupon' && $button_type != 'primary') {
    return;
  }
  $coupon_code_parents = array_merge($inline_form['#parents'], [
    'code',
  ]);
  $coupon_code = $form_state
    ->getValue($coupon_code_parents);
  $coupon_code_path = implode('][', $coupon_code_parents);
  if (empty($coupon_code)) {
    if ($triggering_element['#name'] == 'apply_coupon') {
      $form_state
        ->setErrorByName($coupon_code_path, t('Please provide a coupon code.'));
    }
    return;
  }

  /** @var \Drupal\commerce_promotion\CouponStorageInterface $coupon_storage */
  $coupon_storage = $this->entityTypeManager
    ->getStorage('commerce_promotion_coupon');
  $coupon = $coupon_storage
    ->loadEnabledByCode($coupon_code);
  if (empty($coupon)) {
    $form_state
      ->setErrorByName($coupon_code_path, t('The provided coupon code is invalid.'));
    return;
  }
  $order_storage = $this->entityTypeManager
    ->getStorage('commerce_order');

  /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  $order = $order_storage
    ->load($this->configuration['order_id']);
  foreach ($order
    ->get('coupons') as $item) {
    if ($item->target_id == $coupon
      ->id()) {

      // Coupon already applied. Error message not set for UX reasons.
      return;
    }
  }
  if (!$coupon
    ->available($order)) {
    $form_state
      ->setErrorByName($coupon_code_path, t('The provided coupon code is not available. It may have expired or already been used.'));
    return;
  }
  if (!$coupon
    ->getPromotion()
    ->applies($order)) {
    $form_state
      ->setErrorByName($coupon_code_path, t('The provided coupon code cannot be applied to your order.'));
    return;
  }

  // Save the coupon ID for applyCoupon.
  $inline_form['code']['#coupon_id'] = $coupon
    ->id();
}