ARTICLE

Magento 2 system.xml and config.xml: Building Custom Admin Configuration Fields, Default Values, and Reading Them With ScopeConfigInterface

Magento 2 system.xml and config.xml: Building Custom Admin Configuration Fields, Default Values, and Reading Them With ScopeConfigInterface

In Magento 2, etc/adminhtml/system.xml defines the form fields merchants see under Stores > Configuration, and etc/config.xml supplies the default value for each field. Saved values go to the core_config_data table under a section/group/field path, and your code reads them with ScopeConfigInterface::getValue() or isSetFlag() at the scope you ask for.

Those three pieces, the form, the default, and the read, are separate on purpose, and most configuration bugs come from treating them as one thing. A field with no default returns null on a fresh install. A field read without a scope returns the global value on a multi store setup. A password field declared with the wrong type is stored in plain text. This guide builds a complete configuration section and covers each of those traps.

How the pieces fit together

File or table Role Loaded when
etc/adminhtml/system.xml Declares the admin form: tabs, sections, groups, fields Admin area only
etc/config.xml Default values, by the same path Every area
etc/acl.xml Permission resource that guards the section Admin area
core_config_data Values saved by an admin, per scope Every area
app/etc/config.php and app/etc/env.php Values locked by deployment, which override the database Every area

The link between all of them is the config path: section_id/group_id/field_id. system.xml builds it from the nesting of its elements. config.xml repeats it as nested XML nodes. core_config_data stores it in the path column.

Because system.xml is only loaded in the admin area, it cannot supply values to the storefront. A field that exists in system.xml but has no default in config.xml and has never been saved simply has no value.

Building a section in system.xml

Adobe’s system.xml reference describes the hierarchy as tab, section, group, field, with the field as the smallest unit.

<?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="400">
            <label>Acme</label>
        </tab>
        <section id="acme_shipping" translate="label" sortOrder="10"
                 showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Delivery Promise</label>
            <tab>acme</tab>
            <resource>Acme_Shipping::config</resource>
            <group id="general" translate="label" 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="0">
                    <label>Enable</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="cutoff_hour" translate="label comment" type="text" sortOrder="20"
                       showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Order Cutoff Hour</label>
                    <comment>24 hour format, store timezone.</comment>
                    <validate>required-entry validate-digits-range digits-range-0-23</validate>
                    <depends>
                        <field id="enabled">1</field>
                    </depends>
                </field>
                <field id="api_key" translate="label" type="obscure" sortOrder="30"
                       showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Carrier API Key</label>
                    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
                </field>
            </group>
        </section>
    </system>
</config>

A few things in that file deserve a closer look.

The scope flags decide where a field can be edited. showInDefault, showInWebsite, and showInStore control whether the field appears when the admin switches the scope selector. They do not restrict where a value can be read from. Set them to match the business meaning: an API key rarely varies by store view, a cutoff message often does.

resource ties the section to an ACL rule. Without a matching entry in etc/acl.xml, only full administrators see the section, and a restricted role sees nothing with no error to explain why. The resource must sit under Magento_Config::config in the ACL tree:

<resource id="Magento_Backend::admin">
    <resource id="Magento_Backend::stores">
        <resource id="Magento_Backend::stores_settings">
            <resource id="Magento_Config::config">
                <resource id="Acme_Shipping::config" title="Delivery Promise"/>
            </resource>
        </resource>
    </resource>
</resource>

To add fields to an existing section, reuse its ID. Declaring <section id="sales"> with a new group merges your group into the core Sales section. You do not need a new tab for two fields.

Field types and the three kinds of model

The reference lists the built in types: text, textarea, select, multiselect, obscure, password, image, file, time, allowspecific, button, label, and note. The behavior of a field mostly comes from the models attached to it.

Model What it does Typical use
source_model Supplies the options for select and multiselect Yes/No, a list of countries, your own option list
backend_model Runs code before save and after load Encrypt a secret, validate a value, serialize an array, clear a cache
frontend_model Renders the field in the admin form Dynamic rows table, a “Test Connection” button, a read only note

