0

In shopping car view i can see only configure option that i selected in product page. i want to display customized option value too. enter image description here

last option gem color is customized option.

while viewing cart enter image description here

it display only 2 values. i want color value to display which i am selected. Can someone guide me to achiev this. Thanks in advance

0

You can create a custom module and with help of layout and observer, you can display customized option value in the shopping cart view.

I assume you will create a custom module name "Company_MyModule".

So create an empty module with the name "Company_MyModule" (or anything you like) and after that follow the steps below to create other files.

NOTE : This solution only will not works for configurable and grouped products.

step 1)

Create catalog_product_view.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/view/frontend/layout/

File: catalog_product_view.xml

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product.info.addtocart">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Company_MyModule::catalog/product/view/addtocart.phtml</argument>
            </action>
        </referenceBlock> 
        <!--<referenceBlock name="product.info.addtocart.additional">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Company_MyModule::catalog/product/view/addtocart.phtml</argument>
            </action>
        </referenceBlock>-->
    </body>
</page>

Step 2)

Create another layout file checkout_cart_item_renderers.xml to override cart item renderer under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/view/frontend/layout/

File: checkout_cart_item_renderers.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.cart.item.renderers">
            <referenceBlock name="default" template="Company_MyModule::cart/item/default.phtml" />
            <referenceBlock name="simple" template="Company_MyModule::cart/item/default.phtml" />
        </referenceBlock>
    </body>
</page>

step 3)

Creaete a template file addtocart.phtml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/view/frontend/templates/catalog/product/view

File : addtocart.phtml

<?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; ?>
        <!-- Custom Input Field -->
        <div>
            <select id="customizeoptions_color" name="customizeoptions[color]">
                <option value="red">Red</option>
                <option value="green">Green</option>
                <option value="blue">Blue</option>
                <option value="black">Black</option>
                <option value="white">White</option>

            </select>            
        </div>
        <!-- Custom Input Field -->
        <br>

        <div class="actions">
            <button 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>

step 4)

Create another template file default.phtml for cart item renderer under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/view/frontend/templates/cart

File : default.phtml

<?php

