You are here

class CheckoutForm in Ubercart 8.4

The checkout form built up from the enabled checkout panes.

Hierarchy

Expanded class hierarchy of CheckoutForm

File

uc_cart/src/Form/CheckoutForm.php, line 17

Namespace

Drupal\uc_cart\Form
View source
class CheckoutForm extends FormBase {
  use AjaxAttachTrait;

  /**
   * The checkout pane manager.
   *
   * @var \Drupal\uc_cart\Plugin\CheckoutPaneManager
   */
  protected $checkoutPaneManager;

  /**
   * The session.
   *
   * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
   */
  protected $session;

  /**
   * The datetime.time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $dateTime;

  /**
   * Constructs a CheckoutController.
   *
   * @param \Drupal\uc_cart\Plugin\CheckoutPaneManager $checkout_pane_manager
   *   The checkout pane plugin manager.
   * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
   *   The session.
   * @param \Drupal\Component\Datetime\TimeInterface $date_time
   *   The datetime.time service.
   */
  public function __construct(CheckoutPaneManager $checkout_pane_manager, SessionInterface $session, TimeInterface $date_time) {
    $this->checkoutPaneManager = $checkout_pane_manager;
    $this->session = $session;
    $this->dateTime = $date_time;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.uc_cart.checkout_pane'), $container
      ->get('session'), $container
      ->get('datetime.time'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'uc_cart_checkout_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $order = NULL) {
    if ($processed = $form_state
      ->has('order')) {
      $order = $form_state
        ->get('order');
    }
    else {
      $form_state
        ->set('order', $order);
    }
    $form['#attributes']['class'][] = 'uc-cart-checkout-form';
    $form['#attached']['library'][] = 'uc_cart/uc_cart.styles';
    $form['panes'] = [
      '#tree' => TRUE,
    ];
    $filter = [
      'enabled' => FALSE,
    ];

    // If the order isn't shippable, remove panes with shippable == TRUE.
    if (!$order
      ->isShippable() && $this
      ->config('uc_cart.settings')
      ->get('panes.delivery.settings.delivery_not_shippable')) {
      $filter['shippable'] = TRUE;
    }
    $panes = $this->checkoutPaneManager
      ->getPanes($filter);

    // Invoke the 'prepare' op of enabled panes, but only if their 'process' ops
    // have not been invoked on this request (i.e. when rebuilding after AJAX).
    foreach ($panes as $id => $pane) {
      if (!$form_state
        ->get([
        'panes',
        $id,
        'prepared',
      ])) {
        $pane
          ->prepare($order, $form, $form_state);
        $form_state
          ->set([
          'panes',
          $id,
          'prepared',
        ], TRUE);

        // Make sure we save the updated order.
        $processed = FALSE;
      }
    }

    // Load the line items and save the order. We do this after the 'prepare'
    // callbacks of enabled panes have been invoked, because these may have
    // altered the order.
    if (!$processed) {
      $order->line_items = $order
        ->getLineItems();
      $order
        ->save();
    }
    foreach ($panes as $id => $pane) {
      $form['panes'][$id] = $pane
        ->view($order, $form, $form_state);
      $form['panes'][$id] += [
        '#type' => 'details',
        '#title' => $pane
          ->getTitle(),
        '#id' => $id . '-pane',
        '#open' => TRUE,
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['cancel'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Cancel'),
      '#validate' => [],
      '#limit_validation_errors' => [],
      '#submit' => [
        [
          $this,
          'cancel',
        ],
      ],
    ];
    $form['actions']['continue'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Review order'),
      '#button_type' => 'primary',
    ];
    $form['#process'][] = [
      $this,
      'ajaxProcessForm',
    ];
    $this->session
      ->remove('uc_checkout_review_' . $order
      ->id());
    $this->session
      ->remove('uc_checkout_complete_' . $order
      ->id());
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $order = $form_state
      ->get('order');

    // Update the order "changed" time to prevent timeout on ajax requests.
    $order
      ->setChangedTime($this->dateTime
      ->getRequestTime());

    // Validate/process each cart pane. If one of the process() functions
    // returns FALSE, checkout fails.
    $form_state
      ->set('checkout_valid', TRUE);
    foreach (Element::children($form_state
      ->getValue('panes')) as $id) {
      $pane = $this->checkoutPaneManager
        ->createInstance($id);
      if ($pane
        ->process($order, $form, $form_state) === FALSE) {
        $form_state
          ->set('checkout_valid', FALSE);
      }
    }

    // Reload line items and save order.
    $order->line_items = $order
      ->getLineItems();
    $order
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->get('checkout_valid') === FALSE) {
      $form_state
        ->setRedirect('uc_cart.checkout');
    }
    else {
      $form_state
        ->setRedirect('uc_cart.checkout_review');
      $this->session
        ->set('uc_checkout_review_' . $form_state
        ->get('order')
        ->id(), TRUE);
    }
    $form_state
      ->set('checkout_valid', NULL);
  }

  /**
   * Submit handler for the "Cancel" button on the checkout form.
   */
  public function cancel(array &$form, FormStateInterface $form_state) {
    $order = $form_state
      ->get('order');
    if ($this->session
      ->get('cart_order') == $order
      ->id()) {
      uc_order_comment_save($order
        ->id(), 0, $this
        ->t('Customer canceled this order from the checkout form.'));
      $this->session
        ->remove('cart_order');
    }
    $this->session
      ->remove('uc_checkout_review_' . $order
      ->id());
    $this->session
      ->remove('uc_checkout_complete_' . $order
      ->id());
    $form_state
      ->setRedirect('uc_cart.cart');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxAttachTrait::ajaxMultiplex public function Ajax callback multiplexer.
AjaxAttachTrait::ajaxProcessForm public function Form process callback to allow multiple Ajax callbacks on form elements.
AjaxAttachTrait::ajaxReplaceCheckoutPane public function Ajax callback to replace a whole checkout pane.
CheckoutForm::$checkoutPaneManager protected property The checkout pane manager.
CheckoutForm::$dateTime protected property The datetime.time service.
CheckoutForm::$session protected property The session.
CheckoutForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
CheckoutForm::cancel public function Submit handler for the "Cancel" button on the checkout form.
CheckoutForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
CheckoutForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CheckoutForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CheckoutForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
CheckoutForm::__construct public function Constructs a CheckoutController.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.