Magento 2 – How to Change Multiple Config Values Programmatically

configurationmagento2

I know how to change single config value programmatically, by this way

$configData = [
    'section' => 'MY_SECTION',
    'website' => null,
    'store'   => null,
    'groups'  => [
        'MY_GROUP' => [
            'fields' => [
                'MY_FIELD' => [
                    'value' => $myValue,
                ],
            ],
        ],
    ],
];

// $this->configFactory --> \Magento\Config\Model\Config\Factory
/** @var \Magento\Config\Model\Config $configModel */
$configModel = $this->configFactory->create(['data' => $configData]);
$configModel->save();

But now I want to know, can we set multiple config field values by this way or any other way ?

Best Answer

We can use the Magento Database Adapter to insert or update the data.

<?php

namespace Vendor\Config\Helper;

class Data
{
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $adapter;

    /**
     * Config Helper data constructor.
     * @param \Magento\Framework\App\ResourceConnection $adapter
     */
    public function __construct(
        \Magento\Framework\App\ResourceConnection $adapter
    )
    {
        $this->adapter = $adapter;
    }

    public function checkDataConfig()
    {
        $connection = $this->getConnection();
        $table = $connection->getTableName('core_config_data');

        $select = $connection->select()->from(
            $table,
            ['config_id', 'value']
        )->where(
            'path = ?',
            'checkout/options/onepage_checkout_disabled'
        );

        $data = $connection->fetchAll($select);

        if ($data) {
            try {
                $connection->beginTransaction();

                foreach ($data as $value) {
                    $bind = ['path' => 'checkout/options/onepage_checkout_enabled', 'value' => !(bool)$value['value']];
                    $where = 'config_id = ' . $value['config_id'];
                    $connection->update($table, $bind, $where);
                }

                $connection->commit();
            } catch (\Exception $e) {
                $connection->rollback();
                throw $e;
            }
        }

    }

    /**
     * Get connection
     *
     * @return \Magento\Framework\DB\Adapter\AdapterInterface
     */
    public function getConnection()
    {
        return $this->adapter->getConnection();
    }
}

I follow the same logic of checkout module -vendor/magento/module-checkout/Setup/InstallData.php.

[EDIT]

We also try with Magento\Config\Model\Config::setDataByPath() method.

Related Topic