Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Add Product to Cart Programmatically in Magento 2?

Vinh Jacker | 12-05-2017

How to Add Product to Cart Programmatically in Magento 2? How to Add Product to Cart Programmatically in Magento 2?

The Most Popular Extension Builder for Magento 2

With a big catalog of 224+ extensions for your online store

The product page is the most important aspects of any ecommerce store as it contains all the details about the products.

However, if the appearance of your product page is not up to the mark, you can lose a lot of sales. An attractive front end of your store can make your customers stay and can help in boosting sales. The look of add to cart button also plays a vital role in making the product page look attractive.

Magento 2 is one of the most used ecommerce platforms, so in this guide I am going to show you how to customize Add to cart button in Magento 2. You also can custom Add to Cart button to other types by Call for Price extension


Call for Price

Call for Price for Magento 2

Unlock the potential of your product sales with our custom pricing options on Magento 2

Check it out!


I will implement the procedure using a custom module. So let’s start by creating a custom module:

Related Topics

Configuration and Registration of Module

  • Create module.xml in app/code/Vendor/Mymodule/etc:
<?xml version="1.0"?>
	<configxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Vendor_Mymodule" setup_version="1.0.0"></module>
</config>
  • Create registration.php in app/code/Vendor/Mymodule:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
   \Magento\Framework\Component\ComponentRegistrar::MODULE,
   'Vendor_Mymodule',
   __DIR__
);

Copy addtocart.phtml File

Copy addtocart.phtml file from vendor/magento/module-catalog/view/frontend/templates/product/view paste this file in app/code/Vendor/Mymodule/view/frontend/templates/catalog/product/view.

Now create default.xml file in app/code/Vendor/Mymodule/view/frontend/layout and add this code in the file:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <head>
        <csssrc="Vendor_Mymodule::css/colorcart.css"/>
   </head>

   <body>
       <referenceBlock name="product.info.addtocart">
           <action method="setTemplate">
               <argument name="template" xsi:type="string">Vendor_Mymodule::catalog/product/view/addtocart.phtml</argument>
           </action>
       </referenceBlock>
   </body>
</page>

I have added colorcart.css file which I will use to customize add to cart button.

Edit addtocart.phtml

Now open addtocart.phtml file by going to app/code/Vendor/Mymodule/view/frontend/templates/catalog/product/view and add css class newcolor in the button tag:

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var $block \Magento\Catalog\Block\Product\View */
?>
<?php $_product = $block->getProduct(); ?>
<?php $buttonTitle = __('Add to Cart'); ?>
<?php if ($_product->isSaleable()) :?>
<div class="box-tocart">
    <div class="fieldset">
        <?php if ($block->shouldRenderQuantity()) :?>
        <div class="field qty">
            <label class="label" for="qty"><span><?= $block->escapeHtml(__('Qty')) ?></span></label>
            <div class="control">
                <input type="number"
                       name="qty"
                       id="qty"
                       min="0"
                       value="<?= $block->getProductDefaultQty() * 1 ?>"
                       title="<?= $block->escapeHtmlAttr(__('Qty')) ?>"
                       class="input-text qty"
                       data-validate="<?= $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                       />
            </div>
        </div>
        <?php endif; ?>
        <div class="actions">
            <button class=”newcolor” type="submit"
                    title="<?= $block->escapeHtmlAttr($buttonTitle) ?>"
                    class="action primary tocart"
                    id="product-addtocart-button" disabled>
                <span><?= $block->escapeHtml($buttonTitle) ?></span>
            </button>
            <?= $block->getChildHtml('', true) ?>
        </div>
    </div>
</div>
<?php endif; ?>
<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "Magento_Catalog/js/validate-product": {}
        }
    }
</script>

Create CSS file

Now create a css file colorcart.css in app/code/Vendor/Mymodule/view/frontend/web/css and add the following code in it:

.newcolor
{
   background: #29487d !important;
   box-shadow: 1px 5px 5px 1px rgba(66, 103, 178, 0.51);
   font-size: 23px !important;
   font-weight: bold !important;
   border-radius: 10px;
   height: 60px;
   font-family: cursive !important;
}

