Creating New Category Attributes in Magento 2

While developing Magento 2 website, many times you may require to create new category attributes as per your requirement. But by default, there is no option on the admin side to add category attribute in Magento 2. Thus we have to create an installable script to add new category attribute. So, here is the blog which will help you to create new category attribute in Magento 2 programmatically by using some simple steps.

Step 1: Module Registration

To create an installable script, first, we have to create a new custom module with the mandatory file named registration.php as like the sample file path is given below,

Sample File Path: app/code/BlogTreat/CategoryAttribute/registration.php

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

Step 2: Module Configuration

Create another mandatory file named module.xml as like the below file path to define new Magento 2 extension,

Sample File Path: app/code/BlogTreat/CategoryAttribute/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="BlogTreat_CategoryAttribute" setup_version="1.0.0">
    </module>
</config>

Step 3: Create a Setup File

Then, create the setup file named InstallData.php as like the below file path,

Sample File Path: app/code/BlogTreat/CategoryAttribute/Setup/InstallData.php

In this setup file, we have added the code to create new category attribute.

<?php
namespace BlogTreat\CategoryAttribute\Setup;
  
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

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

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

    /**
     * {@inheritdoc}
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        /**
         * Add attributes to the eav/attribute
         */
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'custom_attribute',
            [
                'group' => 'General Information',
                'type' => 'varchar',
                'label' => 'Custom Attribute',
                'input' => 'text',
                'required' => false,
                'sort_order' => 100,
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'user_defined' => true,
                'is_used_in_grid' => true,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => true,
            ]
        );

        $setup->endSetup();
    }
}

In the above code, you can see the global param with the value ScopedAttributeInterface::SCOPE_GLOBAL. Which means, the attribute is created with the scope level as global. You may also create the attribute with the scope level as either website or store. You can find the class Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface for your further reference.

Step 4: Show Category Attribute in Admin Form

In the latest Magento 2 versions, the category form on the admin panel is created via the configuration file category_form.xml. You can found the configuration file in the path vendor/magento/module-catalog/view/adminhtml/ui_component/category_form.xml, so we need to create the same configuration file in our module and add our category attribute to the category form as follows,

Sample File Path: app/code/BlogTreat/CategoryAttribute/view/adminhtml/ui_component/category_form.xml

<?xml version="1.0" ?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="general">
        <field name="custom_attribute">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">false</item>
                    </item>
                    <item name="sortOrder" xsi:type="number">100</item>
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="formElement" xsi:type="string">input</item>
                    <item name="label" translate="true" xsi:type="string">Custom Attribute</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

After completing all the above steps run the below SSH command in your Magento 2 installed root directory,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check whether the extension has been successfully installed in Magento 2 admin.

Once the extension has been installed, you can be able to view the newly created category attribute in admin side as shown in the reference screenshot below,

Creating New Category Attributes in Magento 2

Read Also: Create Custom Attribute Group & Product Attribute in Magento 2 via InstallData.php

Hope this helps.

One Comment on “Creating New Category Attributes in Magento 2”

Leave a Reply

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