2

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.

6

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()

  • Is there anything I need to get this file loaded in developer mode? Or how am I to call the attribute? I am attempting $item->getDataByKey('desiredAttribute'); and $item->getDesiredAttribute(); and neither of those work. Issuing get_class($item) yields Magento\Quote\Model\Quote\Item as the class, so that matches the quote_item above I believe. – Joshua Fricke Mar 13 '18 at 18:09
  • @JoshuaFricke Please check the updated Answer. – MagePsycho Mar 15 '18 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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