TransWikia.com

Add product to cart using code in Craft Commerce plugin

Craft CMS Asked on December 29, 2020

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 = craftcommercePlugin::getInstance()->getCarts()->getCart();

I can also get a Product using the below code

$product = craftcommerceelementsProduct::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.

2 Answers

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

$theOrder = $event->sender;
$myProduct = craftcommerceelementsProduct::find()->id([$giftProductId])->one();
if($myProduct){
    $myPurchasable = $myProduct->getDefaultVariant();
    $newOrExistingLineItem = craftcommercePlugin::getInstance()->getLineItems()->resolveLineItem($theOrder->id, $myPurchasable->id, []);
    $theOrder->addLineItem($newOrExistingLineItem);
}

Answered by aslamdoctor on December 29, 2020

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 = craftcommercePlugin::getInstance()->getCarts()->getCart();
        $product = craftcommerceelementsProduct::find()->id([123])->one();
        $purchasableId = $product->getDefaultVariant()->id;

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

        // Save the updated cart...

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

Answered by Jeremy Daalder on December 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP