0

Can anybody guide me how can I add the related products ti recently added item to cart in minicart in Magento2

I know that the magento2 minicart content is loaded by the Js layout.

I have created one module override the Customerdata by adding di.xml in my module But it did not work.

module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Mypackage_Minicartrelated" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Checkout"/>   
        </sequence>
    </module>
</config>

app/code/Mypackage/Minicartrelated/etc/di.xml code

<config>
    <type name="Magento\Checkout\CustomerData\Cart">
        <plugin name="Mypackage_Minicartrelated" type="Mypackage\Minicartrelated\Plugin\CustomerData" sortOrder="1"/>
    </type>
</config>

app/code/Mypackage/Minicartrelated/Plugin/CustomerDataCart.php

<?php

namespace Mypackage\Minicartrelated\Plugin\CustomerData;  
use Magento\Customer\CustomerData\SectionSourceInterface;
class Cart { 
    public method afterGetSectionData(\Magento\Checkout\CustomerData\Cart $subject, $result)
    {
        // Get the previous data
        $data = $result;
        $data .="test"; 
        return $data;
    }
}

But it gives me error Error: [object Object]

throw new Error(jqXHR);

Can anybody can give me right direction how can I show related products in Magento2 minicart.

  • I have show the related products in minicart – Ram singh Sep 10 '16 at 13:42
1

I have solved the error and shown the related product of recent added item to cart in minicart content

I have created updated my module to override the content.html

app/code/Mymodule/Minicartrelated/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\CustomerData\AbstractItem">
    <plugin name="Mymodule_Minicartrelated" type="Magentoservices\Minicartrelated\Plugin\DefaultItem" disabled="false" sortOrder="10"/>
</type>
<type name="Magento\Checkout\CustomerData\Cart">
    <plugin name="Mymodule_Minicartrelated" type="Mymodule\Minicartrelated\Plugin\Cart" disabled="false" sortOrder="1"/>  
</type>  
</config

app/code/Mymodule/Minicartrelated/etc/module.xml

<!--
            /**
             * Copyright © 2016 Magento. All rights reserved.
             * See COPYING.txt for license details.
             */
            -->
            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
                <module name="Mymodule_Minicartrelated" setup_version="1.0.0" schema_version="1.0.0">
                    <sequence>
                        <module name="Magento_Checkout"/>   
                    </sequence>
                </module>
            </config>

app/code/Mymodule/Minicartrelated/Plugin/DefaultItem.php

In this file i have sent the data of related product with item data 

            <!--
            /**
             * Copyright © 2016 Magento. All rights reserved.
             * See COPYING.txt for license details.
             */
            -->
            <?php

            namespace Mymodule\Minicartrelated\Plugin;


            use Magento\Catalog\Api\ProductRepositoryInterface;
            use Magento\Catalog\Model\Product;
            use Magento\Quote\Model\Quote\Item;
            use \Magento\Catalog\Helper\Image;

            class DefaultItem
            {

                protected $productRepo;
                 protected $imageHelper;
                public function __construct(ProductRepositoryInterface $productRepository,\Magento\Catalog\Helper\Image $imageHelper)
                {
                    $this->productRepo = $productRepository;
                    $this->imageHelper = $imageHelper;
                }
                public function aroundGetItemData($subject, \Closure $proceed, Item $item)
                {
                    $data = $proceed($item);

                    /** @var Product $product */
                    $product = $this->productRepo->getById($item->getProduct()->getId());
                    $relatedProducts = $product->getRelatedProducts();
                    $relateditem= array();
                    $result=[];
                    foreach($relatedProducts as $related){ 
                    $related = $this->productRepo->getById($related->getId());
                    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                    $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');  
                    $currentStore = $storeManager->getStore(); 
                    $priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data'); // Instance of Pricing Helper
                    $imageHelper = $this->imageHelper->init($related->getProductForThumbnail(), 'mini_cart_product_thumbnail');
                   // $imageUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $related->getImage();    
                    //$imageHelper = $this->imageHelper->init($related->getProductForThumbnail(), 'mini_cart_product_thumbnail'); 
                    $result['relateditemsdata'] = [ 
                        'relatedid'        => $related->getId(),
                        'related_sku'      => $related->getSku(),
                        'relatedpermalink' => $related->getProductUrl(),
                        'relatedtitle'     => $related->getName(),
                        'relatedraw_price' => $priceHelper->currency($related->getPrice(), true, false),
                        'relatedproduct_image' =>$related->getProductForThumbnail(), 
                        'related_image' =>$currentStore->getUrl().'pub/media/catalog/product'.$related->getImage() 
                    ];

                    }  

                    return array_merge($data,$result); 
                }
            }

