Magento 2 - How to add short_description to cart item?
-
06-10-2020 - |
Question
On the /checkout/cart
page I like to add the short description attribute to the cart items. But if I look in $item->getProduct()->getShortDescription()
I get an empty string, also $item->getProduct()->hasShortDescription()
returns false
.
I also read somewhere that the short_description
attribute isn't loaded automatically and need to add this piece of xml to M2
<?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="short_description"/>
</group>
</config>
But I am unsure of where to add this exactly or that I even need this. So can somebody help me out?
Solution
We can add the custom attribute to catalog_attributes.xml
under etc
folder.
For example:
app/code/Company/Catalog/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="short_description"/>
</group>
</config>
Now, we can get $item->getProduct()->getShortDescription()
.
See more here: vendor/magento/module-sales/etc/catalog_attributes.xml
OTHER TIPS
Full solution as provided by @Khoa TruongDinh
Create a custom module in app/code/vendor/ModuleName/.
app/code/vendor/ModuleName/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="short_description"/>
</group>
</config>
app/code/vendor/ModuleName/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="vendor_ModuleName" setup_version="0.0.1">
<sequence>
<module name="Magento_Sales"/>
<module name="Magento_Catalog"/>
</sequence>
</module>
</config>
app/code/vendor/ModuleName/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'vendor_ModuleName',
__DIR__
);
Now we can add in any phtml where it is needed. echo $product->getShortDescription()
Run magento commands:
php bin/magento module:enable vendor_ModuleName
php bin/magento setup:upgrade
php bin/magento cache:clean
Check frontend