$_item = $block->getItem();
$product = $_item->getProduct();
$isVisibleProduct = $product->isVisibleInSiteVisibility();
/** @var \Magento\Msrp\Helper\Data $helper */
$helper = $this->helper('Magento\Msrp\Helper\Data');
$canApplyMsrp = $helper->isShowBeforeOrderConfirm($product) && $helper->isMinimalPriceLessMsrp($product);
?>
<tbody class="cart item">
    <tr class="item-info">
        <td data-th="<?php echo $block->escapeHtml(__('Item')); ?>" class="col item">
            <?php if ($block->hasProductUrl()):?>
                <a href="<?php /* @escapeNotVerified */ echo $block->getProductUrl() ?>"
                   title="<?php echo $block->escapeHtml($block->getProductName()) ?>"
                   tabindex="-1"
                   class="product-item-photo">
            <?php else:?>
                <span class="product-item-photo">
            <?php endif;?>
            <?php echo $block->getImage($block->getProductForThumbnail(), 'cart_page_product_thumbnail')->toHtml(); ?>
            <?php if ($block->hasProductUrl()):?>
                </a>
            <?php else: ?>
                </span>
            <?php endif; ?>
            <div class="product-item-details">
                <strong class="product-item-name">
                    <?php if ($block->hasProductUrl()):?>
                        <a href="<?php /* @escapeNotVerified */ echo $block->getProductUrl() ?>"><?php echo $block->escapeHtml($block->getProductName()) ?></a>
                    <?php else: ?>
                        <?php echo $block->escapeHtml($block->getProductName()) ?>
                    <?php endif; ?>
                </strong>
                <?php if ($_options = $block->getOptionList()):?>
                    <dl class="item-options">
                        <?php foreach ($_options as $_option) : ?>
                            <?php $_formatedOptionValue = $block->getFormatedOptionValue($_option) ?>
                            <dt><?php echo $block->escapeHtml($_option['label']) ?></dt>
                            <dd>
                                <?php if (isset($_formatedOptionValue['full_view'])): ?>
                                    <?php /* @escapeNotVerified */ echo $_formatedOptionValue['full_view'] ?>
                                <?php else: ?>
                                    <?php /* @escapeNotVerified */ echo $_formatedOptionValue['value'] ?>
                                <?php endif; ?>
                            </dd>
                        <?php endforeach; ?>
                    </dl>
                <?php endif;?>
                <?php if ($messages = $block->getMessages()): ?>
                    <?php foreach ($messages as $message): ?>
                        <div class="cart item message <?php /* @escapeNotVerified */ echo $message['type'] ?>"><div><?php echo $block->escapeHtml($message['text']) ?></div></div>
                    <?php endforeach; ?>
                <?php endif; ?>
                <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
                <?php if ($addInfoBlock): ?>
                    <?php echo $addInfoBlock->setItem($_item)->toHtml() ?>
                <?php endif;?>
            </div>
        </td>

        <?php if ($canApplyMsrp): ?>
            <td class="col msrp" data-th="<?php echo $block->escapeHtml(__('Price')); ?>">
                <span class="pricing msrp">
                    <span class="msrp notice"><?php /* @escapeNotVerified */ echo __('See price before order confirmation.'); ?></span>
                    <?php $helpLinkId = 'cart-msrp-help-' . $_item->getId(); ?>
                    <a href="#" class="action help map" id="<?php /* @escapeNotVerified */ echo($helpLinkId); ?>" data-mage-init='{"addToCart":{"helpLinkId": "#<?php /* @escapeNotVerified */ echo $helpLinkId;?>","productName": "<?php /* @escapeNotVerified */ echo $product->getName(); ?>","showAddToCart": false}}'>
                        <span><?php /* @escapeNotVerified */ echo __("What's this?"); ?></span>
                    </a>
                </span>
            </td>
        <?php else: ?>
            <td class="col price" data-th="<?php echo $block->escapeHtml(__('Price')); ?>">
                <?php echo $block->getUnitPriceHtml($_item); ?>
            </td>
        <?php endif; ?>
        <td class="col qty" data-th="<?php echo $block->escapeHtml(__('Qty')); ?>">
            <div class="field qty">
                <label class="label" for="cart-<?php /* @escapeNotVerified */ echo $_item->getId() ?>-qty">
                    <span><?php /* @escapeNotVerified */ echo __('Qty') ?></span>
                </label>
                <div class="control qty">
                    <input id="cart-<?php /* @escapeNotVerified */ echo $_item->getId() ?>-qty"
                           name="cart[<?php /* @escapeNotVerified */ echo $_item->getId() ?>][qty]"
                           data-cart-item-id="<?php /* @escapeNotVerified */ echo $_item->getSku() ?>"
                           value="<?php /* @escapeNotVerified */ echo $block->getQty() ?>"
                           type="number"
                           size="4"
                           title="<?php echo $block->escapeHtml(__('Qty')); ?>"
                           class="input-text qty"
                           maxlength="12"
                           data-validate="{required:true,'validate-greater-than-zero':true}"
                           data-role="cart-item-qty"/>
                </div>
            </div>
        </td>

        <td class="col subtotal" data-th="<?php echo $block->escapeHtml(__('Subtotal'));?>">
            <?php if ($canApplyMsrp): ?>
                <span class="cart msrp subtotal">--</span>
            <?php else: ?>
                <?php echo $block->getRowTotalHtml($_item); ?>
            <?php endif; ?>
        </td>
    </tr>
    <tr class="item-actions">
        <td colspan="100">
            <div class="actions-toolbar">
                <?php /* @escapeNotVerified */ echo $block->getActions($_item) ?>
            </div>
        </td>
    </tr>
</tbody>

step 5)

Creae event observer xml file events.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc

In that file, we are declaring two events.

File: events.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="checkout_cart_product_add_after">
        <observer name="company_mymodule_checkout_cart_product_add_after" instance="Company\MyModule\Observer\CheckoutCartProductAddAfterObserver" />
    </event>
    <event name="sales_model_service_quote_submit_before">
        <observer name="company_mymodule_sales_model_service_quote_submit_before" instance="Company\MyModule\Observer\SalesModelServiceQuoteSubmitBeforeObserver" />
    </event>
</config>

step 6)

Create first event observer class file CheckoutCartProductAddAfterObserver.php under YOUR-MAGENTO-ROOT/app/code/Company/MuModule/Observer

File: CheckoutCartProductAddAfterObserver.php

<?php
namespace Company\MyModule\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Serialize\SerializerInterface;

class CheckoutCartProductAddAfterObserver implements ObserverInterface
{
    /**
     * @var \Magento\Framework\View\LayoutInterface
     */
    protected $_layout;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;
    protected $_request;
    /**
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\View\LayoutInterface $layout
     */

