Magento 2: save item options in quote(quote_item_option)
Question
I need to add new option for item.
Now in quote_item_option
i have:
{"id":"54","product":"54","selected_configurable_option":"","related_product":"","options":{"4":""},"qty":"1"}
But wanna {"id":"54","product":"54","selected_configurable_option":"","related_product":"","options":{"4":"", "new_option":"some_value"},"qty":"1"}
I created following controller:
<?php
namespace MySpace\SomeModule\Controller\Quote;
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Magento\Checkout\Model\Session
*/
protected $checkoutSession;
/**
* Update constructor.
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
* @param \Magento\Checkout\Model\Session $checkoutSession
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Checkout\Model\Session $checkoutSession
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->checkoutSession = $checkoutSession;
}
/**
* @return \Magento\Framework\Controller\Result\Json
*/
public function execute()
{
$a = 3;
$itemId = (int) $this->getRequest()->getParam('item_id');
$orderNoteEnabledValue = (string) $this->getRequest()->getParam('new_option');
if ($itemId && $newOptionValue) {
$quote = $this->checkoutSession->getQuote();
/** @var \Magento\Quote\Model\Quote\Item $item */
foreach ($this->checkoutSession->getQuote()->getItems() as $item) {
if ((int)$item->getItemId() !== $itemId) {
continue;
}
$buyRequest = $item->getBuyRequest();
$options = $buyRequest->getData('options');
if (!$options) {
$options = [];
}
$options['new_option'] = $newOptionValue;
$buyRequest->setData('options', $options);
$quote->updateItem($itemId, $buyRequest);
$quote->save();
break;
}
}
return $this->resultJsonFactory->create()->setData(['message' => 'Error']);
}
}
I debugged, script getts data(option value) successfully, modified it also, but not saving option with new field to table.
What is issue or my mistake?
Thanks for any halp and advise:)
Solution 2
the solution: just need to get option for item_id by name "info_buyRequest". after unserialize, modify value(add element), serialize and save
OTHER TIPS
Try calling $item->saveItemOptions()
instead of (or along side with) $quote->save()
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange