You are here

class OrderAddForm in Commerce Core 8.2

Provides the order add form.

Hierarchy

Expanded class hierarchy of OrderAddForm

1 string reference to 'OrderAddForm'
commerce_order.routing.yml in modules/order/commerce_order.routing.yml
modules/order/commerce_order.routing.yml

File

modules/order/src/Form/OrderAddForm.php, line 15

Namespace

Drupal\commerce_order\Form
View source
class OrderAddForm extends FormBase {
  use CustomerFormTrait;

  /**
   * The order storage.
   *
   * @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage
   */
  protected $orderStorage;

  /**
   * The store storage.
   *
   * @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage
   */
  protected $storeStorage;

  /**
   * Constructs a new OrderAddForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->orderStorage = $entity_type_manager
      ->getStorage('commerce_order');
    $this->storeStorage = $entity_type_manager
      ->getStorage('commerce_store');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Skip building the form if there are no available stores.
    $store_query = $this->storeStorage
      ->getQuery()
      ->accessCheck(TRUE);
    if ($store_query
      ->count()
      ->execute() == 0) {
      $link = Link::createFromRoute('Add a new store.', 'entity.commerce_store.add_page');
      $form['warning'] = [
        '#markup' => $this
          ->t("Orders can't be created until a store has been added. @link", [
          '@link' => $link
            ->toString(),
        ]),
      ];
      return $form;
    }
    $form['type'] = [
      '#type' => 'commerce_entity_select',
      '#title' => $this
        ->t('Order type'),
      '#target_type' => 'commerce_order_type',
      '#required' => TRUE,
    ];
    $form['store_id'] = [
      '#type' => 'commerce_entity_select',
      '#title' => $this
        ->t('Store'),
      '#target_type' => 'commerce_store',
      '#required' => TRUE,
    ];
    $form = $this
      ->buildCustomerForm($form, $form_state);
    $form['custom_placed_date'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Place the order on a different date'),
      '#default_value' => FALSE,
    ];

    // The datetime element needs to be wrapped in order for #states to work
    // properly. See https://www.drupal.org/node/2419131
    $form['placed_wrapper'] = [
      '#type' => 'container',
      '#states' => [
        'visible' => [
          ':input[name="custom_placed_date"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['placed_wrapper']['placed'] = [
      '#type' => 'datetime',
      '#title_display' => 'invisible',
      '#title' => $this
        ->t('Placed'),
      '#default_value' => new DrupalDateTime(),
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Create'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->submitCustomerForm($form, $form_state);
    $values = $form_state
      ->getValues();
    $order_data = [
      'type' => $values['type'],
      'mail' => $values['mail'],
      'uid' => [
        $values['uid'],
      ],
      'store_id' => [
        $values['store_id'],
      ],
    ];
    if (!empty($values['custom_placed_date']) && !empty($values['placed'])) {
      $order_data['placed'] = $values['placed']
        ->getTimestamp();
    }
    $order = $this->orderStorage
      ->create($order_data);
    $order
      ->save();
    $values['order_id'] = $order
      ->id();
    $form_state
      ->setValues($values);

    // Redirect to the edit form to complete the order.
    $form_state
      ->setRedirect('entity.commerce_order.edit_form', [
      'commerce_order' => $order
        ->id(),
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CustomerFormTrait::buildCustomerForm public function Builds the customer form.
CustomerFormTrait::customerFormAjax public function Ajax callback.
CustomerFormTrait::submitCustomerForm public function Submit handler for the customer select form.
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
OrderAddForm::$orderStorage protected property The order storage.
OrderAddForm::$storeStorage protected property The store storage.
OrderAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
OrderAddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
OrderAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
OrderAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
OrderAddForm::__construct public function Constructs a new OrderAddForm object.
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.