Recently, one of my clients was asking me to create custom add-to-cart functionality. Products were simple products with the customizable options dropdown. The code that I have written was for Magento 2.3.6 but this should work in 2.4.x too.
In this article, we will create a custom module Magetutorials/Addtocartajax with Frontname as “addwithcustom”
We are creating a controller file where we are going to add our custom add to cart function. File path would be “Magetutorials\Addtocartajax\Controller\Index”
How to add products to the cart using existing custom options?
The controller can get the parameter like product ID that we want to add into the cart. Also, we will pass the custom option that is selected by the end user. To get all the custom options of product we can use below code. Use cart object to add the product to cart.
<?php
declare(strict_types=1);
namespace Magetutorials\Addtocartajax\Controller\Index;
use Magento\Framework\View\Result\PageFactory;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Data\Form\FormKey;
class Index implements HttpGetActionInterface
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* @var \Magento\Checkout\Model\Session
*/
protected $checkoutSession;
/**
* @var \Magento\Quote\Api\CartRepositoryInterface
*/
protected $cartRepository;
/**
* @var \Magento\Catalog\Api\ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
protected $json;
protected $formKey;
protected $cart;
/**
* Constructor
*
* @param PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Quote\Api\CartRepositoryInterface $cartRepository,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Serialize\Serializer\Json $json,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory $optionCollection,
\Magento\Framework\App\Action\Context $context
) {
$this->formKey = $formKey;
$this->resultPageFactory = $resultPageFactory;
$this->checkoutSession = $checkoutSession;
$this->cartRepository = $cartRepository;
$this->productRepository = $productRepository;
$this->json = $json;
$this->cart = $cart;
$this->optionCollection = $optionCollection;
parent::__construct($context);
}
/**
* Execute view action
*
* @return ResultInterface
*/
public function execute()
{
try {
$postedData = $this->getRequest()->getPostValue();
parse_str($postedData['data'], $output);
$productId = $output['prod_id'];
$product = $this->productRepository->getById($productId);
/* get all options by product id */
$productOption = $this->optionCollection->create()->getProductOptions($product->getEntityId(),$product->getStoreId(),false);
$optionData = [];
foreach($productOption as $option) {
$optionId = $option->getId();
$optionValues = $product->getOptionById($optionId);
if ($optionValues === null) {
throw \Magento\Framework\Exception\NoSuchEntityException::singleField('optionId', $optionId);
}
foreach($optionValues->getValues() as $values) {
$optionData[] = $values->getData();
}
}
echo "<pre>";
var_dump($optionData);
/* End: get all options by product id */
$cartobj = $this->cart->create();
$params = array();
$params['qty'] = 1;
$params['product'] = $productId;
// set your option id and value.
//The key: 1 is the optionTypeId.
//The val: 3 is the optionId.
$options = array();
$options[1] = 3;
$params['options'] = $options;
$cartobj->addProduct($product, $params);
$cartobj->save();
} catch (Exception $e) {
// handle exceptions here
}
}
}