How to Set Additional Options in Magento2 Cart Item?

  • author-img Nidhi Arora
  • 7 years
how-to-set-additional-options-in-magento2-cart-item

Sometimes, setting up some additional options in cart item is required to showcase specific details along with some products in Magento 2 cart. There are many different ways to do so, but we’re going to explain a simple and easy approach to do it, i.e. Event observer pattern. Read on to learn how to set additional options in cart item in Magento2:

First off, you need to define an event in the events.xml file by means of the code mentioned below in a module.

Path to file: Envision/Demo/ect/event.xml

<?xml version=”1.0″?>

<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Event/etc/events.xsd”>

<event name=”catalog_product_load_after”>

<observer name=”set_additional_options” instance=”Envision\Demo\Observer    \SetAdditionalOptions”/>

</event>

</config>

After defining afore-shared code, you need to add following code in your observer file.

Path to file:  Envision/Demo/Observer/SetAdditionalOptions.php

<?php

namespace Envision\Demo\Observer;

use Magento\Framework\Event\ObserverInterface;

use Magento\Framework\App\RequestInterface;

class SetAdditionalOptions implements ObserverInterface

{

/**

* @var RequestInterface

*/

protected $_request;

/**

* @param RequestInterface $request

*/

public function __construct(

RequestInterface $request

) {

$this->_request = $request;

}

/**

* @param \Magento\Framework\Event\Observer $observer

*/

public function execute(\Magento\Framework\Event\Observer $observer)

{

// Check and set information according to your need

if ($this->_request->getFullActionName() == ‘checkout_cart_add’) { //checking when product is adding to cart

$product = $observer->getProduct();

$additionalOptions = [];

$additionalOptions[] = array(

‘label’ => “Some Label”,

‘value’ => “Your Information”,

);

$observer->getProduct()->addCustomOption(‘additional_options’, serialize($additionalOptions));

}

}

}

If you still have any query regarding this “How to” or would like to add some suggestions to this solution, let us know your feedback or query at sales@envisionecommerce.com, and don’t forget to share this “How to” blog with your fellow Magento 2 users!

Download Blog

ENQUIRY

Ready to Get Started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    815 Brazos St STE 500, Austin,
    TX 78701, USA