You are here

public function CouponRedemption::viewsForm in Commerce Core 8.2

Form constructor for the views form.

Parameters

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

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

File

modules/promotion/src/Plugin/views/area/CouponRedemption.php, line 116

Class

CouponRedemption
Defines a coupon redemption area handler.

Namespace

Drupal\commerce_promotion\Plugin\views\area

Code

public function viewsForm(array &$form, FormStateInterface $form_state) {
  foreach ($this->view->argument as $name => $argument) {

    // First look for an order_id argument.
    if (!$argument instanceof NumericArgument) {
      continue;
    }
    if ($argument
      ->getField() !== 'commerce_order.order_id') {
      continue;
    }
    $order = $this->orderStorage
      ->load($argument
      ->getValue());
    if (!$order) {
      continue;
    }
    $inline_form = $this->inlineFormManager
      ->createInstance('coupon_redemption', [
      'order_id' => $order
        ->id(),
      'max_coupons' => $this->options['allow_multiple'] ? NULL : 1,
    ]);

    // Workaround for core bug #2897377.
    $form['#id'] = Html::getId($form_state
      ->getBuildInfo()['form_id']);
    $form['coupon_redemption'] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#weight' => $this->position,
      '#parents' => [
        'coupon_redemption',
      ],
    ];
    $form['coupon_redemption'] = $inline_form
      ->buildInlineForm($form['coupon_redemption'], $form_state);

    // InlineForm AJAX uses \Drupal\commerce\AjaxFormTrait::ajaxRefreshForm.
    // This re-renders the entire form and causes Views to break. We have
    // to override this AJAX definition so that we only return a subset
    // of the Views form.
    //
    // Without this, the order summary area can disappear _and_ the form
    // action becomes cart?ajax_form=1&_wrapper_format=html.
    //
    // @see \Drupal\commerce\AjaxFormTrait::ajaxRefreshForm
    // @see \Drupal\views\Form\ViewsForm::buildForm
    $form['coupon_redemption']['apply']['#ajax']['callback'] = [
      static::class,
      'ajaxRefreshSummary',
    ];
    if (isset($form['coupon_redemption']['coupons'])) {
      foreach ($form['coupon_redemption']['coupons'] as &$coupon) {
        $coupon['remove_button']['#ajax']['callback'] = [
          static::class,
          'ajaxRefreshSummary',
        ];
      }
    }
  }
}