I want to add product to cart with some additional data. My code adds the product to cart,but the additional info is not saved properly.
I want to display the additional content in cart like custom option
http://i.prntscr.com/KzmHQqaNSYGhOt3buzlK1A.png
Here is my code
namespace Namespace\Module\Controller\Index;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
class Post extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $_productRepository;
protected $_cart;
protected $formKey;
private $serializer;
public function __construct(
Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Checkout\Model\Cart $cart,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Framework\Serialize\SerializerInterface $serializer,
PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
$this->_productRepository = $productRepository;
$this->_cart = $cart;
$this->formKey = $formKey;
$this->serializer = $serializer;
parent::__construct($context);
}
public function execute()
{
$post = $this->getRequest()->getPostValue();
$additionalOptions['print_style'] = [
'label' => 'Print Style',
'value' => 'Test',
];
$params = array(
'product' => 4,
'qty' => 1,
'options' => array('additional_options'=>$this->serializer->serialize($additionalOptions))
);
$_product = $this->_productRepository->getById(4);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();
echo 'success';
}
}
How can I do it?