Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 42 ยท Admin, APIs and Backend Services

System Configuration (system.xml)

Add settings to Stores > Configuration with system.xml, set defaults in config.xml, read values with ScopeConfigInterface and understand scope fallback.

Almost every Magento module has settings: an on/off switch, an API key, a number of days, a text label. Hard-coding them would force a code change for every tweak, and putting them in your own database table would mean building an admin form for each one. Magento solves this once. You describe your settings in an XML file, and the admin panel shows them under Stores > Configuration, saves them to one shared table, and lets the merchant set different values per website or store view.

In this lesson you will learn the three parts of the system: the system.xml file that draws the form, the config.xml file that supplies defaults, and the ScopeConfigInterface that your code uses to read values. The real Magento files are read-only here, since Magento cannot run on this site. The runnable examples are stand-ins that show the scope fallback and a config-path reader. If you have not yet seen how XML files from modules are combined, read Areas and Configuration Files first.

How the pieces connect

A setting is addressed by a three-part path: section/group/field, for example acme_badge/general/enabled. Each part has a job:

  • etc/adminhtml/system.xml declares the form: tabs, sections, groups and fields. It is loaded only in the admin area.
  • etc/config.xml gives the default value for each path.
  • The table core_config_data stores values the merchant has saved, together with their scope.
  • Your code asks ScopeConfigInterface for a path and gets the best value for the current scope.
flowchart LR
    X["system.xml<br/>(draws the form)"] --> A["Admin: Stores > Configuration"]
    A -->|"Save"| D["core_config_data<br/>(scope, scope_id, path, value)"]
    C["config.xml<br/>(defaults)"] --> R["ScopeConfigInterface::getValue()"]
    D --> R
    R --> M["Your module code"]

system.xml defines the form, saved values go to core_config_data, and getValue() combines them with the config.xml defaults.

system.xml

The structure of the file is a tree: a section contains group elements, and a group contains field elements. This is a trimmed example for a made-up badge module (read-only):

XML
<?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="acme" translate="label" sortOrder="500">
            <label>Acme</label>
        </tab>
        <section id="acme_badge" translate="label" type="text" sortOrder="10"
                 showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Product Badge</label>
            <tab>acme</tab>
            <resource>Acme_Badge::config</resource>
            <group id="general" translate="label" type="text" sortOrder="10"
                   showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General</label>
                <field id="enabled" translate="label" type="select" sortOrder="10"
                       showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Enable badge</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="api_key" translate="label" type="obscure" sortOrder="20"
                       showInDefault="1" showInWebsite="0" showInStore="0">
                    <label>API key</label>
                    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
                </field>
            </group>
        </section>
    </system>
</config>

The attributes you will use most:

  • showInDefault, showInWebsite, showInStore control in which scopes the field appears. A field that appears at store view level can differ per store view; a field shown only at default level is global.
  • type is the form control: text, select, multiselect, textarea, obscure (a password-style input), and others.
  • source_model supplies the options of a select. Yesno is a core class that returns yes and no.
  • backend_model runs when the value is saved or loaded. Encrypted encrypts on save, as used for keys and passwords.
  • <resource> names the ACL resource that controls who may open the section; see Admin Controllers, Menus and ACL.
  • canRestore="1" shows a "Use system value" checkbox that restores the config.xml default.

After editing XML, clear the config cache (bin/magento cache:clean config) so the form is rebuilt.

config.xml defaults

Defaults live in etc/config.xml. The tree mirrors the path, under a default node (read-only):

XML
<?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>
        <acme_badge>
            <general>
                <enabled>1</enabled>
            </general>
        </acme_badge>
    </default>
</config>

So acme_badge/general/enabled is 1 until someone saves something else. A module should always provide a default, so code never has to guess what an unset value means.

Reading values in code

You inject Magento\Framework\App\Config\ScopeConfigInterface and call getValue() or isSetFlag(). Do not read core_config_data yourself. This is the typical pattern, wrapped in a small helper class (read-only):

PHP
namespace Acme\Badge\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Config
{
    private const XML_PATH_ENABLED = 'acme_badge/general/enabled';

    public function __construct(private ScopeConfigInterface $scopeConfig)
    {
    }

