I have a controller which when called (actions/some-module/discount-link/apply?code=abc
) associates abc
with an entry and based on some stuff in that entry populates the cart with some specific products. This works well.
What I want to do next is apply a discount to each line item that the cart is populated with. Setting up an adjuster as per the docs was no problem, but when I'm trying to add adjustments to the cart from within my controller I can't figure it out.
The last part of of my controller:
foreach ($cart->getLineItems() as $item) {
$adjustment = new OrderAdjustment;
$adjustment->type = 'discount';
$adjustment->name = '$2 off';
$adjustment->description = '$2 off everything in the store';
$adjustment->sourceSnapshot = ['data' => 'value'];
$adjustment->amount = -2;
$adjustment->setOrder(Order::findOne($cart));
$adjustment->setLineItem($item);
plugin::getInstance()->getOrderAdjustments()->saveOrderAdjustment($adjustment, true);
}
Craft::$app->elements->saveElement($cart);
Is the entire thing wrong? Or am I not saving the adjustments to the cart correctly?