How to Programmatically Add Option Values to a Dropdown Attribute in Magento 2?

How to Programmatically Add Option Values to a Dropdown Attribute in Magento 2

Hello Magento Friends,

Dropdown attributes (or select attributes) in Magento 2 are very common attributes to use when providing customers with pre-defined options for products, such as color, size, brand, etc. Dropdown attributes help standardize your product data and the overall shopping experience for your customers.

Magento version upgrade

In many scenarios, the store owner or developer will require to programmatically add new option values rather than manually do it within the admin panel, especially with an extensive catalog of products or with an automated setup.

This blog post will provide a detailed step by step guide on how to add option values programmatically to a dropdown attribute in Magento 2.

Steps to Programmatically Add Option Values to a Dropdown Attribute in Magento 2:

Step 1: Create a file in your Magento root directory at the below path 

magento_root_directory\saveDropdownOptions.php

Add the code as given below

<?php
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/../app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

try {
    $entityType = 'catalog_product';

    $eavConfig = $objectManager->get(\Magento\Eav\Model\Config::class);
    $eavSetup = $objectManager->get(\Magento\Eav\Setup\EavSetup::class);
    $storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);

    $stores = $storeManager->getStores();
    $storeArray[0] = "All Store Views";
    foreach ($stores as $store) {
        $storeArray[$store->getId()] = $store->getName();
    }

    $attributeCode = 'color';  // your dropdown attribute code
    $newOptions = ['Sky Blue', 'Dark Green', 'Neon Yellow'];

    $attribute = $eavConfig->getAttribute($entityType, $attributeCode);

    if (!$attribute || !$attribute->getAttributeId()) {
        throw new \Exception("Attribute '$attributeCode' not found.");
    }

    foreach ($newOptions as $value) {
        try {
            $option = [];
            $option['attribute_id'] = $attribute->getAttributeId();

            $str = '"' . $value . '"';
            $option['value'][$str][0] = str_replace('"', '', $str);

            foreach ($storeArray as $storeKey => $store) {
                $option['value'][$str][$storeKey] = str_replace('"', '', $str);
            }

            $eavSetup->addAttributeOption($option);

            echo "Option '$value' added successfully to attribute '$attributeCode'." . PHP_EOL;
        } catch (\Exception $e) {
            echo "Failed to add option '$value': " . $e->getMessage() . PHP_EOL;
        }
    }

    echo "Attribute option values have been associated to '$attributeCode' successfully." . PHP_EOL;

} catch (\Exception $e) {
    echo "Script error: " . $e->getMessage() . PHP_EOL;
}

Output:

Programmatically Add Option Values to a Dropdown Attribute in Magento 2 output

Conclusion:

Programmatically adding dropdown attribute option choices in Magento 2 is clean and scalable. The alternative of relying on data patches for consistent behaviour of your module over time, or running an ad-hoc script, is more efficient and correct than entering values manually.

By following the steps above, you can efficiently handle attribute option values in Magento 2 and keep your store’s product data well-organized.

Hire Magento Programmer

FAQ

  1. What is a dropdown attribute in Magento 2?

A dropdown attribute, also called a select attribute, is a way for you to create a list of the pre-defined values a product can have. For example, which size, which colour, or which brand. This attribute makes sure products have standardized information across the store.

  1. Why should I add attribute options programmatically instead of manually?

You can add attribute options from the admin panel manually; however, adding attribute options programmatically is much faster compared to using the admin panel, especially when we have a lot of data already created or want to set up an automated process or work with multi-store systems. Adding programmatically also reduces human error.

  1. Will customers see the new options immediately?

Yes. The moment you add options to the dropdown attribute, you will see the options available in the product edit page in admin panel, and if assigned the products with the dropdown attribute to, the customer will see them on the frontend.

Previous Article

How to Implement Bottom Tab Navigation in a React Native App?

Next Article

Critical Adobe Commerce Security Patch APSB25-71 Released

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