MAGENTO 2 – ADD ATTRIBUTES TO MINI CART LIST

SHANE BLANDFORD

August 29th, 2018

Recently the team at Orange Collar Media have been working on a custom Magento 2 module for a client that involves modifying the item list in the mini cart. To do this correctly is a bit more involved in Magento 2 than it used to be.

This is due to the mini cart being rendered by the knockout templates. The list of product attributes is built by a function called doGetItemData() located in the file vendor/magento/module-checkout/CustomerData/DefaultItem.php

Quickly looking at this function and it is clear that to get our custom attribute added we need to modify the array being produced.

The correct way to update this array is to create a plugin in our module. However, the doGetItemData()function is not public so we can not intercept this exact function.

Looking at the DefaultItem class we can see that it extends the AbstractItem class. In this class the function getItemData()is a public function and it calls the doGetItemData() function.

This plugin will fire after the getItemData() function and add the custom attribute to the array.

Step 1 — Define the Plugin

In your module di.xml file add the following

<type name="Magento\Checkout\CustomerData\AbstractItem">
    <plugin name="Vendor_Module_DefaultItemPlugin" type="Vendor\Module\Plugin\DefaultItemPlugin" sortOrder="10"  disabled="false" />
</type>

So it looks like this

Example of modification di.xml above.

Step 2 — Create the Plugin

Create a new plugin class in Vendor\Module\Plugin\DefaultItemPlugin.php

<?php

namespace Vendor\Module\Plugin;

class DefaultItemPlugin
{

    public function afterGetItemData(
        \Magento\Checkout\CustomerData\AbstractItem $subject,
        $result,
        \Magento\Quote\Model\Quote\Item $item)
    {
        $data['customattribute'] = $item->getProduct()->getAttributeText('customattribute');

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

}

It should look like this class

See example of the DefaultItemPlugin class above.

Step 3 — Update your template file

Then add this code to your template file.

<Vendor>/<theme>/Magento_Checkout/frontend/web/templates/minicart/item/default.html

<! – ko if: customattribute –>
<! – ko text: customattribute –><! – /ko –>
<! – /ko –>

To get this to work you will need to run

php bin/magento setup:di:compile

SHARE POST

logo

Orange Collar Inc. is based in Denver, CO. We believe in delivering total solutions to our clients from design to support.

2009 – 2020 © ORANGE COLLAR MEDIA​