Magento 2 – Make Product Attribute Available in QuoteItem

magento2shipping-methods

Working on a modification to shipping in Magento 2 and need to have a conditional based on a product attribute which is not currently exposed. How can this be done?

In my Shipping class, I can get access to the product in these two ways (productFactory is passed into construct of class):

$allItems = $request->getAllItems();
foreach ($allItems as $item) {
    //First way
    $desiredAttribute = $item->getData('desiredAttribute');
    $desiredAttribute = $item->getDataByKey('desiredAttribute');
    $productData = $item->getData();
    //Second way
    $product = $this->productFactory->create()->load($item->getId());
    $desiredAttribute = $product->getData('desiredAttribute');
    $desiredAttribute = $product->getDataByKey('desiredAttribute');
    $productData = $product->getData();
}

Neither have the custom attribute visible. I tried setting the attribute available for Promo code = Yes, but that still does not work. Can definitely see some data about the product such as dimensions and such which would be expected at this point. I can see in the $product object a protected array called _attributesByCode which does display this, however accessing the attribute by key is not working. Thanks in advance.

Final solution leveraging the XML from the answer below my code ended up looking something like this:

$allItems = $request->getAllItems();
foreach ($allItems as $item) {
    $desiredAttribute = $item->getProduct()->getDesiredAttribute();
}

If this attribute is a set of options it will return the optionId which you can use to get the optionText if need be by some additional code.

Best Answer

In order to make custom product attribute available in quote item, simply add the attribute in the file: Vendor/Module/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="desiredAttribute"/>
    </group>
</config>

And you can simply get the product attribute via item object as: $item->getProduct()->getDesiredAttribute()

Related Topic