Introduction

Imagine we are working on the client’s project.

It serves on staging and production servers, of course. But we are working locally.

And we need to change a category attribute value.

It’s easy! Just navigate to the admin panel and select the necessary value.

But this is a bad practice. Because now we should remember about this attribute and after ticket will be deployed to staging we should change attribute value here also. And then do the same thing on production (if we still remember about it).

Solution

The best approach would be to create a Data Patch. It will be deployed to staging and production and there’s no need to remember to change the attribute value, because it will be changed automatically by the Data Patch.

This is the example of Data Patch to update category attribute value.

<?php

declare(strict_types=1);

namespace Vendor\ModuleName\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Catalog\Api\CategoryRepositoryInterface;

class UpdateCategoryBottomDescription implements DataPatchInterface
{
    /** @var ModuleDataSetupInterface */
    private ModuleDataSetupInterface $moduleDataSetup;

    /**
     * @var CategoryRepositoryInterface
     */
    private CategoryRepositoryInterface $categoryRepository;

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

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $category = $this->categoryRepository->get(1803);

        if (!$category->getId()) {
            return;
        }

        $category->setBottomDescription(
            'Yo! This is the Data Patched Bottom Desctiption attribute value for the Category Id = 1803.'
        );

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

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

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

Explanation

  1. We load the category with the id=1803.
$category = $this->categoryRepository->get(1803);
  1. Set the botton_description attribute value.
$category->setBottomDescription(
    'Yo! This is the Data Patched Bottom Desctiption attribute value for the Category Id = 1803.'
);
  1. Save category using Category Repository.
$this->categoryRepository->save($category);