
After Magento 2.2 there was a major change to the way in which data is serialized within the store. This means that old methodologies of using serialize() no longer function. The following is how to add simple products to cart in Magento 2.2+ through the use of a controller.
<?php
namespace Ecommercegorilla\Customadd\Controller\Addtocart;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $_productRepository;
protected $_cart;
public function __construct(
Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Checkout\Model\Cart $cart,
PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
$this->_productRepository = $productRepository;
$this->_cart = $cart;
parent::__construct($context);
}
public function execute()
{
// Define the product ID you wish to add
$productId = 1;
// Define the array of custom options
$additionalOptions['shirt_color'] = [
'label' => 'Shirt Color',
'value' => 'White',
];
// Define product parameters such as quantity
$params = array(
'product' => $productId,
'qty' => 1
);
// Load the product from the database
$_product = $this->_productRepository->getById($productId);
// Append custom options to the product
$_product->addCustomOption('additional_options', json_encode($additionalOptions));
// Add the product to the customers cart
$this->_cart->addProduct($_product,$params);
// Save the customers cart
$this->_cart->save();
//include further logic such as redirect here
}
}If we wanted to add multiple custom options on the same product, “Shirt Color” and “Pocket Color” we would merely duplicate and update the additionalOptions array.
$additionalOptions['shirt_color'] = [
'label' => 'Shirt Color',
'value' => 'White',
];
$additionalOptions['pocket_color'] = [
'label' => 'Pocket Color',
'value' => 'Green',
];Advertisement



