Add Custom Product Attribute to Mini-Cart in Magento 2

checkoutcustom-attributesmagento2mini-cart

I have to use a custom product attribute in the mini cart and the full cart view.
After creating the file /etc/catalog_attributes.xml in my module folder i could read my custom attribute in the full cart view at base.url/checkout/cart.

/etc/catalog_attributes.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Catalog:etc/catalog_attributes.xsd">
    <group name="quote_item">
        <attribute name="custom_attribute"/>
    </group>
</config>

I now can access the custom_attribute via $product->getData("custom_attribute").
But this doesn't work for the minicart.

Is there any way to add the attribute to the minicart view?

Best Answer

Adding the attribute to the collection is working exactly as you describe, for the cart AND the minicart.

You also need to overwrite \Magento\Checkout\CustomerData\DefaultItem::doGetItemData to provide a new attribute, as shown here with the brand attribute:

protected function doGetItemData()
{
    $imageHelper = $this->imageHelper->init($this->getProductForThumbnail(), 'mini_cart_product_thumbnail');
    $productName = $this->escaper->escapeHtml($this->item->getProduct()->getName());
    $productBrand = $this->escaper->escapeHtml($this->item->getProduct()->getAttributeText('brand'));

    return [
        'options' => $this->getOptionList(),
        'qty' => $this->item->getQty() * 1,
        'item_id' => $this->item->getId(),
        'configure_url' => $this->getConfigureUrl(),
        'is_visible_in_site_visibility' => $this->item->getProduct()->isVisibleInSiteVisibility(),
        'product_id' => $this->item->getProduct()->getId(),
        'product_name' => $productName,
        'product_brand' => $productBrand,
        'product_sku' => $this->item->getProduct()->getSku(),
        'product_url' => $this->getProductUrl(),
        'product_has_url' => $this->hasProductUrl(),
        'product_price' => $this->checkoutHelper->formatPrice($this->item->getCalculationPrice()),
        'product_price_value' => $this->item->getCalculationPrice(),
        'product_image' => [
            'src' => $imageHelper->getUrl(),
            'alt' => $imageHelper->getLabel(),
            'width' => $imageHelper->getWidth(),
            'height' => $imageHelper->getHeight(),
        ],
        'canApplyMsrp' => $this->msrpHelper->isShowBeforeOrderConfirm($this->item->getProduct())
            && $this->msrpHelper->isMinimalPriceLessMsrp($this->item->getProduct()),
    ];
}

Please use a preference for overwriting the method.

And then the html template vendor/magento/module-checkout/view/frontend/web/template/minicart/item/default.html will have to be overwritten in order to add the placeholder like <!-- ko text: product_brand --><!-- /ko --> in it.

Related Topic