Blog

Create Product Attribute programmatically in magento2

In this article, we will find out how to create a product attribute in Magento 2 programatically. As you know, Magento 2 manage Product by EAV model, so we cannot simply add an attribute for product by adding a column for product table.

Today  I am going to explain, how we can create text & drop down attribute for Products in Magento 2.
There are two ways to create the drop down attribute in Magento.
1 -> Manually : Go To admin panel,  Store -> Attributes -> Product .
2 -> Programmatically .

Overview of Adding Product Attribute Programmatically

Create file InstallData.php

We will start with the InstallData class which located in app/code/Thecoachsmb/ProductAttribute/Setup/InstallData.php. The content for this file:

1. Create Text custom attribute

Here are all lines code of InstallSchema.php to create product attribute programmically.

<?php
namespace Thecoachsmb\ProductAttribute\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;

class InstallData implements InstallDataInterface
{
	private $eavSetupFactory;

	public function __construct(EavSetupFactory $eavSetupFactory)
	{
		$this->eavSetupFactory = $eavSetupFactory;
	}
	
	public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
	{
		$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
		$eavSetup->addAttribute(
			\Magento\Catalog\Model\Product::ENTITY,
			'sample_attribute',
			[
				'type' => 'text',
				'backend' => '',
				'frontend' => '',
				'label' => 'Sample Atrribute',
				'input' => 'text',
				'class' => '',
				'source' => '',
				'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
				'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,
				'apply_to' => ''
			]
		);
	}
}

As you can see, all the addAttribute method requires is:

  • The type id of the entity which we want to add attribute
  • The name of the attribute
  • An array of key value pairs to define the attribute such as group, input type, source, label…

All done, please run the upgrade script php bin/magento setup:upgrade to install the module and the product attribute sample_attribute will be created.

After run upgrade complete, please run php bin/magento setup:static-content:deploy and go to product from admin to check the result.

2. Create Dropdown custom attribute

Today  I am going to explain, how we can create drop down attribute for Products in Magento 2.
There are two ways to create the drop down attribute in Magento.
1 -> Manually : Go To admin panel,  Store -> Attributes -> Product .
2 -> Programmatically .

In this blog I am covering how we can create the drop down attribute programmatically,
So let’s start :
Step 1 : create InstallData.php file : Thecoachsmb\ProductAttribute\Setup\InstallData.php
Now In this file, create an Array of the attributes that you want to add as below.

$attributeGroup = 'Test Group';
        $attributes = [
            'attribute_code' => [
                'group'              => $attributeGroup,
                'input'              => 'select',
                'type'               => 'int',
                'label'              => 'Attribute Label',
                'visible'            => true,
                'required'           => false,
                'user_defined'               => true,
                'searchable'                 => false,
                'filterable'                 => false,
                'comparable'                 => false,
                'visible_on_front'           => false,
                'visible_in_advanced_search' => false,
                'is_html_allowed_on_front'   => false,
                'used_for_promo_rules'       => true,
                'source'                     => 'Thecoachsmb\ProductAttribute\Model\Config\Source\Options',
                'frontend_class'             => '',
                'global'                     =>  \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'unique'                     => false,
                'apply_to'                   => 'simple,grouped,configurable,downloadable,virtual,bundle'
            ],...
          ];

Step 2 : Now Add and Assign Attribute to Group and Attribute Set.

// Add Attribute
// Magento\Eav\Setup\EavSetupFactory  $this->eavSetupFactory
// Magento\Framework\Setup\ModuleDataSetupInterface $setup
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
            foreach ($attributes as $attribute_code => $attributeOptions) {
                $eavSetup->addAttribute(
                    \Magento\Catalog\Model\Product::ENTITY,
                    $attribute_code,
                    $attributeOptions
                );
            }
//Assign 
            foreach ($attributes as $attribute_code => $attributeOptions) {

                // Class \Magento\Eav\Model\AttributeManagement

                $this->attributeManagement->assign(
                    'catalog_product',
                    $attributeSet->getId(),
                    $groupId,
                    $attribute_code,
                    $attributeSet->getCollection()->getSize() * 10
                );
            }

Note :
$attributeSet : you can load the attribute collection and loop for it or Can pass specific id instead.
$groupId : Magento\Eav\Model\Entity\Attribute\Group : you can get the group id with the help of this class.

Now , Options for drop down attribute , you can add options directly as a array.
and another approach is to use class Magento\Eav\Model\Entity\Attribute\Source\AbstractSource  as follows :

<?php

namespace Thecoachsmb\ProductAttribute\Model\Config\Source;

class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
    * Get all options
    *
    * @return array
    */
    public function getAllOptions()
    {
        $this->_options = [
                ['label' => __('No'), 'value'=>'0'],
                ['label' => __('Yes'), 'value'=>'1'],
                ['label' => __('Other'), 'value'=>'2']
            ];

    return $this->_options;

    }

}

Please read each line carefully, so that you can create the attributes easily.

One thought on “Create Product Attribute programmatically in magento2

  1. Hi Sonal, i am new in Magento 2, so i will have lots of questions. Will this code have output on frontend? ,I’m aiming for the select menu. Because on adobe tutorials they have backend,source, and frontend folders.,.i have try Mage2gen generator,. and there, there is no frontend,and backend., and i dont have displayed atribut status on frontend of the store,. but on backend everything works fine. Thanks

Leave a Reply

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