Add Category Attributes in Magento 2

Occasionally Magento developers will need to extra attributes to the system. Here we explain how to add category attributes in Magento 2.

If you are familiar with adding attributes to Magento 1, you’ll know that they can be added via install scripts and using a specific resource class. Category attributes are added via the Mage_Catalog_Model_Resource_Setup class.

Within the install scripts, we can then use the addAttribute() method of the Mage_Catalog_Model_Resource_Setup to add our given attribute.

In Magento 2, we can use data scripts to add attributes. So here is what you need to do to add a category attribute.

Create Your Module

If you haven’t done so already, a basic module will need to be added and enabled. You can follow the Registering a Magento 2 Custom Module post.

Add the Data Class

The InstallData class will be added within your module’s Setup directory. If you do not have a Setup directory, you can create an empty one.

The InstallData class will be called InstallData.php and will look similar to the following:

// app/code/[Your_Vendor]/[Your_Module]/Setup/InstallData.php
<?php
namespace [Your_Vendor]\[Your_Module]\Setup;
use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Setup\CategorySetupFactory;

class InstallData implements InstallDataInterface
{
    private $categorySetupFactory;

    public function __construct(CategorySetupFactory $categorySetupFactory)
    {
        $this->categorySetupFactory = $categorySetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);
        $entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
        $attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);

        $categorySetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY, 'custom_attribute', [
                'type' => 'int',
                'label' => 'Custom Attribute',
                'input' => 'select',
                'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                'required' => false,
                'sort_order' => 100,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'General Information',
            ]
        );
        $installer->endSetup();
    }
}

You’ll notice that we use the Magento\Catalog\Setup\CategorySetupFactory class in Magento 2. This class is used in the __construct() method via dependency injection.

We can create an instance of $categorySetup using the create() method of the CategorySetupFactory class.

Take note that there are three arguments when using addAttribute():

  • The entity type ID. In this example, it is catalog_category.
  • The attribute code you’ll be using for your new attribute.
  • An array of data to assign to your attribute.

Define the Category Attribute in UI Component

Form elements in the admin are defined using UI Components. The category form specifically using the category_form.xml file to define the default attributes.

Therefore in order for our category attribute to show, we must define our own category_form.xml file and add it into our module’s view/adminhtml/ui_component directory.

// app/code/[Your_Vendor]/[Your_Module]/view/adminhtml/ui_component/category_form.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="options" xsi:type="object">Magento\Config\Model\Config\Source\Yesno</item>
             <item name="config" xsi:type="array">
                 <item name="sortOrder" xsi:type="number">60</item>
                 <item name="dataType" xsi:type="string">string</item>
                 <item name="formElement" xsi:type="string">select</item>
                 <item name="label" xsi:type="string" translate="true">Custom Attribute</item>
             </item>
         </argument>
     </field>
</fieldset>
</form>

The result of this is our category attribute appearing nicely in the admin.

Add Category Attributes in Magento 2

Note: This article is based on Magento CE version 2.1.