Validating the Cart¶
If you want to apply some custom logic or business rules to the cart before you checkout then you can implement an event listener to validate the cart.
Event Listener: civi.shoppingcart.validatecart¶
It takes one parameter "Cart ID" and returns an array of error strings.
Example:
<?php
namespace Civi\Customextension;
use Civi\Core\Service\AutoSubscriber;
use Civi\Shoppingcart\Event\ValidateCartEvent;
class ValidateCartSubscriber extends AutoSubscriber {
/**
* @return array
*/
public static function getSubscribedEvents(): array {
return [
'civi.shoppingcart.validatecart' => [['validateCart', 100]],
];
}
public function validateCart(ValidateCartEvent $event) {
$cartID = $event->cartID;
$cartItems = \Civi\Api4\CartItem::get(FALSE)
->addWhere('cart_id', '=', $cartID)
->execute();
foreach ($cartItems as $cartItem) {
if ($cartItem['entity_table'] === 'civicrm_membership') {
$event->errors[] = 'You are not allowed to have a membership in your cart';
}
}
}
}