View source
<?php
namespace Drupal\commerce_promotion\Plugin\Commerce\CheckoutPane;
use Drupal\commerce\InlineFormManager;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CouponRedemption extends CheckoutPaneBase {
protected $inlineFormManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager, InlineFormManager $inline_form_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
$this->inlineFormManager = $inline_form_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, CheckoutFlowInterface $checkout_flow = NULL) {
return new static($configuration, $plugin_id, $plugin_definition, $checkout_flow, $container
->get('entity_type.manager'), $container
->get('plugin.manager.commerce_inline_form'));
}
public function defaultConfiguration() {
return [
'allow_multiple' => FALSE,
] + parent::defaultConfiguration();
}
public function buildConfigurationSummary() {
if ($this->configuration['allow_multiple']) {
$summary = $this
->t('Allows multiple coupons: Yes');
}
else {
$summary = $this
->t('Allows multiple coupons: No');
}
return $summary;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['allow_multiple'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Allow multiple coupons to be redeemed'),
'#default_value' => $this->configuration['allow_multiple'],
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
if (!$form_state
->getErrors()) {
$values = $form_state
->getValue($form['#parents']);
$this->configuration['allow_multiple'] = $values['allow_multiple'];
}
}
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
$inline_form = $this->inlineFormManager
->createInstance('coupon_redemption', [
'order_id' => $this->order
->id(),
'max_coupons' => $this->configuration['allow_multiple'] ? NULL : 1,
]);
$pane_form['form'] = [
'#parents' => array_merge($pane_form['#parents'], [
'form',
]),
];
$pane_form['form'] = $inline_form
->buildInlineForm($pane_form['form'], $form_state);
return $pane_form;
}
public function submitPaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
if (!empty($pane_form['form']['code']['#coupon_id'])) {
$this->order
->get('coupons')
->appendItem($pane_form['form']['code']['#coupon_id']);
}
}
}