We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
Set Core Config Data Programmatically

Lately we had to set a core config data value programmatically and afterwards to retrieve that new value. Let's see together how we achieved that and how we managed the enabled cache.
Having a deeper look we figured out that 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);
An example of the usage of the save function in Magneto 2 can be found here
A really common issue is that because of the enabled cache, if you try to retrieve the new value after saving, you probably will retrieve the old one. To get the new value you have to clear the config cache and probably the full page cache if it is also enabled. So before trying to retrieve the new core config data value you have to add the following lines.
Firstly inject the following dependency into your constructor.
protected $cacheTypeList;
public function __construct( \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList ) {
$this->cacheTypeList = $cacheTypeList;
}
Then add the following two lines before you retrieve the core config data value. By doing that, you refresh the Configuration and the Page Cache cache types. Its recommended not to perform that actions so often, as it will slow down your store for a while afterwards.
$this->cacheTypeList->cleanType(\Magento\Framework\App\Cache\Type\Config::TYPE_IDENTIFIER);
$this->cacheTypeList->cleanType(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER);
Feel free to share this post and ask your questions in the comments below.
Till next time!