Created
August 31, 2017 14:00
-
-
Save heddn/74386a203797894a84c67901cf4951d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CartOnlySingleItem implements EventSubscriberInterface { | |
use StringTranslationTrait; | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function getSubscribedEvents() { | |
return [ | |
CartEvents::CART_ENTITY_ADD => ['limitNumberEntriesAdd'], | |
CartEvents::CART_ORDER_ITEM_UPDATE => ['limitNumberEntriesUpdate'], | |
]; | |
} | |
/** | |
* Limit the number of items added to the cart. | |
* | |
* @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event | |
* The cart event. | |
*/ | |
public function limitNumberEntriesAdd(CartEntityAddEvent $event) { | |
$this->limitItemQuantity($event->getOrderItem()); | |
} | |
/** | |
* Limit the number of items added to the cart. | |
* | |
* @param \Drupal\commerce_cart\Event\CartOrderItemUpdateEvent $event | |
* The cart event. | |
*/ | |
public function limitNumberEntriesUpdate(CartOrderItemUpdateEvent $event) { | |
$this->limitItemQuantity($event->getOrderItem()); | |
} | |
/** | |
* Limit the number of items added to the cart. | |
* | |
* @param \Drupal\commerce_order\Entity\OrderItemInterface $orderItem | |
* The order item. | |
*/ | |
protected function limitItemQuantity(OrderItemInterface $orderItem) { | |
if ($orderItem->getQuantity() > 1) { | |
$orderItem->setQuantity(1)->save(); | |
// Clear out existing status messages related to addition to the cart. | |
drupal_get_messages('status'); | |
drupal_set_message($this->t('Only a single instance of an event is allowed at a time in your cart.'), 'error'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment