Magento 2: How to Create a Category using Data Patch

Magento 2 How to Create a Category using Data Patch

Hello Magento Friends,

Magento 2’s flexibility allows developers to automate store setup using data patches, a structured way to insert or update data during module installation or upgrade. One common use case is creating product categories programmatically. This is especially useful when setting up new environments, deploying across multiple stores, or managing multi-language setups.

Magento version upgrade

In this blog, we’ll guide you through creating a new category using a data patch in Magento 2.

Steps to Create a Category using Data Patch in Magento 2:

Step 1: We need to create a “Createbestsellerscategory.php“ file inside our extension at the following path

app\code\Vendor\Extension\Setup\Patch\Data\Createbestsellerscategory.php

Then add the code as follows

<?php
namespace Vendor\Extension\Setup\Patch\Data;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Framework\App\Config\Storage\WriterInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Store\Model\Store;

class Createbestsellerscategory implements DataPatchInterface
{
    private $moduleDataSetup;
    private $categoryFactory;
    private $categoryRepository;
    private $configWriter;

    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CategoryFactory $categoryFactory,
        CategoryRepositoryInterface $categoryRepository,
        WriterInterface $configWriter
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->categoryFactory = $categoryFactory;
        $this->categoryRepository = $categoryRepository;
        $this->configWriter = $configWriter;
    }

    public function apply()
    {
        $this->moduleDataSetup->getConnection()->startSetup();

        $parentCategoryId = 2;
        $categoryName = 'Best Sellers';
        $baseUrlKey = 'best-sellers';
        $urlKey = $baseUrlKey;

        $existingCategory = $this->categoryFactory->create()
            ->getCollection()
            ->addAttributeToFilter('parent_id', $parentCategoryId)
            ->addAttributeToFilter('name', $categoryName)
            ->getFirstItem();

        $i = 1;
        while (true) {
            $urlKeyExists = $this->categoryFactory->create()
                ->getCollection()
                ->addAttributeToFilter('parent_id', $parentCategoryId)
                ->addAttributeToFilter('url_key', $urlKey)
                ->getFirstItem();
            if (!$urlKeyExists || !$urlKeyExists->getId()) {
                break;
            }
            $urlKey = $baseUrlKey . '-' . $i;
            $i++;
        }

        if (!$existingCategory || !$existingCategory->getId()) {
            $category = $this->categoryFactory->create();
            $category->setName($categoryName);
            $category->setIsActive(true);
            $category->setIncludeInMenu(false);
            $category->setParentId($parentCategoryId);
            $category->setStoreId(Store::DEFAULT_STORE_ID);
            $category->setAttributeSetId($category->getDefaultAttributeSetId());
            $category->setPosition(1);
            $category->setCustomAttribute('url_key', $urlKey);

            $this->categoryRepository->save($category);
        }

        $this->moduleDataSetup->getConnection()->endSetup();
    }

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

    public function getAliases()
    {
        return [];
    }
}

Conclusion:

This way you can create category using data patch in Magento 2. If you face any difficulty, leave a comment and I will be quick to respond you with a solution. Stay connected with us for more such Magento 2 solutions.

Hire Magento Programmer

Happy Coding!

FAQ

  1. What is a Data Patch in Magento 2?

A data patch in Magento 2 is a type of setup script used to modify or insert data into the database when a module is installed or upgraded. Introduced in Magento 2.3, data patches are a modern replacement for the old InstallData.php and UpgradeData.php scripts.

  1. What are some use cases of data patches?
  •    Creating CMS pages or blocks
  •     Adding default product categories
  •     Setting up custom configurations
  •     Creating custom attributes
  •     Importing default data for new modules
  1. What Magento version supports data patches?

Data patches were introduced in Magento 2.3. They won’t work in earlier versions like 2.2 or 2.1.

Previous Article

How to Choose the Best Adobe Commerce Development Company?

Next Article

How to Create Automatic Discounts in Shopify Remix Using GraphQL?

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