Thursday, March 5, 2020

magento 2 add product to cart programmatically with custom options

Hello

Here I explain to you how to add product to cart programmatically with custom options.

First, create custom options from the Magento admin.


 Now go to app->code->Czar->Cart


 registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Czar_Cart',
    __DIR__
);


etc -> module.xml

 <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Czar_Cart" setup_version="1.0.0">
    </module>
</config>


etc -> routes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="add" frontName="add">
            <module name="Czar_Cart"/>
        </route>
    </router>
</config>


Controller->Index->Index.php


<?php
namespace Czar\Cart\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;

class Index extends Action
{
protected $formKey;  
protected $cart;
protected $product;
protected $_pageFactory;
protected $_session;
protected $serializer;
protected $ProductRepository;

protected $_responseFactory;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
 \Magento\Catalog\Model\ProductRepository $ProductRepository,
\Magento\Customer\Model\Session $session,
\Magento\Framework\Serialize\SerializerInterface $serializer,
\Magento\Framework\View\Result\PageFactory $PageFactory,
\Magento\Framework\App\ResponseFactory $responseFactory,
array $data = []) {
    $this->_responseFactory = $responseFactory;

    $this->formKey = $formKey;
    $this->_pageFactory = $PageFactory;
    $this->cart = $cart;
    $this->serializer = $serializer;
    $this->product = $product;
    $this->ProductRepository = $ProductRepository;
    $this->_session = $session;   
    parent::__construct($context);
}

public function execute()
 {

  $page = $this->_pageFactory->create();
  $productId =1;
  $id = $this->_session->getId();
  $additionalOptions['firstnamesku'] = [
            'label' => 'First Name',
            'value' => 'chirag',
        ];
  $additionalOptions['lnamesku'] = [
            'label' => 'Last Name',
            'value' => 'parmar',
        ];
  $additionalOptions['emailidsku'] = [
            'label' => 'Email ID',
            'value' => 'chirag@czargroup.net',
        ];
  $additionalOptions['phonenosku'] = [
            'label' => 'Phone No',
            'value' => '1234567890',
        ];

  if(!$this->_session->isLoggedIn()){
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, //product Id
                'qty'   =>1 //quantity of product
                             
            );  
   }else{
           $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, //product Id
                'qty'   =>1, //quantity of product
                'customer_id'   =>$id
                               
            );
   }          
    //Load the product based on productID  
    $_product = $this->ProductRepository->getById($productId);
   
    $_product->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
    $this->cart->addProduct($_product, $params);
    $this->cart->save();
    //return $page;
    $message = "Product have been successfully added to your Shopping Cart.";
    $this->messageManager->addSuccess($message);
    $accUrl = $this->_url->getUrl('checkout/cart/');
    $this->_responseFactory->create()->setRedirect($accUrl)->sendResponse();
    $this->setRefererUrl($accUrl);
  }
}

Now run commands : 

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento c:f


now hit url like this:
yourwebsite.com/add

It will display result like this:-


 

No comments:

Post a Comment