6

Magento 2 how to get custom attribute value in cart page and weight in mini cart.

3 Answers 3

8

For displaying product attribute in minicart

1. Create file catalog_attributes.xml Vendor/Module/etc

<?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="weight"/>
    </group>
</config>

2.Create di.xml in Vendor/Module/etc

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
   <preference for="Magento\Checkout\CustomerData\DefaultItem" type="Vendor\Module\CustomerData\DefaultItem" />
</config>

3.Create file DefaultItem.php inside Vendor\Module\CustomerData

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\CustomerData;

use Magento\Framework\App\ObjectManager;

/**
 * Default item
 */
class DefaultItem extends \Magento\Checkout\CustomerData\DefaultItem
{
         /**
         * @var \Magento\Catalog\Helper\Image
         */
        protected $imageHelper;

        /**
         * @var \Magento\Msrp\Helper\Data
         */
        protected $msrpHelper;

        /**
         * @var \Magento\Framework\UrlInterface
         */
        protected $urlBuilder;

        /**
         * @var \Magento\Catalog\Helper\Product\ConfigurationPool
         */
        protected $configurationPool;

        /**
         * @var \Magento\Checkout\Helper\Data
         */
        protected $checkoutHelper;

        /**
         * Escaper
         *
         * @var \Magento\Framework\Escaper
         */
        private $escaper;
    public function __construct(
        \Magento\Catalog\Helper\Image $imageHelper,
        \Magento\Msrp\Helper\Data $msrpHelper,
        \Magento\Framework\UrlInterface $urlBuilder,
        \Magento\Catalog\Helper\Product\ConfigurationPool $configurationPool,
        \Magento\Checkout\Helper\Data $checkoutHelper,
        \Magento\Framework\Escaper $escaper = null
    ) {
        $this->configurationPool = $configurationPool;
        $this->imageHelper = $imageHelper;
        $this->msrpHelper = $msrpHelper;
        $this->urlBuilder = $urlBuilder;
        $this->checkoutHelper = $checkoutHelper;
        $this->escaper = $escaper ?: ObjectManager::getInstance()->get(\Magento\Framework\Escaper::class);
    }

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

        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_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(),
            'weight' => $this->item->getProduct()->getWeight(),
            '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()),
        ];
    }
    
}
?>

4.Create File default.html inside Current Theme app/design/frontend/Vendor/Themename/Magento_Checkout/web/template/minicart/item

<!--
/**
 * Copyright © Magento, Inc. 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}, html: 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.value) -->
                                <span data-bind="html: option.value.join('<br>')"></span>
                            <!-- /ko -->
                            <!-- ko ifnot: Array.isArray(option.value) -->
                                <span data-bind="html: option.value"></span>
                            <!-- /ko -->
                        </dd>
                        <!-- /ko -->
                    </dl>
                </div>
            </div>
            <!-- /ko -->
            <!-- ko if: weight -->
            <div data-bind="html: 'Weight : ' + weight"></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,
                           'data-cart-item-id': product_sku
                           }, value: qty"
                           type="number"
                           size="4"
                           class="item-qty cart-item-qty">
                    <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>
8
  • i tried with this its not working please help me on this Jul 26, 2018 at 13:41
  • did you use same code as i have used weight on same code ? Jul 26, 2018 at 14:15
  • yes i have created new module for this and did as you did . Jul 27, 2018 at 5:08
  • can you do one setting in "weight" attribute to use in "product listing" ? Jul 27, 2018 at 5:30
  • any idea on Magento 2 how to get total productsweight in order summary Jul 27, 2018 at 9:04
14

Create File catalog_attributes.xml inside Vendor/Module/etc or any existing module.

<?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="product-arrtibute"/>
    </group>
</config>

Now call that attribute in cart page or minicart like as

if dropdown type attribute

$_item->getProduct()->getAttributeText('product-attribute')

else

$_item->getProduct()->getProductAttribute()
8
  • 1
    For cart page override file Magento_Checkout/templates/cart/item/default.phtml and write here Jul 24, 2018 at 10:59
  • You can create catalog_attributes.xml file in any existing module under etc directory no need to create new one module for it Jul 24, 2018 at 11:00
  • thank you very much for your support i did like this <?php echo $_item->getProduct()->getProductAttribute('length') ?> is this right way its text field attribute in admin panel Jul 24, 2018 at 11:09
  • can you try this : <?php echo $_item->getProduct()->getLength() ?> Jul 24, 2018 at 11:15
  • Ansar Husain any idea on Magento 2 how to get weight in mini cart Jul 24, 2018 at 11:51
0

2nd answer good for templates not dependent on section data, but where section data is needed (e.g. on mini-cart) the first answer is better but can be simplified to just add the additional custom attribute(s) to section data. No need to completely overwrite the core class, just extend it. So Vender/Module/CustomerData/DefaultItem.php just needs to have:

<?php

namespace Vendor\Module\CustomerData;

/**
 * Add custom attribute(s) to Default item
 */
class DefaultItem extends \Magento\Checkout\CustomerData\DefaultItem
{
    protected function doGetItemData()
    {
        $data = parent::doGetItemData();
        $data['custom-attr-id'] = $this->item->getProduct()->getCustomAttrId();
        return $data;
    }
}

Now you can reference your custom-attr-id in the JS code, same as standard attributes.

This XML addition makes the attribute available on the quote item in PHP so you can use it where needed i.e. here when adding to section data for JS.

<group name="quote_item">
    <attribute name="custom-attr-id"/>
</group>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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