Magento 2 – get core config data programmatically
In this tutorial I show you how to get core config data programmatically. This article is based on my previous one. There I showed you how to add system configuration fields to Magento 2 backend. You can create your own configuration fields within you module, but you can also get config data programmatically from all other modules or Magento core.
Magento 2 – get core config data programmatically
In your core_config_data table you find all settings you make or made in you Magento 2 backend. If you add new input fields in your modules system.xml, new lines are generated if you safe this form. So if you want to use this information within you code, you will get it with ScopeConfigInterface. To use this functionality, we need to inject this class:
1 2 3 4 5 6 7 8 | class Example { protected $_scopeConfig; public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig) { $this->_scopeConfig = $scopeConfig; } ... |
Now you can load all configuration data with $_scopeConfig object. All you need is the correct path and the relevant scope. A backend use may save different values for each store view or use data from website or global scope. A simple example of how to get this data looks like this:
1 2 | $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORES; echo $this->scopeConfig->getValue("example_section/general/field_data", $storeScope); |
The path looks like this: example_section is the id of your section, general the id of your group and field_data the id of your field defined in system.xml.
Possible scopes are:
1 2 3 4 5 | const SCOPE_STORES = 'stores'; const SCOPE_WEBSITES = 'websites'; const SCOPE_STORE = 'store'; const SCOPE_GROUP = 'group'; const SCOPE_WEBSITE = 'website'; |
Problems
You may discover problems if you want to use the sample shown above. A typical error my look like this:
1 | PHP Fatal error: Uncaught TypeError: Argument 1 passed to Example\Importer\Model\Importer::__construct() must implement interface Magento\Framework\App\Config\ScopeConfigInterface, none given, called in... |
This error happens if you add new injections but forget to recompile your module. The simple solution to this is to compile it with the following command:
1 | php bin/magento setup:di:compile |
Conclusion
It is very easy to get core config data programmatically. The above example shows you how to to add appropriate injections for your own model.
protected $_scopeConfig
semicolon is missing in the end of this line