Add Product To Cart Programmatically With Custom Options Step-by-step

by Grace Bui

Add product to cart programmatically with custom options is a valuable feature in Magento 2.  Consumer competition on the internet is no longer exceptional, thus it’s become vital to choose the most appealing product design. Customers today demand to see all product options (e.g., available colors, size, material, and so on) before making a purchase choice. Adding a variety of options to your products is the best method to suit their needs. Magento 2 custom choices extension is the key to attracting more customers and giving them the feeling that they always have a choice on the Magento 2 platform.

So let’s dive into our guide to add product to the cart programmatically with custom options!

What Are Custom Options?

Customizable options are features that give unique characteristics to simple products (as well as downloadable and virtual products) in Magento 2. 

Simple products, which make up the foundation of a Magento 2 store, are stand-alone items that can be sold separately or as part of more complicated entities like grouped, bundled, and customizable products. The same is true for downloadable and virtual products that are not physically present. One of the types’ peculiarities is that merchants are unable to sell products that have many attribute sets within a single product. As a result, the variety of the products is limited. 

magento-2-products-option

Magento does support custom options for several product types – by its nature. For example, when you sell clothes, color and size choices are custom options that help customers pick items that suit their needs. You can increase the flexibility of your offers by selecting custom options.

READ NOW >>> Compare Magento 2 Layered Navigation Extensions Free & Paid if you want to know more about custom options

Why We Need Custom Options?

Consider this scenario: clients visit a website, and the only product information available is the name of the product and the amount to be purchased.

In the viewpoint of customers, this renders them blank and useless!

Customized options, as shown in the image above, will aid in making the information associated with your product more comprehensive than ever before.

Customers will feel more at ease if they have a variety of options for the things they need to buy, from color to material to even size.

When a consumer buys a product with configurable options, a description of each option displays underneath the product description, and any corresponding markup (or markdown) is applied to the item’s price automatically.

storefront-customizable-option-cart-price-rule-why

If the purchase triggers a cart price rule, the original calculation is applied first to the product price and then to the line item price, with any adjustments made for any customizable options. In the following example, the buyer pays $74.00 for a duffle bag with a monogram customization option. The adjusted price is $88.80 after a $14.80 markup is applied to the original product price.

The purchase of the duffle bag, in this scenario, activates a cart price rule based on the product SKU, which gives the customer a discount and free shipping. Despite the fact that the customized option does not activate the cart price rule, it does apply the discount to the cart items, which includes the markup for the customizable option.

Then your website’s consumer experience will improve! As a result, you can increase your conversation rate and purchases. 

You can CHECK >>> Custom Product Labels For Magento 2 Tips To Steal NOW! to have more information.

How To Add Product To Cart Programmatically With Custom Options

Step 1: Create registration.php file

Add this command line to create registration.php file in app\code\[Vendor]\[Namespace]\

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

\Magento\Framework\Component\ComponentRegistrar::MODULE,

'[Vendor]_[Namespace]',

__DIR__

);

Step 2: Create module.xml file

Copy this code in app\code\[Vendor]\[Namespace]\etc to create module file

<?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="[Vendor]_[Namespace]" setup_version="1.0.0"/>

</config>

How-to-Add-Product-to-Cart-Programmatically-With-Custom-Options-in-Magento-2

Step 3: Create Data.php file

Create Data.php file in app\code\[Vendor]\[Namespace]\Helper

<?php
namespace [Vendor]\[namespace]\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\ProductFactory;
class Data extends AbstractHelper
{
    private $cart
    private $productFactory;
    public function __construct(Context $context, Cart $cart, ProductFactory $productFactory)
    {
        $this->productFactory = $productFactory;
        $this->cart = $cart;
        parent::__construct($context);
    }
    public function getAddCustomProduct($productId)

    {
        $product = $this->productFactory->load($productId);
        $cart = $this->cart;
        $params = array();

        $options = array();

        $params['qty'] = 1;

        $params['product'] = $productId;

        foreach ($product->getOptions() as $o) {

            foreach ($o->getValues() as $value) {

                $options[$value['option_id']] = $value['option_type_id'];
            }

        }
        $params['options'] = $options;

        $cart->addProduct($product, $params);

        $cart->save();
    }

}

