Prepopulating Dropdown Attributes in Magento
As a senior developer working on an e-commerce project for a client, I often face challenges involving customization of the product attributes within the Magento admin panel. One such common requirement is to pre-populate dropdown attribute values from an external API whenever a new product is created or an existing one is edited.
In this post, we will explore how to achieve this functionality using Magento’s extension development capabilities and some PHP and curl implementation for fetching data from the remote site.
Understanding the Requirement
The client wants a ‘Manufacturer’ attribute that behaves like a dropdown list on the product creation/editing pages in the admin panel. The values of this dropdown should be populated dynamically each time, retrieved from an API endpoint on a remote server using curl.
The API returns a JSON response containing the manufacturer names and IDs. The ID field must remain persistent but the name can change occasionally. Therefore, we need to ensure that any changes on the external site are reflected in our Magento store’s dropdown.
Creating a Custom Extension
To begin, let’s create a custom extension that will handle this functionality. In your Magento installation root directory, navigate to:
app/code/YourVendor/ManufacturerSync/etc/
Within the etc folder, create a new configuration file named di.xml.
<!-- vendor/yourvendor/manufacturersync/etc/di.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Product">
<plugin name="yourvendor_manufacturersync_product_attribute_populator"
type="YourVendor\ManufacturerSync\Model\AttributePopulator"/>
</type>
</config>
This di.xml file will enable a plugin on the Magento\Catalog\Model\Product class. The next step is to create the actual plugin.
Implementing the Attribute Populator
Navigate to:
app/code/YourVendor/ManufacturerSync/Model/
Create a new file named AttributePopulator.php.
<?php
namespace YourVendor\ManufacturerSync\Model;
use Magento\Framework\App\Http\Client\Curl;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Attribute\AbstractAttribute;
class AttributePopulator
{
const MANUFACTURER_API_URL = 'https://example.com/api/manufacturers';
protected $curl;
protected $request;
public function __construct(
Curl $curl,
RequestInterface $request
) {
$this->curl = $curl;
$this->request = $request;
}
public function beforeSave(Product $product)
{
if (!$product->getId()) { // If it's a new product being created
$manufacturers = $this->fetchManufacturers();
$attributeCode = 'manufacturer'; // Replace with your attribute code
$product->setData($attributeCode, reset(array_keys($manufacturers)));
}
}
protected function fetchManufacturers()
{
try {
$response = $this->curl->get(self::MANUFACTURER_API_URL);
return json_decode($response->getContent(), true);
} catch (LocalizedException $e) {
throw new LocalizedException(__('Unable to fetch manufacturers from API: %1', $e->getMessage()));
}
}
}
This AttributePopulator class uses Magento’s built-in Curl client to fetch data from the remote API. Before saving a product, it checks if this is a new entity (using $product->getId() == null) and then populates the manufacturer attribute with the first available value fetched from the API.
Conclusion
Populating dropdown attributes dynamically in Magento requires understanding of plugin development and integrating external data sources using PHP and curl. By creating a custom extension and implementing a pre-save hook, we can ensure that our product’s ‘Manufacturer’ field is always up-to-date with the latest values from an external site.
Remember to replace ‘YourVendor’, ‘manufacturersync’, and API URLs with your actual vendor name, module code, and valid endpoints. Also, make sure your local Magento installation has proper access to the internet for curl requests to succeed.
If you find this guide useful or have any other questions about Magento extension development, feel free to explore more resources on https://laravelcompany.com. We regularly publish posts covering advanced topics in e-commerce software engineering.