Create product attribute in Magento 2

In Magento 2 we can create product attribute using two way.

  1. From Admin controll panel
  2. Using programmatically

1. Create product attribute using admin panel.

Magento 2 admin controll panel provide feature to add, update and remove product attribute from admin controll panel.

For creating product attribute we need follow the bellow simple step.

Login to Admin controll panel.

Login to admin panel using your username and password.

Goto product attribute.

After login click on Store > Attribute > Product. It’s redirect to product attribute grid.

Adding new Attribute.

Click on “Add New Attribute” button, It’s redirect to new attribute form.

Fill the attribute details as per your needs and click on “Save Attribute” button.

Assign attribute to attribute set.

Click on Store > Attribute > Attribute set, it’s redirect to attribute set grid.

Click on “Default”, It’s redirect to attribute set. In that page you can drag your attribute and move to any product section like general, content…etc which section you want that attribute on edit product form.

After that just click on save button. That attribute is assign to that attribute set with that specific section.

After saving attribute set you can get that attribute in edit product page in admin. Also you can save your custom data to that atttribute.

2. Creating product attribute using programattically.

In Magento 2 we can create product attribute easily by adding some line of code in our custom module.

Before Magento 2.3.x we use InstallData to perform any data level operation in Magento. Using InstallData we can add new data to table or we can modify or remove table data.

Magento 2.3 introduce the data patch and schema patch and the InstallData, UpgradeData, InstallSchema and UpgradeSchema was deprecated in Magento version 2.3.

We create product attribte using both ways.

Create product attribute using InstallData

We need to use UpgradeData when our module is already installed. For me I just creating fresh module so using InstallData we create product attribute.

<?php
//file path: MAGENTO_ROOT/app/code/RS/ProductAttribute/Setup/InstallData.php

namespace RS\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;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;

class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $_eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory EnvSetupfactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->_eavSetupFactory = $eavSetupFactory;
    }

    /**
     * Install Data script
     *
     * @param ModuleDataSetupInterface $setup   Setup Object
     * @param ModuleContextInterface   $context Context Object
     *
     * @return void
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {

        $eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'custom_attr',
            [
            'group' => 'General',
            'type' => 'varchar',
            'sort_order' => 100,
            'label' => 'Custom Attribute 01',
            'input' => 'text',
            'global' => Attribute::SCOPE_GLOBAL,
            'visible' => true,
            'required' => false,
            'user_defined' => true,
            'default' => '',
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
            ]
        );
    }
}

After that we just need to run the setup commands (setup:upgrade and setup:static-contnet:deploy -f).

Create product attribute using data patch

We can use data patch to create attribute and manipulate and table data. We need create product attribute that is manipulate EAV data. So, we use data patch to create product attribute.

This patch is execute only one time. It’s automatically execute when you run setup:upgrade command.

After successfully execute patch it’s register in patch_list table. So, after that patch is no logger execute when we run the setup:upgrade.

<?php
//file path: MAGENTO_ROOT/app/code/RS/ProductAttribute/Setup/Patch/Data/CustomAttrPatch.php

namespace RS\ProductAttribute\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Eav\Setup\EavSetupFactory;

class CustomAttrPatch implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    protected $moduleDataSetup;

    /**
     * @var EavSetupFactory
     */
    protected $eavSetupFactory;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * Default patch method that cover the patch logic
     */
    public function apply()
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        /**
        * Add attributes to the eav/attribute
        */
        $eavSetup->addAttribute(
            Product::ENTITY,
            'custom_attr2',
            [
                'group' => 'General',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Custom Attribute 02',
                'input' => 'text',
                'class' => '',
                'source' => '',
                'global' => Attribute::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => true,
                'default' => '',
                'searchable' => true,
                'filterable' => true,
                'comparable' => false,
                'visible_on_front' => true,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to' => 'simple,configurable,virtual,bundle,downloadable'
            ]
        );
    }

    /**
     * Return the dependency array
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * Return the alias array
     */
    public function getAliases()
    {
        return [];
    }
}

That’s all for creating product attribute using admin panel and programattically.

Fill free to ask me any of the Magento issues or contact me if your need any customisation or other Magento related service.

Will provide you these Magento services click here for more details

Leave your comment

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