A custom source model is a class that implements Magento\Framework\Data\OptionSourceInterface and returns an array of value and label pairs from toOptionArray().

A backend model extends Magento\Framework\App\Config\Value. Override beforeSave() to validate and throw a LocalizedException with a readable message, and afterSave() to react to a change, for example to invalidate a cache type when a setting that affects rendered output changes.

obscure vs password

This is the most common security mistake in custom modules. Adobe’s reference is explicit: with type="obscure" the value is encrypted and shown as asterisks, while type="password" is not encrypted and can be revealed by changing the input type in the browser.

Even obscure needs the Magento\Config\Model\Config\Backend\Encrypted backend model to encrypt on save. And the encryption only helps if your code decrypts on read, which brings us to defaults and reading.

depends, validate, and comments

<depends> hides a field until another field has a given value. It is display logic only. The hidden field’s last saved value is still in the database and still returned by getValue(), so always check the parent flag in code as well.

<validate> takes space separated client side rules such as required-entry, validate-email, validate-url, and integer. Client side validation does not run for values set through the CLI or locked in files, so anything that must be valid needs a backend model check too.

Default values in config.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_shipping>
            <general>
                <enabled>0</enabled>
                <cutoff_hour>14</cutoff_hour>
                <api_key backend_model="Magento\Config\Model\Config\Backend\Encrypted"/>
            </general>
        </acme_shipping>
    </default>
</config>

Rules worth knowing:

  • Every field should have a default, including “off”. It makes behavior on a fresh install deterministic and makes the “Use system value” checkbox in the admin meaningful.
  • Defaults are not written to the database. core_config_data only holds values someone saved. Searching that table for your path and finding nothing is normal.
  • config.xml can hold values that have no admin field at all. This is a clean way to keep tunable constants such as batch sizes or API endpoints out of PHP while not exposing them to merchants.
  • Declare the backend model on encrypted paths. The backend_model attribute in config.xml tells the config reader to decrypt the value when it is loaded, so getValue() returns plain text. Without it you get the encrypted string and need to call EncryptorInterface::decrypt() yourself.
  • Scoped defaults exist. The same path can be nested under <websites><base> or <stores><default> to ship a different default for a specific website or store code.

Reading values with ScopeConfigInterface

Inject Magento\Framework\App\Config\ScopeConfigInterface and wrap it in one small class per module, so config paths live in one place:

<?php
declare(strict_types=1);

namespace Acme\Shipping\Model;

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

class Config
{
    private const XML_PATH_ENABLED = 'acme_shipping/general/enabled';
    private const XML_PATH_CUTOFF  = 'acme_shipping/general/cutoff_hour';

    public function __construct(private readonly ScopeConfigInterface $scopeConfig)
    {
    }

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

    public function getCutoffHour(?int $storeId = null): int
    {
        return (int) $this->scopeConfig->getValue(
            self::XML_PATH_CUTOFF,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }
}

The mistakes to avoid:

  1. Omitting the scope. getValue($path) with no second argument reads the default scope. On a store with one website that works by accident. On a multi store setup every store view gets the global value. Pass ScopeInterface::SCOPE_STORE, and Magento falls back from store view to website to default for you.
  2. Passing no store ID in background code. With a null scope code, the current store is used. In cron jobs, queue consumers, and console commands the “current store” is the admin store, so pass the store ID of the order or customer you are processing.
  3. Using getValue() for booleans. It returns strings. "0" is falsy in PHP but an unset path returns null, and loose comparisons hide the difference. isSetFlag() returns a real boolean.
  4. Trusting types. Everything comes back as a string or null. Cast it.
  5. Reading config in a constructor. It runs too early for store emulation and breaks console commands. Read it in the method that needs it.

Where a value actually comes from

When the same path is defined in several places, Magento resolves it in this order, from strongest to weakest:

