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);
craft\commerce\models\LineItem
model and thecraft\commerce\services\LineItems::createLineItem()
method. The cart is anOrder
instance and contains a collection ofLineItem
s. EachLineItem
has aPurchasable
id andProduct
implementsPurchasable
.