How to Programmatically Set Magento 2 Core Config Data
Ever had to programmatically set Magento 2 core config data? Not only that but afterward, retrieve that new value?
I had to! And, today, I’ll share the method to set core config data programmatically in Magento 2.
I have also added how I managed the enabled cache.
The following interface can be used to achieve that
/vendor/magento/framework/App/Config/Storage/WriterInterface.php
using the following save method
public function save($path, $value, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0);
Additionally, to delete a core config data value you can use the delete method
public function delete($path, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0);
Execute the below code for the solution:
Mehod to programmatically set Magento 2 Core Config Data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace Vendor_Name\Extension_Name\Helper; use Magento\Framework\App\Config\Storage\WriterInterface; use Magento\Framework\App\Config\ScopeConfigInterface; class Data { protected $configWriter; public function __construct(WriterInterface $configWriter) { $this->configWriter = $configWriter; } /** * @param $path = 'extension_name/general/data' * @param $value = '1' */ public function SetData($path, $value) { $this->configWriter->save($path, $value, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0); } } |
Feel free to share the post and use the Comments section below to discuss any doubts on the topic with me. I’d be happy to help.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Get Order Information By Order Id in Magento 2
How to Get Magento 2 Base URL
Next