app/code/Mymodule/Minicartrelated/view/frontend/layout/default.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">
                <update handle="checkout_cart_sidebar_item_renderers"/>
                <update handle="checkout_cart_sidebar_item_price_renderers"/>
                <update handle="checkout_cart_sidebar_total_renderers"/>
                <body>
                    <referenceBlock name="head.components">
                        <block class="Magento\Framework\View\Element\Js\Components" name="checkout_page_head_components" template="Magento_Checkout::js/components.phtml"/>
                    </referenceBlock> 
                    <referenceContainer name="header-wrapper">
                        <block name="minicart">
                            <arguments>
                                <argument name="jsLayout" xsi:type="array">
                                    <item name="types" xsi:type="array"/>
                                    <item name="components" xsi:type="array">
                                        <item name="minicart_content" xsi:type="array">
                                            <item name="component" xsi:type="string">Magento_Checkout/js/view/minicart</item>
                                            <item name="config" xsi:type="array">
                                                <item name="template" xsi:type="string">Mymodule_Minicartrelated/minicart/content</item> 
                                            </item>
                                            <item name="children" xsi:type="array">
                                                <item name="subtotal.container" xsi:type="array">
                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                    <item name="config" xsi:type="array">
                                                        <item name="displayArea" xsi:type="string">subtotalContainer</item>
                                                    </item>
                                                    <item name="children" xsi:type="array">
                                                        <item name="subtotal" xsi:type="array">
                                                            <item name="component" xsi:type="string">uiComponent</item>
                                                            <item name="config" xsi:type="array">
                                                                <item name="template" xsi:type="string">Magento_Checkout/minicart/subtotal</item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                                <item name="extra_info" xsi:type="array">
                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                    <item name="config" xsi:type="array">
                                                        <item name="displayArea" xsi:type="string">extraInfo</item>
                                                    </item>
                                                </item>
                                                <item name="promotion" xsi:type="array">
                                                    <item name="component" xsi:type="string">uiComponent</item>
                                                    <item name="config" xsi:type="array">
                                                        <item name="displayArea" xsi:type="string">promotion</item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </argument>
                            </arguments>
                        </block>
                    </referenceContainer>
                </body>
            </page>

app/code/Mymodule/Minicartrelated/view/frontend/layout/checkout_cart_sidebar_item_renderers.xml

            <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
                <body>
                    <referenceBlock name="minicart">
                        <arguments>
                            <argument name="jsLayout" xsi:type="array">
                                <item name="components" xsi:type="array">
                                    <item name="minicart_content" xsi:type="array">
                                        <item name="children" xsi:type="array">
                                            <item name="item.renderer" xsi:type="array">
                                                <item name="config" xsi:type="array">
                                                    <item name="template" xsi:type="string">Mymodule_Minicartrelated/minicart/item/default</item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </argument> 
                        </arguments>
                    </referenceBlock>
                </body>
            </page>

app/code/Mymodule/Minicartrelated/view/frontend/requirejs-config.js

 var config = {
                map: {
                    '*': {
                        'Magento_Checkout/template/minicart/content.html':
                            'Mymodule_Minicartrelated/template/minicart/content.html'
                    }
                }
            };

app/code/Mymodule/Minicartrelated/view/frontend/web/template/minicart/item/default.html

