Back to Top

Magento2- How to create product custom attribute from installer in custom module

Updated 21 February 2024

Here we learn in Magento2 – How to create product custom attribute (Dropdown type) from the installer file in the custom module.

Here we create a select type custom attribute in which options come from the option list file.

1=>First we need to create an installer file named InstallData.php in our custom module Setup folder

 complete path: app/code/ModuleNameSpace/YourModuleName/Setup

<?php

namespace ModuleNameSpace\YourModuleName\Setup;

use Magento\Eav\Setup\EavSetup; 
use Magento\Eav\Setup\EavSetupFactory /* For Attribute create  */;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;
    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory; 
        /* assign object to class global variable for use in other class methods */
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        
        /**
         * Add attributes to the eav/attribute
         */
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY,'yourcustomattribute_id');
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'yourcustomattribute_id',/* Custom Attribute Code */
            [
                'group' => 'Product Details',/* Group name in which you want 
											  to display your custom attribute */
                'type' => 'int',/* Data type in which formate your value save in database*/
                'backend' => '',
                'frontend' => '',
                'label' => 'Your Custom Attribute Label', /* label of your attribute*/
                'input' => 'select',
                'class' => '',
                'source' => 'ModuleNameSpace\YourModuleName\Model\Config\Source\Options',
								/* Source of your select type custom attribute options*/
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
									/*Scope of your attribute */
                'visible' => true,
                'required' => true,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false
            ]
        );
    }
}

2=> Now we create option source file class Options for the custom attribute options list

Searching for an experienced
Magento Company ?
Find out More

File Name– Options.php

File Path– app/code/ModuleNameSpace/YourModuleName/Model/Config/Source

<?php

namespace ModuleNameSpace\YourModuleName\Model\Config\Source;

use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Framework\DB\Ddl\Table;

/**
 * Custom Attribute Renderer
 *
 * @author      Webkul Core Team <[email protected]>
 */
class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * @var OptionFactory
     */
    protected $optionFactory;

    /**
     * @param OptionFactory $optionFactory
     */
    /*public function __construct(OptionFactory $optionFactory)
    {
        $this->optionFactory = $optionFactory;  
        //you can use this if you want to prepare options dynamically  
    }*/

    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
		/* your Attribute options list*/
        $this->_options=[ ['label'=>'Select Options', 'value'=>''],
						  ['label'=>'Option1', 'value'=>'1'],
						  ['label'=>'Option2', 'value'=>'2'],
						  ['label'=>'Option3', '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;
    }

    /**
     * Retrieve flat column definition
     *
     * @return array
     */
    public function getFlatColumns()
    {
        $attributeCode = $this->getAttribute()->getAttributeCode();
        return [
            $attributeCode => [
                'unsigned' => false,
                'default' => null,
                'extra' => null,
                'type' => Table::TYPE_INTEGER,
                'nullable' => true,
                'comment' => 'Custom Attribute Options  ' . $attributeCode . ' column',
            ],
        ];
    }
}

After adding these files install your custom module in your magento2 instance

then by terminal run the following command in your magento2 root directory

php bin/magento setup:upgrade

Now, your product create page will open with your custom attribute as following 🙂

Selection_055

. . .

Leave a Comment

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


2 comments

  • Steve Winnington
  • swamy chaluvadi
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home