Hello Devs, In this tutorial we are going to see how to get store configuration value or store config value in Magento 2.
Magento stores all the configuration values in the core_config_data table based on a specific scope website, store, or view.
We can utilize the Magento\Store\Model\ScopeInterface class in our helper file as below.
Method 1 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace VendorName\ModuleName\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Store\Model\ScopeInterface; class Data extends AbstractHelper { const XML_CONFIG_PATH = 'config/to/path'; /* in the format of {sections/group/field} */ public function getConfig() { /** * for website specific value */ $configValue = $this->scopeConfig->getValue(self::XML_CONFIG_PATH,ScopeInterface::SCOPE_STORE); /** * for website specific value * * $configValue = $this->scopeConfig->getValue(self::XML_CONFIG_PATH,ScopeInterface::SCOPE_WEBSITE); */ /** * for group specific value * * $configValue = $this->scopeConfig->getValue(self::XML_CONFIG_PATH,ScopeInterface::SCOPE_GROUP); */ return $configValue; } } |
Now, you can inject the helper class anywhere and use the getConfig() function to get the config value.
Method 2 :
You can also manually specify the Store ID in the getConfig() param and get store-specific configuration values like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace VendorName\ModuleName\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Store\Model\ScopeInterface; use Magento\Framework\App\Config\ScopeConfigInterface; class Data extends AbstractHelper { const XML_AMAZON_PAYMENT_ACTIVE = 'payment/amazon_payment/active'; /** * @var ScopeConfigInterface */ protected $scopeConfig; /* * @return string */ public function getConfig($path, $storeId = null) { return $this->scopeConfig->getValue( $path, ScopeInterface::SCOPE_STORE, $storeId ); } /* * @return bool */ public function isActive() { return $this->getConfig(self::XML_AMAZON_PAYMENT_ACTIVE, 1); // Pass store id in the second parameter } } |
Method 3 :
We can also get configuration values using Object Manager like below.
1 2 3 4 5 6 7 |
<?php $value = \Magento\Framework\App\ObjectManager::getInstance() ->get(\Magento\Framework\App\Config\ScopeConfigInterface::class) ->getValue( 'sections/group/field', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, ); |
Using the above code, you can easily get store config value by scope in Magento 2.
You may also like :
How to get value from env.php in Magento 2?
How to create a root script in Magento 2?
That’s it for this tutorial, See you in the next blog. Thank you!!