  1. Environment variables and app/etc/env.php
  2. app/etc/config.php
  3. core_config_data at store view scope, then website scope, then default scope
  4. config.xml defaults

When a path is locked in env.php or config.php, the admin field is greyed out and cannot be edited. That is the mechanism behind pipeline deployment, where settings are committed and shipped with the code. Our guide to config.php vs env.php and app:config:dump covers how to decide what gets locked.

You can also set and inspect values without the admin. Adobe documents the config:set and config:show commands:

bin/magento config:set --scope=websites --scope-code=base acme_shipping/general/cutoff_hour 16
bin/magento config:show acme_shipping/general/cutoff_hour
bin/magento config:sensitive:set acme_shipping/general/api_key

config:set only accepts paths that have a field in system.xml. Mark secrets as sensitive in di.xml under Magento\Config\Model\Config\TypePool so app:config:dump never writes them into a committed file.

Why a changed value does not take effect

Configuration is cached in the config cache type. Saving in the admin cleans it for you. A direct database update, a deployment that changes config.xml, or an import script does not. Run bin/magento cache:clean config after any of those. If the setting changes what a cached page renders, the full page cache needs to go as well. Our explainer on Magento 2 cache types and cache tags covers which type holds what.

The other common cause is scope. Someone saved a value at website scope months ago, and now a change at default scope appears to do nothing because the narrower scope wins. This query shows every saved value for a path:

SELECT scope, scope_id, value FROM core_config_data WHERE path = 'acme_shipping/general/cutoff_hour';

Using configuration on a Hyva storefront

The configuration system is identical on Hyva. What differs is how templates get the values. Hyva templates should not call ScopeConfigInterface directly. Expose the value through a view model method and call that from the template. Our article on Hyva view models shows the pattern. Remember that a config driven value rendered into a cached page is fixed until that page’s cache entry is purged. Teams working with our Hyva development services build module settings this way so merchants can change storefront behavior without a deploy.

How this compares across platforms

Magento’s scoped configuration is one of its real strengths for multi brand and multi region merchants: one setting, different values per website and store view, with fallback. Each platform we build on handles merchant settings differently. Shopify uses theme settings and app metafields, BigCommerce uses channel level settings and app storage, and Shopware offers a comparable plugin configuration file with sales channel scope.

Where Bemeir fits

Bemeir is a Brooklyn agency that builds and supports Magento and Adobe Commerce stores. Clean, permissioned, well defaulted module configuration is part of every custom build in our Magento development services. Read more about Bemeir, or see our technology partners.

FAQ

What is the difference between system.xml and config.xml in Magento 2?

system.xml describes the admin form under Stores > Configuration: which fields exist, their type, their scope, and who can edit them. config.xml holds the default value for each config path. The first is only loaded in the admin area. The second is loaded everywhere and is what the storefront falls back to when nothing has been saved.

Where does Magento store configuration values?

Values saved by an admin are rows in the core_config_data table with scope, scope_id, path, and value columns. Defaults stay in each module’s config.xml and are never copied to the database. Values locked by deployment live in app/etc/config.php or app/etc/env.php and override both.

How do I get a store specific config value in Magento 2?

Call ScopeConfigInterface::getValue($path, ScopeInterface::SCOPE_STORE, $storeId). Magento checks the store view, then its website, then the default scope, then config.xml. Pass an explicit store ID in cron jobs and console commands, where the current store is the admin store.

How do I store an API key securely in Magento 2 configuration?

Use type="obscure" with the Magento\Config\Model\Config\Backend\Encrypted backend model in system.xml, declare the same backend model on the path in config.xml so reads are decrypted, and register the path as sensitive so it is excluded from app:config:dump. Do not use type="password", which is not encrypted.

Why is my custom configuration section not showing in the admin?

The usual causes are a missing or wrong <resource> and acl.xml entry, all three showIn flags set to 0 for the current scope, the file placed in etc/ when it belongs in etc/adminhtml/, or a stale config cache. Clean the config cache and log in again so the admin role’s permissions reload.

Let us help you get started on a project with Magento 2 system.xml and config.xml: Building Custom Admin Configuration Fields, Default Values, and Reading Them With ScopeConfigInterface and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.