Cover

Magento 2: How to get config value

In Magento 2, configuration data is stored to core_config_data database table. The easiest way to get a configuration value from there, is using the following code snippet.

$value = \Magento\Framework\App\ObjectManager::getInstance()
    ->get(\Magento\Framework\App\Config\ScopeConfigInterface::class)
    ->getValue(
        'sections/group/field',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
    );

It’s the most closest alternative to construction, which we had used in Magento 1: Mage::getStoreConfig(‘section/group/field’).

However, it’s not the best way. According to Magento 2 documentation to use objectmanager is not recommend. You can still use it in a temporary code or while you’re debugging something, but if you want to do it right, you should use dependency injection method.

A way to get a configuration value without objectmanager

To avoid an objectmanager, in Magento 2 we’re using dependency injection. Using this pattern, ScopeConfigInterface object is included via class constructor. Here is the simple example, how to get config value using dependency injection method

public $scopeConfig;

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

and then to get a config value

public function mySomethingSomething()
{
    . . .
    $valueFromConfig = $this->scopeConfig->getValue(
        'section/group/field',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
    );
    . . .
}

Getting a config value by store id

As you probably noticed, Magento is multi store platform and in some cases you might want to get a value from configuration according to store. The method, which we used in the examples above getValue, by default returns global configuration values. To change that, we need to pass our store id

public function mySomethingSomething()
{
    . . .
    $valueFromConfig = $this->scopeConfig->getValue(
        'sections/group/field',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE,,
        $storeId,
    );
    . . .
}

Troubleshooting

No changes in frontend

If you have added the objectmanager code snippet in .phtml template file and can’t see any difference in fronted, probably it because of cache. Try to clear it.

Conclusion

In case, it isn’t a temporary code – use dependency injection. It’s not a rocket science!

That’s all for this post, folks. Let me know in the comments below, if you have some questions, or had some problems using the code snippets. I will be more than happy to append this post with your case.

Happy coding!

Leave a Reply to Anonymous Cancel reply