Create Product Attribute with Drop Down Option in Magento 2 via InstallData.php

In my previous blog “Create Custom Attribute Group & Product Attribute in Magento 2 via InstallData.php” I have explained to create new custom attribute group and the product attribute in Magento 2 programmatically by using InstallData.php. In this blog, I am going to show you how to create new product attribute with drop down option in Magento 2 programmatically.

Step 1: Define new module

In order to create new installable script, first we have to create a file named module.xml in the below file path to define the new module,

File Path: app/code/MyModule/MyDropdownAttribute/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MyModule_MyDropdownAttribute" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

Next, create a file named registration.php in the below file path,

File Path: app/code/MyModule/MyDropdownAttribute/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'MyModule_MyDropdownAttribute',
    __DIR__
);

Step 2: Create setup file InstallData.php

Create a InstallData.php file in the below file path, in this file we have to provide all the information about our new attribute (i.e, Name of the attribute, input type, attribute group name, source model class, etc),

File Path: app/code/MyModule/MyDropdownAttribute/Setup/InstallData.php

<?php
namespace MyModule\MyDropdownAttribute\Setup;
 
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
 
class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;
 
    public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
    }
 
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
 
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'my_custom_size',
            [
                'group' => 'My Custom Attribute Group',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'My Custom Size',
                'input' => 'select',
                'note' => 'My Custom Size',
                'class' => '',
                'source' => 'MyModule\MyDropdownAttribute\Model\Config\Source\Options',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '0',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => true,
                'used_in_product_listing' => true,
                'unique' => false,
                'option' => [ 
                    'values' => [],
                ]
            ]    
        );  
    }
}

Then, create a class file named Options.php in the following file path for the new custom attribute options, This options will be shown in the attribute dropdown.

File Path: app/code/MyModule/MyDropdownAttribute/Model/Config/Source/Options.php

<?php 
namespace MyModule\MyDropdownAttribute\Model\Config\Source;
 
use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Framework\DB\Ddl\Table;
 
class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{ 
    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
        $this->_options = [ 
            ['label'=>'', 'value'=>''],
            ['label'=>'Small', 'value'=>'1'],
            ['label'=>'Medium', 'value'=>'2'],
            ['label'=>'Large', 'value'=>'3']
        ];
        return $this->_options;
    }
 
    /**
     * Get a text for option value
     *
     * @param string|integer $value
     * @return string|bool
     */
    public function getOptionText($value)
    {
        foreach ($this->getAllOptions() as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
        return false;
    }
}

Step 3: Module setup upgrade

After completing the above steps, go to the [magento 2 installed root directory]/bin directory and run the below command in your CLI for enable the new extension,

php magento module:enable MyModule_MyDropdownAttribute

Then, run the below command in CLI to upgrade the setup,

php magento setup:upgrade

Then, clear the cache and check on your admin. Now you can able to see the new product attribute with dropdown option on the admin side like the reference image below,

Reference image:

Create Product Attribute with Drop Down Option in Magento 2 via InstallData.php

Note: The above code has tested in Magento 2.3.

Hope this helps.

Leave a Reply

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