5+ Magento 2 Add Custom Option To Product In Cart Problems

Easy to cross bugs

One of the most significant advantages of using a custom option is creating a unique web experience for each web browser. People are more likely to have a positive impression of a corporation that pays them more attention. In other words, clients demand special treatment from internet retailers. The online store system may track all client shopping behaviors and set up a private mode for each customer with the help of product suggestion engines. When a web browser visits your website, he can see a collection of products and recommendations from customers who have already purchased your products.

magento-2-bugs

But go with the custom option benefits is its complexity. You can easily miss some bugs in your code, and once you get in it, you can be stuck in.

Solution: 

We all want to fix the bugs. First, search your bugs on Google before coming to anything else, and your bugs may be familiar with others people.

Then, if you still can not fix this, go to Magento 2 forums. I am sure that all people in these forums can help you.

You can also CHECK >>> Custom Product Labels For Magento 2 Tips To Steal NOW! to have more information. 

Can not add labels for the specific products

Yes, I have to say that is the truth. Default Magento 2 does not let you add labels or labels images for each product you want. Or, if you can do that, the code will be very complex.

Make Group Product and Layered Navigation more complex

Layered Navigation is a Magento 2 catalog navigation feature that allows users to find products faster by filtering the results based on price, category, color, or other product qualities.

Your major goal is to improve your Magento 2 store’s consumer experience by providing the finest shopping circumstances.

group-product

A grouped product is a collection of simple products that are related to one another and grouped together to maximize the likelihood of customers purchasing additional items. Each product in a group can be bought independently or as part of a larger group.

The components of a grouped product are listed as individual products in the shopping basket, but they are sold together.

These two features if very important and also complex.

Solution:

In these two situations, the most effective way is to use a third-party extension. You can choose what extension you want to customize your product.

CHECK NOW >>> Magento 2 Product Label: Can It Boost Your Sales? to see more details 

Not load custom options after saving the product in admin

Imagine creating a few custom options for a product: a field type and dropdown type. After saving the product getting a javascript error in the console, as shown in the screenshot:

data.forEach is not a function.

Solution:

Here is an option from Magento 2 forum that you can refer to:

Create file at below location,

Custom/Modulename/view/adminhtml/requirejs-config.js

var config = {	
    map: {
        '*': {
            "Magento_Ui/js/dynamic-rows/dynamic-rows-grid": 'Custom_Modulename/js/dynamic-rows/dynamic-rows-grid'
        }
    }
};

create a file at the location,

Custom/Modulename/view/adminhtml/web/js/dynamic-rows/dynamic-rows-grid.js

Copy content from the core file to your custom file.

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

Receive payment error with custom options in Magento 2

When consumers use Authorize.net or PayPal to purchase a product with a custom option, they will receive an error message that says, “An error occurred on the server.”, ” Please try placing the order once more.” When you receive such an error, a variety of factors can contribute to the problem. In our case, however, we discovered that the customer had a custom option in the cart that needed to be fixed in Magento core.

http-error-codes-magento-2-add-custom-option-problems

Solution: 

You can try the solution we found on Github:

Go to vendor/magento/module-catalog/Model/Product.php and look for getOptionById method and replace the codes with below:

public function getOptionById($optionId)

{

  $result = null;

  if (is_array($this->getOptions())) {

      /** @var \Magento\Catalog\Model\Product\Option $option */

      foreach ($this->getOptions() as $option) {

          if ($option->getId() == $optionId) {

              $result = $option;

              break;

          }

      }

  }

  return $result;

}

Conclusion

That is how you can add product to cart programmatically with custom options. Take your chance now and see what you can do! 

READ NOW >>> Magento 2 Product Image: Top 4 Practices To Boost Your Sale! to have more details. 

BSS Commerce is one of the leading Multi-platform eCommerce solutions and web development services providers in the world. With experienced and certified developers, we commit to bring high-quality products and services to optimize your business effectively.

CONTACT NOW to let us know your problems. We are willing to support you every time.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.