How to define and read the values in etc/config.xml
in a custom module?
What is the best practice to use it?
1 Answer
You cannot read the values directly from etc/config.xml
.
I mean, you can, but there is no point in reading directly from there since the values may be overwritten from the stores->configuration section that makes the value from config.xml
useless.
Instead you can read from the global merged config and if the value is not overwritten in the configuration section you get the value from config.xml
.
And you can do that by adding a dependency to your class that needs to read the config value like this:
namespace Your\Namespace\Here;
class YourClassName
{
protected $scopeConfig;
public function __construct(
....
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
....
) {
....
$this->scopeConfig = $scopeConfig;
....
}
}
Then you can read the config value like this
$path = 'path/to/value';
$value = $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
Or, if it's a yes/no flag and you want to get a true/false
value you can do it like this:
$flag = $this->scopeConfig->isSetFlag($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
$path
represents all the tags concatenated by slash (/
) up to your value (similar to M1).
To define them in config.xml
you need to add this in your file
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default><--! reserved word -->
<section><!-- anything goes here -->
<group><!-- anything goes here -->
<value1>1</value1><!-- anything goes here -->
<value2>some text</value2><!-- anything goes here -->
</group>
</section>
</default>
</config>
Using the code above,
$value = $this->scopeConfig->getValue('section/group/value1', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
will return 1
and
$value = $this->scopeConfig->isSetFlag('section/group/value1', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
will return true
.