15

I know you can set config data in Magento 1 with:

Mage::getModel('core/config')->saveConfig('my/path/whatever', $value);

and you can get config data in Magento 2 with:

protected $_scopeConfig

public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig) {
    $this->_scopeConfig = $scopeConfig;
}

+

$this->_scopeConfig->getValue( 'path/of/config', \Magento\Store\Model\ScopeInterface::SCOPE_STORE );

But I can't figure out, how I can save config data in Magento 2

2 Answers 2

29

This is how you should save data in magento2 core_config_data

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Storage\WriterInterface

/**
 *  @var \Magento\Framework\App\Config\Storage\WriterInterface
 */
protected $configWriter;

/**
 * @param WriterInterface $configWriter
 */
public function __construct(
    ....
    WriterInterface $configWriter
    .....
) {
    $this->configWriter = $configWriter;
}

add below line in your calling method:

$this->configWriter->save('my/path/whatever',  $value, $scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0);
8

You can Inject ConfigInterface class and use it to save the value.

protected $_configInterface;

public function __construct(
    \Magento\Framework\App\Config\ConfigResource\ConfigInterface $configInterface
) {
    $this->_configInterface = $configInterface;
}

Then you can use it in your method like

$this->_configInterface
    ->saveConfig('section/group/field', $value, 'default', 0);
1
  • 1
    Do not do this except you are sure your paths don't need to be trimmed. It is recommended to use the configWriter
    – Chuvisco
    Commented Apr 9, 2018 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.