Magento 2: Add Category Attribute Using Data Patch

Create Category Attribute Using Data Patch in Magento 2 - Sb Dev Blog

Do we need to add a category attribute using a data patch? Let’s do it.

We will add an extra text field on the category edit page on the admin side. So let’s create a class that implements the below interface.

Magento\Framework\Setup\Patch\DataPatchInterface

We are required to extend the getDependencies() and getAliases() functions along with the apply() function.

We must write logic to create an attribute inside the apply() function. First, it’s time to create a category attribute using the data patch.

Magento 2: Add Category Attribute Using Data Patch

Create a data patch inside the Setup > Patch > Data directory.

<?php
/**
 * @copyright Copyright (c) sbdevblog (https://www.sbdevblog.com)
 */

namespace SbDevBlog\Catalog\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Model\Category;

class addCategoryAttributePatch implements DataPatchInterface
{
    /**
     * ModuleDataSetupInterface
     *
     * @var ModuleDataSetupInterface
     */
    private ModuleDataSetupInterface $moduleDataSetup;
    /**
     * EavSetupFactory
     *
     * @var EavSetupFactory
     */
    private EavSetupFactory $eavSetupFactory;

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

    /**
     * @inheritDoc
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public function apply()
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->addAttribute(Category::ENTITY, 'sbdevcat_attrbute', [
            'type' => 'text',
            'label' => 'SB Category Attribute',
            'input' => 'text',
            'global' => 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' => '',
        ]);
    }
}

Next, we will run the setup:upgrade command, executing the above data patch. Then we can see the sbdevcat_attrbute attribute in the eav_attribute table. Also, we can see the above patch file in the patch_list table.

When an attribute is created, we must allow the admin to save the attribute value for each category. So let’s add a field to the category form. The field type is the text field in this post.

Add a custom field to the category form at admin.

<?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="sbdevcat_attrbute">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="required" xsi:type="boolean">true</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">false</item>
                    </item>
                    <item name="sortOrder" xsi:type="number">50</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">SB Category Attribute</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

That’s it. The field is required in this post. We may make it optional by passing false as the required-entry under the validation block. We can also change the sort order, data type, input type (formElement), and label according to our requirements.

Magento 2: Add Category Attribute Using Data Patch - Sb DevBlog

Thanks for reading this post: Magento 2: Add Category Attributes Using a Data Patch Please subscribe and share SbDevBlog with your connections. Also, please use the comment box to give your suggestions. Thank you.

Click here to create the customer attribute using a data patch. Also, visit the post to create a product attribute using a data patch.

Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

Leave a Reply

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