Introduction

A few moments earlier I posted two articles:

where described why we should use Data Patch to update something in the admin panel.

In this article I will show the method of how to update 'Stores > Configuration' settings in the Magento 2.

Solution

<?php

declare(strict_types=1);

namespace Vendor\ModuleName\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\App\Config\Storage\WriterInterface;

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

    /**
     * @var WriterInterface
     */
    private WriterInterface $configWriter;

    /**
     * Constructor
     *
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @apram WriterInterface $configWriter
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        WriterInterface $configWriter
    )
    {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->configWriter = $configWriter;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $this->moduleDataSetup->startSetup();
        $this->configWriter->save('catalog/layered_navigation/display_category', '0');
        $this->configWriter->save('catalog/layered_navigation/display_product_count', '0');
        $this->moduleDataSetup->endSetup();
    }

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

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

Explanation

If read my previous articles you remember that we used something like EavSetup model for the product attribute and Category Repository for the category attribute.

To update Stores > Configuration setting we are using Config Writer

\Magento\Framework\App\Config\Storage\WriterInterface

It’s easy!

We just call save method of Config Writer and pass into it 2 params:

  1. Full path to the configuration setting
'catalog/layered_navigation/display_category'
  1. New value
0

That’s it!