/** * Selects the store for the given purchasable entity. * * If the entity is sold from one store, then that store is selected. * If the entity is sold from multiple stores, and the current store is * one of them, then that store is selected. * * @param \Drupal\commerce\PurchasableEntityInterface $entity * The entity being added to cart. * * @throws \Exception * When the entity can't be purchased from the current store. * * @return \Drupal\commerce_store\Entity\StoreInterface * The selected store. */ protected function selectStore(PurchasableEntityInterface $entity) { // @todo Add getStores() to the PurchasableEntityInterface. $stores = $entity->getProduct()->getStores(); if (count($stores) === 1) { $store = reset($stores); } else { $store = $this->storeContext->getStore(); if (!in_array($store, $stores)) { // Indicates that the site listings are not filtered properly. throw new \Exception("The given entity can't be purchased from the current store."); } } return $store; }
/** * {@inheritdoc} */ function submitForm(array &$form, FormStateInterface $form_state) { $variation = $this->variationStorage->load($form_state->getValue('variation')); $available_stores = $variation->getProduct()->getStores(); if (count($available_stores) === 1) { $store = reset($available_stores); } else { $store = $this->storeContext->getStore(); if (!in_array($store, $available_stores)) { // Throw an exception. } } // @todo The order type should not be hardcoded. $cart = $this->cartProvider->getCart('default', $store); if (!$cart) { $cart = $this->cartProvider->createCart('default', $store); } $quantity = $form_state->getValue('quantity'); $combine = $form['#settings']['combine']; $this->cartManager->addEntity($cart, $variation, $quantity, $combine); drupal_set_message(t('@variation added to @cart-link.', ['@variation' => $variation->label(), '@cart-link' => Link::createFromRoute('your cart', 'commerce_cart.page')->toString()])); }