Configuration values lie at the heart of any Magento 2 and adobe commerce store, defining various settings that influence its behaviour. In this article, we’ll explore the methods to access configuration values in Magento 2 and provide a practical example to illustrate how this process works within the context of a real-world scenario.
Table of Contents
Understanding Configuration Values in Magento 2
Configuration values in Magento 2 are crucial for tailoring the behaviour of your store. They cover a wide range of settings, from general store information to specific module configurations. These values are stored in table name core_config_data
system.xml file for configuration
The system.xml
file is a pivotal configuration element in Magento 2. It defines the structure and settings for the admin configuration section of a module. Through a structured XML format, developers can define fields, groups, and sections, enabling the customization of module settings via the admin panel. We will use a system.xml for our example below to access it values using a helper class.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="logcleaner" translate="label" sortOrder="10">
<label>Log Cleaner</label>
</tab>
<section id="logclean" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Settings</label>
<tab>logcleaner</tab>
<resource>Friendsta_Logcleaner::logcleaner_config</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>General Configuration</label>
<field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Module Enable</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
</section>
</system>
</config>
The provided system.xml
is a straightforward file featuring a single configuration option, toggling module enablement. To retrieve this value, we’ll employ the following class.
How to access configuration value programmatically
The Magento\Framework\App\Config\ScopeConfigInterface
interface plays a central role in this process. However we will be extending an abstract class name AbstractHelper
. The Magento\Framework\App\Helper\AbstractHelper
class serves as a foundational component in Magento 2 development. As a base helper class, it provides essential functionalities that can be extended to create custom helper classes.
Begin by crafting a Helper
directory beneath your custom model. Inside this directory, forge a class named Config.
For configuration access, extend this newly crafted class by inheriting from the AbstractHelper
.
namespace Vendor\Module\Helper;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\AbstractHelper;
class Config extend AbstractHelper
{
public const XML_PATH_CONFIG = 'logclean/';
private function getConfigValue($field, $storeId = null)
{
return $this->scopeConfig->getValue(
$field, ScopeInterface::SCOPE_STORE, $storeId
);
}
public function getGeneralConfig($code, $storeId = null)
{
return $this->getConfigValue(self::XML_PATH_CONFIG .'general/'. $code, $storeId);
}
}
Moving forward, let’s define a constant named XML_PATH_CONFIG
, housing the section name. Additionally, we’ve crafted two methods, namely getConfigValue()
and getGeneralConfig()
. The latter is publicly accessible and serves as the class’s configuration entry point. It accepts two parameters, $code
and an optional $storeId
. In $code
, we’ll input the desired field name, which in our context is ‘enable’.
The getConfigValue
method operates in a private capacity, exclusively accessed via getGeneralConfig()
. This method communicates with its parent variable, namely scopeConfig
, to fulfill its functionality. This variable is Magento\Framework\App\Config\ScopeConfigInterface
is a critical interface within Magento 2’s architecture. It serves as the entry point for retrieving configuration values based on various scopes, such as store, website, or default.
The getValue()
method of scopeConfig
takes three parameters. The $field
signifies the configuration path, such as ‘logclean/general/enable’ in our case. The second parameter denotes the scope, like ‘store’ or ‘website’, to determine the configuration value. Finally, $storeId
comes into play in multi-store e-commerce setups, ensuring accurate value retrieval across different stores
Retrieve Config Value in other classes
Will use the above class and inject in one of our controller to check if admin have enabled the module from configuration or not. This controller clear all the logs in var/log directory. You can use this free module from Logs cleaner.
<?php
namespace Vendor\Module\Controller\Adminhtml\Clean;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Index extends \Magento\Backend\App\Action
{
protected $clearLogs;
protected $config;
public function __construct(
\Vendor\Module\Helper\Clearlogs $clearlogs,
\Vendor\Module\Helper\Configuration $config,
Context $context
) {
$this->clearLogs = $clearlogs;
$this->config = $config;
parent::__construct($context);
}
public function execute()
{
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
if($this->config->getGeneralConfig("enable")) {
try {
$this->clearLogs->clearLogContent();
$this->messageManager->addSuccessMessage("Logs are cleared successfully");
} catch (\Exception $exception) {
$this->messageManager->addErrorMessage("Something went wrong while clearing logs(" . $exception->getMessage() . ")");
}
}
else {
$this->messageManager->addErrorMessage("Module is disabled in Configuration");
}
$resultRedirect->setUrl($this->_redirect->getRefererUrl());
return $resultRedirect;
}
}
When admin goes to this controller he either will be able to clear the logs from var/logs or an error message will be shown to him “Module is disabled in Configuration” We can use this method to get configuration like dynamic row in configuration
One comment
Comments are closed.