Modifying the Cart Items¶
If you want to apply any custom logic or business rules to cart items as they are added
to the cart, you can use the AddCartItemEvent to modify them before they are persisted. -
e.g. append a companion/related line when a "driver" item is added to the cart
Note that this event differs from the SubmitCartEvent as this event is working directly with
the CartItems as they are added to the Cart. The SubmitCartEvent allows you to modify the whole
Cart before it is processed through Order.create.
Event Listener: civi.shoppingcart.addcartitems¶
It has one parameters: - items - The list of lineitems to be added to the cart. This is an ALTER event: mutate $items only.
Example:
<?php
namespace Civi\Customextension;
use Civi\Core\Service\AutoSubscriber;
use Civi\Shoppingcart\Event\AddCartItemsEvent;
class CartItemsSubscriber extends AutoSubscriber {
/**
* @return array
*/
public static function getSubscribedEvents(): array {
return [
'civi.shoppingcart.addcartitems' => [['onCartItemsAdded', 100]],
];
}
public function onCartItemsAdded(AddCartItemsEvent $event) {
$driverPriceFieldId = 2; // a specific price field id, manual or derived from a setting
$result = [];
foreach ($event->items as $lineItem) {
$result[] = $lineItem;
// some business logic to append a companion lineItem
if ((int) ($lineItem['price_field_id'] ?? 0) !== $driverPriceFieldId) {
continue;
}
$companionData = CustomClass::getCompanion(FALSE)
->setLineItems([[
'price_field_id' => $driverPriceFieldId,
'price_field_value_id' => (int) ($lineItem['price_field_value_id'] ?? 0),
]])
->execute();
if ($companion) {
$companionItem = [
'entity_type' => 'Contribution',
'entity_table' => 'civicrm_contribution',
'price_field_id' => (int) $companionData['price_field_id'],
'price_field_value_id' => (int) ($companionData['price_field_value_id'] ?? 0),
'qty' => (float) ($companionData['qty'] ?? 1),
'unit_price' => (float) ($companionData['unit_price'] ?? 0),
'line_total' => (float) ($companionData['line_total'] ?? 0),
'description' => $companionData['label'] ?? NULL,
'contact_id' => $lineItem['contact_id'] ?? NULL,
];
if (!empty($lineItem['cart_id'])) {
$companionItem['cart_id'] = $lineItem['cart_id'];
}
$result[] = $companionItem;
}
}
$event->items = $result;
}
}