1

I want to add a specific product to a cart using its ID. I have created a module which runs on Order::EVENT_BEFORE_ADD_LINE_ITEM event. Here I am able to capture the current cart using the below code

$cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();

I can also get a Product using the below code

$product = \craft\commerce\elements\Product::find()->id([123]); // here 123 is product id

But I am not sure how to add this product to the existing cart using a code.

1
1

I managed to figure this out. Below is the code:

$theOrder = $event->sender;
$myProduct = \craft\commerce\elements\Product::find()->id([$giftProductId])->one();
if($myProduct){
    $myPurchasable = $myProduct->getDefaultVariant();
    $newOrExistingLineItem = \craft\commerce\Plugin::getInstance()->getLineItems()->resolveLineItem($theOrder->id, $myPurchasable->id, []);
    $theOrder->addLineItem($newOrExistingLineItem);
}
1

In Twig, you can do something like this to add purchasable id (n.b. not product id) - 123 to a cart:

{% set cart = craft.commerce.carts.cart(true) %}
{% set lineItem = craft.commerce.lineitems.createLineItem(cart.id, 123, {"note":"Test note"}, 2, "") %}
{% do cart.addLineItem(lineItem) %}
{%  do craft.app.elements.saveElement(cart) %}

Thus the PHP equivalent should thus be (n.b. not actually tested):

        // You need the cart, and actual purchasable Id of what you want to add...
        // Here was assume a product without variants...so get the default variant's id

        $cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();
        $product = \craft\commerce\elements\Product::find()->id([123])->one();
        $purchasableId = $product->getDefaultVariant()->id;

        // Create a new line item & add it to the cart
    
        $newLineItem = \craft\commerce\Plugin::getInstance()->getLineItems()->createLineItem($cart->id, $purchasableId, [], 1, 'some note');
        $cart->addLineItem($newLineItem);

        // Save the updated cart...

        Craft::$app->getElements()->saveElement($cart);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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