Now go to your Magento 2 root directory through SSH terminal and run these commands:

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

Launch the product’s front page and you will see the new design applied to the add to cart button:

new design applied to the add to cart button

Add products to cart using Quote Model

The AddToCart controller processes a GET request at ‘example/product/addToCart’ by retrieving product information from request parameters and adding it to the cart.

<?php
namespace Magenest\Example\Controller\Product;

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;

/**
* Class AddToCart
* @package Magenest\BookingReservation\Controller\Product
*/
class AddToCart extends Action implements HttpGetActionInterface
{
   /** @var \Magento\Checkout\Model\SessionFactory */
   private $checkoutSession;

   /** @var \Magento\Quote\Api\CartRepositoryInterface */
   private $cartRepository;

   /** @var \Magento\Catalog\Api\ProductRepositoryInterface */
   private $productRepository;

   /** @var \Magento\Framework\Serialize\Serializer\Json */
   private $json;

   /** @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable */
   private $configurableType;

   /**
     * AddToCart constructor.
     * @param Context $context
     * @param \Magento\Framework\Serialize\Serializer\Json $json
     * @param \Magento\Checkout\Model\SessionFactory $checkoutSession
     * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     * @param \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurableType
     */
   public function __construct(
       Context $context,
       \Magento\Framework\Serialize\Serializer\Json $json,
       \Magento\Checkout\Model\SessionFactory $checkoutSession,
       \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
       \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
       \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurableType
   ) {
       $this->checkoutSession = $checkoutSession;
       $this->cartRepository = $cartRepository;
       $this->productRepository = $productRepository;
       $this->json = $json;
       $this->configurableType = $configurableType;
       parent::__construct($context);
   }

   /**
    * @return ResultInterface
    * @throws LocalizedException
    */
   public function execute()
   {
       $product = $this->productRepository->getById($this->getRequest()->getParam('id'));
       $qty = $this->getRequest()->getParam('qty');

       $session = $this->checkoutSession->create();
       $quote = $session->getQuote();
       $quote->addProduct($product, $qty);

       $this->cartRepository->save($quote);
       $session->replaceQuote($quote)->unsLastRealOrderId();
   }
}

You can add products to the cart by specifying only their ID. If no quantity parameter is provided, the Quote Model will default to assuming a quantity of 1.

Add product to cart with additional options

The addProduct function supports both simple and advanced parameter formats, enabling you to include extra options and data with cart items as needed.

/**
* @throws LocalizedException
*/
public function addProductWithOptions()
{
   $productSku = $this->getRequest()->getParam('sku');
   $qty       = $this->getRequest()->getParam('qty');

   /**
    * You can specify custom options for a product before adding it to cart
    */
   $product = $this->productRepository->get($productSku);
   $product->addCustomOption('additional_options', $this->json->serialize([
       'custom_option_1' => [
           'label' => __("Custom Option 1"),
           'value' => 10
       ],
       'custom_option_2' => [
           'label' => __("Custom Option 2"),
           'value' => 20
       ]
   ]));

   /**
    * The second parameter of addProduct function can either be an integer, or a Magento DataObject
    * An integer will be interpreted as quantity added
    * Using a DataObject will allow adding custom data to cart items; these data will be saved and can be retrieved as info_buyRequest of quote/order items
    */
   $buyRequest = new \Magento\Framework\DataObject([
       'qty' => $qty,
       'related_product' => '',
       'custom_option' => '?'
   ]);

   $session = $this->checkoutSession->create();
   $quote = $session->getQuote();
   $quote->addProduct($product, $buyRequest);

   $this->cartRepository->save($quote);
   $session->replaceQuote($quote)->unsLastRealOrderId();

Wrapping Up

I have demonstrated just one example, but you can design your Add to cart button according to your intention. With the help of this guide, I believe that you can now customize Add to cart button in Magento 2. If you want to discuss something related to this tutorial, just leave a message in the comment box below and I will get back to you.

Customize Add to Cart button with Mageplaza extension

Table of content
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support & Maintenance Services

    mageplaza services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.