<!--
            /**
             * Copyright © 2016 Magento. All rights reserved.
             * See COPYING.txt for license details.
             */
            -->
            <li class="item product product-item" data-role="product-item">
                <div class="product">
                    <!-- ko if: product_has_url -->
                    <a data-bind="attr: {href: product_url, title: product_name}" tabindex="-1" class="product-item-photo">
                        <!-- ko foreach: $parent.getRegion('itemImage') -->
                            <!-- ko template: {name: getTemplate(), data: item.product_image} --><!-- /ko -->
                        <!-- /ko -->
                    </a>
                    <!-- /ko -->
                    <!-- ko ifnot: product_has_url -->
                    <span class="product-item-photo">
                        <!-- ko foreach: $parent.getRegion('itemImage') -->
                            <!-- ko template: {name: getTemplate(), data: item.product_image} --><!-- /ko -->
                        <!-- /ko -->
                    </span>
                    <!-- /ko -->

                    <div class="product-item-details">
                        <strong class="product-item-name">
                            <!-- ko if: product_has_url -->
                            <a data-bind="attr: {href: product_url}, text: product_name"></a>
                            <!-- /ko -->
                            <!-- ko ifnot: product_has_url -->
                                <!-- ko text: product_name --><!-- /ko -->
                            <!-- /ko -->
                        </strong>

                        <!-- ko if: options.length -->
                        <div class="product options" data-mage-init='{"collapsible":{"openedState": "active", "saveState": false}}'>
                            <span data-role="title" class="toggle"><!-- ko i18n: 'See Details' --><!-- /ko --></span>

                            <div data-role="content" class="content">
                                <strong class="subtitle"><!-- ko i18n: 'Options Details' --><!-- /ko --></strong>
                                <dl class="product options list">
                                    <!-- ko foreach: { data: options, as: 'option' } -->
                                    <dt class="label"><!-- ko text: option.label --><!-- /ko --></dt>
                                    <dd class="values">
                                        <!-- ko if: Array.isArray(option) -->
                                            <span data-bind="html: option.value.join('<br>')"></span>
                                        <!-- /ko -->
                                        <!-- ko ifnot: Array.isArray(option) -->
                                            <span data-bind="html: option.value"></span>
                                        <!-- /ko -->
                                    </dd>
                                    <!-- /ko -->
                                </dl>
                            </div>
                        </div>
                        <!-- /ko -->

                        <div class="product-item-pricing">
                            <!-- ko if: canApplyMsrp -->

                            <div class="details-map">
                                <span class="label" data-bind="i18n: 'Price'"></span>
                                <span class="value" data-bind="i18n: 'See price before order confirmation.'"></span>
                            </div>
                            <!-- /ko -->
                            <!-- ko ifnot: canApplyMsrp -->
                            <!-- ko foreach: $parent.getRegion('priceSidebar') -->
                                <!-- ko template: {name: getTemplate(), data: item.product_price, as: 'price'} --><!-- /ko -->
                            <!-- /ko -->
                            <!-- /ko --> 
                            <div class="details-qty qty">
                                <label class="label" data-bind="i18n: 'Qty', attr: {
                                       for: 'cart-item-'+item_id+'-qty'}"></label>
                                <input data-bind="attr: {
                                       id: 'cart-item-'+item_id+'-qty',
                                       'data-cart-item': item_id,
                                       'data-item-qty': qty
                                       }, value: qty"
                                       type="number"
                                       size="4"
                                       class="item-qty cart-item-qty"
                                       maxlength="12"/>
                                <button data-bind="attr: {
                                       id: 'update-cart-item-'+item_id,
                                       'data-cart-item': item_id,
                                       title: $t('Update')
                                       }"
                                        class="update-cart-item"
                                        style="display: none">
                                    <span data-bind="i18n: 'Update'"></span>
                                </button>
                            </div>
                        </div>

                        <div class="product actions">
                            <!-- ko if: is_visible_in_site_visibility -->
                            <div class="primary">
                                <a data-bind="attr: {href: configure_url, title: $t('Edit item')}" class="action edit">
                                    <span data-bind="i18n: 'Edit'"></span>
                                </a>
                            </div>
                            <!-- /ko -->
                            <div class="secondary">
                                <a href="#" data-bind="attr: {'data-cart-item': item_id, title: $t('Remove item')}"
                                   class="action delete">
                                    <span data-bind="i18n: 'Remove'"></span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </li>

app/code/Mymodule/Minicartrelated/view/frontend/web/template/minicart/content.html

