You are here

public static function CouponRedemption::applyCoupon in Commerce Core 8.2

Submit callback for the "Apply coupon" button.

File

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

Class

CouponRedemption
Provides an inline form for redeeming a coupon.

Namespace

Drupal\commerce_promotion\Plugin\Commerce\InlineForm

Code

public static function applyCoupon(array $form, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();
  $parents = array_slice($triggering_element['#parents'], 0, -1);
  $inline_form = NestedArray::getValue($form, $parents);

  // Clear the coupon code input.
  $user_input =& $form_state
    ->getUserInput();
  NestedArray::setValue($user_input, array_merge($parents, [
    'code',
  ]), '');
  if (isset($inline_form['code']['#coupon_id'])) {
    $order_storage = \Drupal::entityTypeManager()
      ->getStorage('commerce_order');

    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $order_storage
      ->load($inline_form['#configuration']['order_id']);
    $order
      ->get('coupons')
      ->appendItem($inline_form['code']['#coupon_id']);
    $order
      ->save();
  }
  $form_state
    ->setRebuild();
}