Fetching Product Custom Attribute in Magento 2 Custom Shipping Module
In Magento 2, retrieving product custom attributes within a custom shipping module can be straightforward if approached correctly. Let’s dive into the solution to your problem.
Understanding the Issue
You’re attempting to fetch the volweight custom attribute of product ID 5 from your custom shipping carrier model located at app\code\{MODULE_NAME}\CustomShipping\Model\Carrier\Custom.php. However, you’re facing difficulties despite trying various suggestions from the Magento community forums and StackOverflow.
The Common Mistake
The main issue lies in how you’re using the Object Manager. While it’s possible to get objects via the ObjectManager, it’s considered an anti-pattern and can lead to performance issues. Instead, we should use the proper dependency injection system provided by Magento 2.
The Proper Approach: Dependency Injection
To fetch product data correctly, you need to inject the necessary dependencies into your model using constructor or class-level injection. This ensures that you’re following best practices and maintaining a clean separation of concerns.
Here’s how you can refactor your code:
- First, make sure you have properly defined your custom module configuration in
app/code/{MODULE_NAME}/etc/module.xml.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework: Module/etc/module.xsd">
<module name="{MODULE_NAME}" setup_version="1.0.0">
<sequence>
<module name="Magento_Theme"/>
</sequence>
</module>
</config>
- In your
app/code/{MODULE_NAME}/registration.phpfile, register the module:
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'{MODULE_NAME}',
__DIR__
);
- Now, let’s refactor your custom shipping carrier model:
<?php
namespace {MODULE_NAME}\CustomShipping\Model\Carrier;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Math\Vector;
use Magento\Quote\Model\Quote\Item;
use Magento\Shipping\Model\Rate\Result;
class Custom extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
\Magento\Shipping\Model\Carrier\CarrierInterface
{
/**
* @var string
*/
protected $_code = '{MODULE_NAME}';
/**
* @var bool
*/
protected $_isFixed = true;
/**
* Custom constructor.
*
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
* @param \Magento\Quote\Model\Quote\Item $quoteItem
* @param \Magento\Catalog\Model\Product $product
*/
public function __construct(
ScopeConfigInterface $scopeConfig,
ResultFactory $rateResultFactory,
Item $quoteItem,
Product $product
) {
parent::__construct($scopeConfig, $rateResultFactory);
$this->_scopeConfig = $scopeConfig;
$this->_quoteItem = $quoteItem;
$this->_product = $product;
}
// Rest of your methods remain the same
/**
* Fetch product data
*
* @param int $id Product ID
* @return array
*/
protected function getProductData($id)
{
return $this->_product->load($id)->getData();
}
}
In this refactored code, we’re injecting the ScopeConfigInterface, ResultFactory, Item (Quote Item), and Product models into our constructor. This ensures that we have access to these dependencies without using the Object Manager.
Retrieving Custom Product Attribute
Now you can retrieve your custom attribute from within the model:
public function collectRates(\Magento\Shipping\Model\Rate\Request $request)
{
// ... existing code
if ($request->getAllItems()) {
foreach ($request->getAllItems() as $item) {
$productData = $this->getProductData($item->getProductId());
if (isset($productData['volweight'])) {
$volWeight = $productData['volweight'];
// Process the volWeight attribute as needed
}
}
}
// ... rest of your code
}
In this example, we’re using the collectRates method to iterate through all items in the quote. For each item, we get the product data using our protected getProductData method and check if the volweight attribute exists.
Conclusion
Retrieving custom product attributes within a Magento 2 shipping module is straightforward when following the proper dependency injection approach. By avoiding the Object Manager anti-pattern and injecting necessary dependencies, you can maintain clean, performant code that adheres to Magento’s best practices.
Remember to carefully test your changes in a development environment before deploying them to production.
For more advanced topics on Magento 2 custom shipping modules, consider exploring our comprehensive guide at Laravel Company.
Happy coding!