    public function isEnabled(?int $storeId = null): bool
    {
        return $this->scopeConfig->isSetFlag(
            self::XML_PATH_ENABLED,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }
}

isSetFlag() returns a boolean, which avoids the common trap that the string "0" is falsy in PHP while "false" is not. getValue() returns the raw string or null. Keep the path constants in one class, so a typo breaks in one place only.

The second argument is the scope type: default (the global value), websites or stores (the constants ScopeInterface::SCOPE_WEBSITE and SCOPE_STORE). The third is the scope code or id. If you pass a store scope, Magento finds the value for that store view, falling back to its website and then to the default.

Scope fallback

A value can be saved at three levels, in the core_config_data table with columns scope, scope_id, path and value:

scope scope_id Meaning
default 0 Applies to everything
websites website id Overrides the default for one website
stores store view id Overrides the website for one store view

When you ask for a store-scoped value, Magento looks at the store row first, then at the row for the website that store belongs to, then at the default row, and finally at the config.xml default. The first hit wins. Run the stand-in to see this chain with real data. The "store 3 belongs to website 2" relationship is hard-coded in the map.

PHP Scope fallback: store, website, default, config.xml

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Store 1 has no rows of its own and no website row, so it uses the default Hot. Store 2 has its own value. Store 3 belongs to website 2, so it takes the website override. The enabled path was never saved anywhere, so its answer comes from the config.xml default. A path that nobody defined returns null, and your code must be ready for that.

Encrypted values

Secrets such as API keys must not sit in core_config_data as readable text. A field with the Encrypted backend model is encrypted by Magento's encryptor when saved, using the key in app/etc/env.php. When code reads it through ScopeConfigInterface, the value is still the stored (encrypted) string. To get the plain text, you inject Magento\Framework\Encryption\EncryptorInterface and call decrypt():

PHP
$plain = $this->encryptor->decrypt(
    $this->scopeConfig->getValue('acme_badge/general/api_key', ScopeInterface::SCOPE_STORE)
);

Never log decrypted values. If the encryption key is lost, the stored secrets cannot be recovered, so the key must be part of your backups.

The stand-in below shows only the idea of a backend model that transforms a value on save and a reader that reverses it. It uses a reversible toy cipher (base64 and string reversal), which is not encryption and must never be used for real secrets.

PHP A backend model that encodes on save

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The raw column in the output is what would sit in the database, and the value column is what your code receives after the backend model's load hook. In real Magento the Encrypted model encrypts on save, while decryption happens in your code via the encryptor, as shown above.

Other ways to set values

You do not have to click through the admin. The CLI offers bin/magento config:set acme_badge/general/enabled 0 (add --scope=websites --scope-code=base for a scope) and bin/magento config:show acme_badge/general/enabled to read. For deployments, values can also be locked in the system node of app/etc/config.php or app/etc/env.php, and Magento then shows those fields as read-only in the admin. Use that for settings that must be identical on every server and live in version control. The details belong to Deployment and Upgrades.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file provides the default value for the setting acme_badge/general/enabled?

    system.xml only draws the admin form. Defaults are supplied by config.xml, in a tree that mirrors the path.
  2. 2. A value is saved for the default scope and for store view 2. Which value does store view 2 get?

    The lookup goes store view, then website, then default, then config.xml. The first value found is used.
  3. 3. Why prefer isSetFlag() over getValue() for yes/no settings?

    getValue() returns strings. isSetFlag() converts the stored value to a boolean, which avoids bugs from truthiness rules.
  4. 4. What does the Encrypted backend model do?

    The backend model hooks into saving. To read the plain value in code you decrypt it with the encryptor.

Summary

  • A setting has a path section/group/field; system.xml draws the admin form, config.xml gives the default and core_config_data stores saved values.
  • showInDefault, showInWebsite and showInStore decide at which scopes a field can be set.
  • Read settings with ScopeConfigInterface::getValue() or isSetFlag() and a scope type; never query core_config_data yourself.
  • Lookup falls back from store view to website to default to the config.xml value, and may return null.
  • Secrets use the Encrypted backend model and are decrypted with EncryptorInterface.
  • bin/magento config:set and the system node in config.php or env.php set values without the admin.

Next: Admin Controllers, Menus and ACL