     /**
       * @var SerializerInterface
     */
     private $serializer;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\View\LayoutInterface $layout,
        \Magento\Framework\App\RequestInterface $request,
         SerializerInterface $serializer
    )
    {
        $this->_layout = $layout;
        $this->_storeManager = $storeManager;
        $this->_request = $request;
        $this->serializer = $serializer;
    }
    /**
     * Add order information into GA block to render on checkout success pages
     *
     * @param EventObserver $observer
     * @return void
     */
    public function execute(EventObserver $observer)
    {
        /* @var \Magento\Quote\Model\Quote\Item $item */
        //$item = $observer->getQuoteItem();
        $item = $observer->getEvent()->getData('quote_item');
        $item = ($item->getParentItem() ? $item->getParentItem() : $item);

        $additionalOptions = array();
        if ($additionalOption = $item->getOptionByCode('additional_options')){
            $additionalOptions = (array) $this->serializer->unserialize($additionalOption->getValue());
        }
        $post = $this->_request->getParam('customizeoptions');
        if(is_array($post))
        {
            foreach($post as $key => $value)
            {
                if($key == '' || $value == '')
                {
                    continue;
                }
                $additionalOptions[] = [
                    'label' => $key,
                    'value' => $value
                ];
            }
        }
        if(count($additionalOptions) > 0)
        {
            $item->addOption(array(
                'code' => 'additional_options',
                'value' => $this->serializer->serialize($additionalOptions)
            ));
        }
        return $this;
        /* To Do */
        // Edit Cart - May need to remove option and readd them
        // Pre-fill remarks on product edit pages
        // Check for comparability with custom option
    }
}

step 8)

Create another event observer SalesModelServiceQuoteSubmitBeforeObserver.php ( to save the custom option in order item table ) under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Observer

File : SalesModelServiceQuoteSubmitBeforeObserver.php

<?php
namespace Company\MyModule\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Psr\Log\LoggerInterface;

class SalesModelServiceQuoteSubmitBeforeObserver implements ObserverInterface
{
    private $quoteItems = [];
    private $quote = null;
    private $order = null;

    /**
       * @var SerializerInterface
     */
     private $serializer; 

     protected $logger;


    public function __construct(        
         SerializerInterface $serializer,
         LoggerInterface $logger 
    )
    {
        $this->serializer = $serializer;
        $this->logger =  $logger;
    }


    /**
     * Add order information into GA block to render on checkout success pages
     *
     * @param EventObserver $observer
     * @return void
     */
    public function execute(EventObserver $observer)
    {

        $this->quote = $observer->getQuote();
        $this->order = $observer->getOrder();
        // can not find a equivalent event for sales_convert_quote_item_to_order_item
        /* @var  \Magento\Sales\Model\Order\Item $orderItem */
        foreach($this->order->getItems() as $orderItem)
        {
            if(!$orderItem->getParentItemId() && $orderItem->getProductType() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
            {

                if($quoteItem = $this->getQuoteItemById($orderItem->getQuoteItemId())){
                    if ($additionalOptionsQuote = $quoteItem->getOptionByCode('additional_options'))
                    {                       

                        //To do
                        // - check to make sure element are not added twice
                        // - $additionalOptionsQuote - may not be an array
                        if($additionalOptionsOrder = $orderItem->getProductOptionByCode('additional_options'))
                        {
                            $additionalOptions = array_merge($additionalOptionsQuote, $additionalOptionsOrder);
                        }
                        else
                        {
                            $additionalOptions = $additionalOptionsQuote;
                        }                        


                        if(count($additionalOptions->toArray()) > 0)
                        {

                            $options = $orderItem->getProductOptions();
                            $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
                            $orderItem->setProductOptions($options);
                        }

                    }
                }
            }
        }
    }

    private function getQuoteItemById($id)
    {
        if(empty($this->quoteItems))
        {
            /* @var  \Magento\Quote\Model\Quote\Item $item */
            foreach($this->quote->getItems() as $item)
            {
                //filter out config/bundle etc product
                if(!$item->getParentItemId() && $item->getProductType() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
                {
                    $this->quoteItems[$item->getId()] = $item;
                }
            }
        }
        if(array_key_exists($id, $this->quoteItems))
        {
            return $this->quoteItems[$id];
        }
        return null;
    }
}

step 9) Run below command to compile and cache clean

php bin/mageto setup:di:compile php bin/mageto cache:flush

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.