How to Create Product Attributes in Magento 2 Programmatically 

Magento 2 Product attributes play an important role in providing customers with various options and influencing their purchasing decisions on an ecommerce platform. 

In Magento 2, creating product attributes programmatically can be valuable, especially when dealing with multiple attributes quickly. This blog will guide you through the process of creating a new product attribute in Magento 2 using a custom module.

Steps to Create Product Attributes in Magento Programmatically 

Step 1: Setting up the Module

Create a file named `registration.php` in the following path: app/code/DCKAP/ProductAttribute/registration.php

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

Step 2: Defining Module Name

Create a `module.xml` file in the path: app/code/DCKAP/ProductAttribute/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="DCKAP_ProductAttribute" setup_version="1.0.1"></module>
</config>

Step 3: Creating a Custom Attribute

Now, create a custom attribute using a setup/patch. Create a file named NewArrivalAttribute.php in the path: app/code/DCKAP/ProductAttribute/Setup/Patch/Data/NewArrivalAttribute.php

<?php

namespace DCKAP\ProductAttribute\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class NewArrivalAttribute implements DataPatchInterface, PatchRevertableInterface
{
    private $eavSetupFactory;
    private $moduleDataSetup;

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

    public function apply()
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'new_arrivals',
            [
                'type' => 'int', 
                'label' => 'New Arrivals',
                'input' => 'boolean',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'required' => false,
                'sort_order' => 100,
                'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_STORE,
                'used_in_product_listing' => true,
                'visible_on_front' => true,
            ]
        );
    }

    public function revert()
    {
        // Implement revert logic if needed
    }

    public function getAliases()
    {
        return [];
    }

    public static function getDependencies()
    {
return [];
    }
}

Recommended Read: How to Create Custom API and Use CRUD Operations in Magento 2

Attribute Settings

Type

The data type of the attribute. In this case, ‘int’ is used for a boolean attribute representing Yes/No values.

(text, date, boolean, decimal, integer, Price, Media image, dropdown, multiple select, text area, file, gallery, websites, category IDs, Country, Region.)

Label

The label is the human-readable name for the attribute, displayed in the admin panel.

Input

Defines the input type for the attribute.

Source

Specifies the source model for the attribute. For boolean attributes, ‘Magento\Eav\Model\Entity\Attribute\Source\Boolean’ is used.

Required

This determines whether the attribute is mandatory (true) or optional (false) while creating a product.

Sort Order

The position of the attribute relative to others. Lower values appear first.

Global

Defines the scope of the attribute. ‘SCOPE_STORE’ means it is store-specific.

Used in Product Listing

Indicates whether the attribute is used in product listing grids.

Visible on Frontend

Determines if the attribute is displayed on the product page in the front end.

You can customize product attributes to suit your specific ecommerce needs by adjusting the above settings.

getAliases() Method

This method is used to get aliases for the patch. Aliases are alternative names for a patch that might be used to refer to it. In the provided code, an empty array is returned. 

If there were aliases for the patch, they would be specified in this array. Aliases are often used when renaming patches or providing alternative names to simplify referring to them.

revert() Method

This method contains the logic to revert changes made by the patch. If the patch modifies the database schema or data, this method handles the reverse operation to undo those changes. 

In the above code, the method is currently empty, indicating that no specific logic for reverting changes has been implemented. Depending on the nature of your patch, you need to implement logic here to undo any modifications made during the apply() method.

getDependencies() Method

This method returns an array of patch class names that should be executed before the current patch. It helps define the order in which patches should be applied. In the code, an empty array is returned, indicating no dependencies for this patch. 

If your patch depends on the successful execution of another patch, you can specify the class name(s) of those patches in this array. Magento ensures that the specified dependencies are applied before the current patch.

Read Also: Magento 2 Controller Response Types

Step 4: Installing the Module

After creating the module, install it by running the following commands:

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

SCREENSHOT

Conclusion

We can efficiently create product attributes in Magento 2 programmatically. This approach proves beneficial when dealing with multiple attributes, allowing for a faster and more streamlined process in enhancing your ecommerce store.

About The Author

We take the guesswork out of ecommerce.
Schedule a consultation call today