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.