<!--
            /**
             * Copyright © 2016 Magento. All rights reserved.
             * See COPYING.txt for license details.
             */
            -->
            <div class="block-title">
                <strong>
                    <span class="text"><!-- ko i18n: 'My Cart' --><!-- /ko --></span>
                    <span
                        class="qty empty"
                        data-bind="css: { empty: cart().summary_count == 0 },
                                   attr: { title: $t('Items in Cart') }">
                        <!-- ko text: cart().summary_count --><!-- /ko -->
                    </span>
                </strong>
            </div>

            <div class="block-content">
                <button type="button"
                        id="btn-minicart-close"
                        class="action close"
                        data-action="close"
                        data-bind="attr: { title: $t('Close') }">
                    <span><!-- ko i18n: 'Close' --><!-- /ko --></span>
                </button>

                <!-- ko if: cart().summary_count -->
                    <div class="items-total">
                        <span class="count"><!-- ko text: cart().summary_count --><!-- /ko --></span>
                        <!-- ko if: cart().summary_count == 1 -->
                            <!-- ko i18n: 'item' --><!-- /ko -->
                        <!-- /ko -->
                        <!-- ko if: cart().summary_count > 1 -->
                            <!-- ko i18n: 'items' --><!-- /ko -->
                        <!-- /ko -->
                    </div>

                    <!-- ko if: cart().possible_onepage_checkout -->
                        <!-- ko foreach: getRegion('subtotalContainer') -->
                            <!-- ko template: getTemplate() --><!-- /ko -->
                        <!-- /ko -->
                    <!-- /ko -->

                    <!-- ko foreach: getRegion('extraInfo') -->
                        <!-- ko template: getTemplate() --><!-- /ko -->
                    <!-- /ko -->

                    <!-- ko if: cart().possible_onepage_checkout -->
                    <strong class="subtitle"><!-- ko i18n: 'Recently added item(s)' --><!-- /ko --></strong>
                    <div data-action="scroll" class="minicart-items-wrapper">
                        <ol id="mini-cart" class="minicart-items" data-bind="foreach: { data: cart().items, as: 'item' }">
                            <!-- ko foreach: $parent.getRegion($parent.getItemRenderer(item.product_type)) -->
                                <!-- ko template: {name: getTemplate(), data: item, afterRender: function() {$parents[1].initSidebar()}} --><!-- /ko -->
                            <!-- /ko -->
                        </ol>
                    </div> 

                    <div id="minicart-related" class="minicart-related">You may also be interested in:
                    <div data-bind="foreach: { data: cart().items, as: 'item' }"> 
                    <ol>
                        <li class="item product product-item">
                            <div class="product">
                                <a class="product-item-photo">
                                <span class="product-image-container" style="width: 75px;">
                                    <span  class="product-image-wrapper" style="height: 88px;">
                                        <img data-bind="attr: {src: item.relateditemsdata.related_image}" class="product-image-photo"  style="width: 75px; height: 88px;">
                                    </span>
                                </span>
                                </a>
                                <div class="product-item-details">
                                    <strong class="product-item-name">
                                        <a data-bind="attr: {href: item.relateditemsdata.relatedpermalink}, html:item.relateditemsdata.relatedtitle"></a>
                                    </strong> 
                                    <div class="product options">
                                        <div data-bind="html:item.relateditemsdata.related_sku"></div>
                                        <div class="productprice">
                                        <div data-bind="html:item.relateditemsdata.relatedraw_price"></div> 
                                        </div> 
                                    </div>
                                </div>  
                                <a data-bind="attr: {href: item.relateditemsdata.relatedpermalink},html: 'View'"></a>
                            </div>
                        </li>
                    </ol>
                    </div>      
                    </div>
                    <div class="actions">
                        <div class="primary">
                            <button
                                    id="top-cart-btn-checkout"
                                    type="button"
                                    class="action primary checkout"
                                    data-bind="attr: {title: $t('Go to Checkout')}">
                                <!-- ko i18n: 'Go to Checkout' --><!-- /ko -->
                            </button>
                            <div data-bind="html: cart().extra_actions"></div>
                        </div>
                    </div>
                    <!-- /ko -->
                <!-- /ko -->

                <!-- ko if: cart().summary_count -->

                <!-- /ko -->

                <!-- ko ifnot: cart().summary_count -->
                    <strong class="subtitle empty" data-bind="visible: closeSidebar()">
                        <!-- ko i18n: 'You have no items in your shopping cart.' --><!-- /ko -->
                    </strong>
                    <!-- ko if: cart().cart_empty_message -->
                        <p class="minicart empty text"><!-- ko text: cart().cart_empty_message --><!-- /ko --></p>

                        <div class="actions">
                            <div class="secondary">
                                <a class="action viewcart" data-bind="attr: {href: shoppingCartUrl}">
                                    <span><!-- ko text: $t('View and edit cart') --><!-- /ko --></span>
                                </a>
                            </div>
                        </div>
                    <!-- /ko -->
                <!-- /ko -->

                <!-- ko if: cart().summary_count -->
                <div class="actions">
                    <div class="secondary">
                        <a class="action viewcart" data-bind="attr: {href: shoppingCartUrl}">
                            <span><!-- ko i18n: 'View and edit cart' --><!-- /ko --></span>
                        </a>
                    </div>
                </div>
                <!-- /ko -->

                <div id="minicart-widgets" class="minicart-widgets">
                    <!-- ko foreach: getRegion('promotion') -->
                        <!-- ko template: getTemplate() --><!-- /ko -->
                    <!-- /ko -->
                </div>
            </div>
            <!-- ko foreach: getRegion('sign-in-popup') -->
            <!-- ko template: getTemplate() --><!-- /ko -->
            <!-- /ko -->

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.