1

I'm trying to add items to user's cart from a plugin but I'm stuck on getting cart of a user other then current user.

I have the code for adding items to cart, it's something I used on current user. But I don't know how to get the cart for any user.

<?php
$cart = iHaveNoIdeaHowToGetUsersCart($user->id); // <---
// I used this for current user:
// $cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();
if ($cart->id == null) {
    // Create cart if it does not exist
    Craft::$app->getElements()->saveElement($cart);
}

$purchasableId = Craft::$app->getGlobals()->getSetByHandle('booking')->breakProduct->one()->id;
$options = [
    'amount' => (float)$something,
    'description' => 'Something'
];
$newLineItem = Plugin::getInstance()->getLineItems()->createLineItem($cart->id, $purchasableId, $options, 1);
$cart->setLineItems([$newLineItem]);
Craft::$app->getElements()->saveElement($cart);
?>

1 Answer 1

1

In Commerce, a User (or guest with an email address for that matter) can have multiple carts (or unfinished orders).

So we need to get the most recently active one. Something like this should work:

$query = Order::find();
$query->id($whateverId); // you could also use $query->email 
$query->isCompleted(false);
$query->orderBy('dateCreated DESC');
$cart =  $query->one();

... // rest of your code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.