How to save quote items in magento 2
Question
How to save quote items in Magento 2? I have quote id. I'm able to store quote table data but I want to store products name, sku which is going in quote_item
table.
I am able to set Data in quote table . $quote->setItemsqty($this->qty)
;
But i want to set Sku ,Name etc on quote_item
table
Below is my Function on that function i am able to create quote
public function save(\Magento\Quote\Api\Data\CartInterface $quote)
{
if ($quote->getId()) {
$currentQuote = $this->get($quote->getId(), [$quote->getStoreId()]);
foreach ($currentQuote->getData() as $key => $value) {
if (!$quote->hasData($key)) {
$quote->setData($key, $value);
}
}
$quote->setItemscount(count($this->sku));
$quote->setItemsqty($this->qty);
}
$this->getSaveHandler()->save($quote);
$quoteItem = $this->quoteItemFactory->create();
$quoteItem->setProduct($product);
$quoteObj->addItem($quoteItem);
$quoteObj->collectTotals()->save();
$this->customlog->info($quoteItem->getData());
unset($this->quotesById[$quote->getId()]);
unset($this->quotesByCustomerId[$quote->getCustomerId()]);
}
How to do it? Any idea?
Solution
We can use setProduct
method of quote item object.
Inject - \Magento\Quote\Model\Quote\ItemFactory
\Magento\Quote\Api\Data\CartItemInterfaceFactory
in your constructor.
/**
* @var \Magento\Quote\Api\Data\CartItemInterfaceFactory
*/
protected $cartItemFactory;
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $product;
public function __construct(
\Magento\Quote\Api\Data\CartItemInterfaceFactory $cartItemFactory,
\Magento\Catalog\Api\ProductRepositoryInterface $product,
....
) {
$this->cartItemFactory = $cartItemFactory;
$this->product = $product;
}
In your method:
$product = $this->product->get($productSku);
$quoteItem = $this->cartItemFactory->create();
$quoteItem->setProduct($product);
$quote->addItem($quoteItem);
$quote->collectTotals()->save();
EDIT:
I used \Magento\Quote\Api\Data\CartItemInterfaceFactory
instead of using \Magento\Quote\Model\Quote\ItemFactory
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange