Modifying the Cart¶
Use the SubmitCartEvent to modify the cart just before it is used to create an Order.
This allows you to apply any custom logic or business rules to the cart itself and after
the validation has succeeded.
Currently there is no logic for the ContributionRecur in the Cart::submit, but the event allows for setting the contributionRecurValues that will be used in the Order->Create.
Event Listener: civi.shoppingcart.submitcart¶
It takes four parameters:
- Cart ID.
- contributionValues - The list of values that should be set on the contribution.
- lineItems - The list of lineitems generated from the items in the cart.
- contributionRecurValues - The list of values for a ContributionRecur, if not set defaults to []
Example:
<?php
namespace Civi\Customextension;
use Civi\Core\Service\AutoSubscriber;
use Civi\Shoppingcart\Event\SubmitCartEvent;
class SubmitCartSubscriber extends AutoSubscriber {
/**
* @return array
*/
public static function getSubscribedEvents(): array {
return [
'civi.shoppingcart.submitcart' => [['onSubmitCart', 100]],
];
}
public function onSubmitCart(SubmitCartEvent $event) {
$cartID = $event->cartID;
$contributionValues = $event->contributionValues;
$lineItems = $event->lineItems;
foreach ($event->lineItems as $lineItem) {
// Do something with the lineitems..
}
// set some ContributionRecur values and mutate it back
$event->contributionRecurValues = [
'frequency_unit' => 'month',
'frequency_interval' => 1,
// Leave 'amount' unset - CRM_Financial_BAO_Order::setContributionRecurValues
// will calculate it from the order total.
'installments' => 0,
'start_date' => date('Y-m-d'),
];
}
}
Leave contributionRecurValues empty or NULL and no ContributionRecur is created.
If you set it, frequency_unit is mandatory: Order->Create throws
"Cannot create a recurring contribution without specifying frequency_unit" rather than skipping the
recur. frequency_interval defaults to 1, and amount and contact_id are taken from the order and
contribution. You must pass a numeric financial_type_id - the cart never sets the Order's default
financial type, and the check that fills it in does not recognise financial_type_id.name.