How to Add Product With Custom Option to Cart Programmatically in Magento 2

add_product_to_cart_programmatically_magento_2

In this code snippet, we will see how we can add a product to cart along with custom options. For that, we will create one controller file, In that file, we will define execute method. In this method using cart model, we will add a product to cart.

Create Controller

In your custom module create a controller file Post.php under app/code/Codextblog/Customcart/Controller/Index directory

namespace Codextblog\Customcart\Controller\Index;
 
use Magento\Framework\App\Action\Context;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
 
class Post extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
    protected $_cart;
    protected $_productRepositoryInterface;
    protected $_url;
    protected $_responseFactory;
    protected $_logger;


    public function __construct(
        Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepositoryInterface,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Psr\Log\LoggerInterface $logger
        )
    {
        $this->_resultPageFactory = $resultPageFactory;
        $this->_cart = $cart;
        $this->_productRepositoryInterface = $productRepositoryInterface;
        $this->_responseFactory = $responseFactory;
        $this->_url = $context->getUrl();
        $this->_logger = $logger;
        parent::__construct($context);
    }

    public function execute()
    {
       $productid = 111;
       
        $_product = $this->_productRepositoryInterface->getById($productid);
        $options = $_product->getOptions();

        $customoptions = array();
        $customoptions['my_custom_option'] = 'demo';

        $params = array (
            'product' => $_product->getId(),
            'qty' => 1,
            'price' => $_product->getPrice(),
            'options' => $customoptions
        );

       $this->_cart->addProduct($_product, $params);
       $this->_cart->save();

       $this->_redirect('checkout/cart/index'); 
    }

}

Update Minicart

In Magento 2 mini cart is update using knockout js. While adding a product to cart programmatically we need to specify the controller action in sections.xml file so that Magento 2 update the mini cart as well.

create sections.xml file under app/code/Codextblog/Customcart/etc/frontend directory

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="customcart/index/post">
        <section name="cart"/>
    </action>
</config>

That’s it. Using above code we can easily add product to cart programmatically.

Leave a Comment

(2 Comments)

  • thila

    How to update the added Product With Custom Option to Cart Programmatically in Magento 2

  • Ishan

    can you give me this full module?

  • All the comments are goes into moderation before approval. Please do not spam. Your email address will not be published. Required fields are marked *

    Enjoy this post? Please support Us!

    Like our social page for daily new updates….


    Want to become
    a Magento 2 Expert?

    If Yes! Then Subscribe to our newsletter and get weekly article to you email id.
    Subscribe Here
    SUBSCRIBE NOW
    close-link

    To Avoid Spam Downloads, We Want Your Email

    We will send you download link right
    away. Please submit form below.
    SEND ME DOWNLOAD LINK
    Close