How to Set Additional Options in Magento2 Cart Item?

  • Posted by Envision Ecommerce
  • /
  • January 23, 2017
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 [email protected], and don’t forget to share this “How to” blog with your fellow Magento 2 users!