Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 30 ยท Architecture

Plugin Configuration

Add settings to a Shopware 6 plugin with config.xml, read them with SystemConfigService per sales channel, use them in Twig and validate the values.

Almost every real plugin has settings: a text for a badge, a switch to turn a feature off, a color, an API key for an external service. Shopware lets you declare these in an XML file, then renders a settings form in the administration for you. You never write the form, the save button or the storage code. You only describe the fields and read the values.

This lesson covers config.xml, reading values with SystemConfigService, per sales channel overrides, using values in Twig and why you should validate what you read. The real XML and PHP are read-only; the runnable part is a config store that falls back from a sales channel to the global value and then to the default.

config.xml

Place the file at src/Resources/config/config.xml. It is organised in cards (visual groups) that contain fields:

XML
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/shopware/trunk/src/Core/System/SystemConfig/Schema/config.xsd">
    <card>
        <title>Badge settings</title>
        <title lang="de-DE">Badge-Einstellungen</title>

        <input-field type="bool">
            <name>enabled</name>
            <label>Show badges</label>
            <label lang="de-DE">Badges anzeigen</label>
            <defaultValue>true</defaultValue>
        </input-field>

        <input-field type="text">
            <name>badgeText</name>
            <label>Badge text</label>
            <label lang="de-DE">Badge-Text</label>
            <helpText>Shown on products that are almost sold out.</helpText>
            <defaultValue>Almost gone</defaultValue>
        </input-field>

        <input-field type="int">
            <name>lowStockLimit</name>
            <label>Low stock limit</label>
            <defaultValue>5</defaultValue>
        </input-field>

        <input-field type="single-select">
            <name>position</name>
            <label>Badge position</label>
            <options>
                <option>
                    <id>top-left</id>
                    <name>Top left</name>
                </option>
                <option>
                    <id>top-right</id>
                    <name>Top right</name>
                </option>
            </options>
            <defaultValue>top-left</defaultValue>
        </input-field>
    </card>
</config>

Things to notice:

  • A card can have a <title> per language. A field has a <name> (the key), a <label>, an optional <helpText> and a <defaultValue>.
  • type on input-field selects the control. Common types are text, textarea, int, float, bool, password, color, single-select and multi-select. Other component types exist for entity pickers and similar; check the schema file in your Shopware version for the full list.
  • The XML schema reference at the top lets your editor validate the file. A typo in a tag name makes the form fail to load, so validation is worth enabling.

After installing the plugin (or running cache:clear), the settings appear in the administration under Extensions, My extensions, next to your plugin. Merchants can edit them for All Sales Channels or override them for one specific sales channel.

flowchart TD
    Q["get('AcmeBadges.config.badgeText', channel)"] --> A{"Value stored<br/>for this channel?"}
    A -- yes --> R1["Use it"]
    A -- no --> B{"Value stored<br/>for all channels?"}
    B -- yes --> R2["Use it"]
    B -- no --> R3["null (default only if saved on install)"]

A read tries the sales channel first, then the shared value.

Keys and reading values

Every setting is stored under a key built from the plugin name, the fixed word config and the field name:

TEXT
AcmeBadges.config.badgeText

That is why the plugin name matters (it is the prefix for all your keys). Read values with Shopware\Core\System\SystemConfig\SystemConfigService:

PHP
<?php declare(strict_types=1);

namespace Acme\Badges\Service;

use Shopware\Core\System\SystemConfig\SystemConfigService;

class BadgeSettings
{
    private const PREFIX = 'AcmeBadges.config.';

    public function __construct(private readonly SystemConfigService $config)
    {
    }

    public function isEnabled(?string $salesChannelId): bool
    {
        return (bool) ($this->config->get(self::PREFIX . 'enabled', $salesChannelId) ?? true);
    }

    public function text(?string $salesChannelId): string
    {
        $value = $this->config->get(self::PREFIX . 'badgeText', $salesChannelId);

        return is_string($value) && trim($value) !== '' ? trim($value) : 'Almost gone';
    }

    public function lowStockLimit(?string $salesChannelId): int
    {
        $value = $this->config->get(self::PREFIX . 'lowStockLimit', $salesChannelId);

        return max(0, (int) $value);
    }
}

get($key, $salesChannelId) returns mixed. With a sales channel id, Shopware first looks for a value saved for that channel and falls back to the value saved for all channels. With null it reads the global value. Recent Shopware versions also offer typed helpers on the service such as getString, getInt and getBool; check your version before relying on them, and when in doubt cast yourself as above.

Register the service in services.xml with the SystemConfigService argument (its id is its class name), as in the services lesson.

Which sales channel id do you pass? In storefront code you usually have a SalesChannelContext and can use $context->getSalesChannelId(). In background jobs you often read the global value (null) or loop over sales channels. Do not read config in a tight loop over thousands of products: read it once before the loop.

Defaults

Defaults come from <defaultValue> in the XML. They are written into the configuration storage when the plugin is installed, so get() returns them like any other value afterwards. They are not a safe replacement for defensive code, though. A value can be empty (a merchant clears a field), and get() returns null for a key that was never saved. Treat the read as untrusted input and apply a fallback, as the BadgeSettings class does.

Settings can also be set and inspected from the console, which is handy in scripts and tests:

Terminal
bin/console system:config:set AcmeBadges.config.badgeText "Hot item"
bin/console system:config:get AcmeBadges.config.badgeText

Config in Twig

In storefront templates there is a Twig function for reading configuration. Using the same key:

TWIG
{% if config('AcmeBadges.config.enabled') %}
    <span class="acme-badge">{{ config('AcmeBadges.config.badgeText') }}</span>
{% endif %}

The function uses the sales channel of the current request, so per-channel overrides apply automatically. It is fine for a few values in a template. For anything with logic, compute the value in a PHP service or subscriber and hand the template a ready object, as the Storefront Templates lesson does.

Validating configuration

Merchants type free text. A config form accepts what its field type allows, and nothing more: a text field accepts any string, an integer field gives you a number but not a sensible number. So validate where you use the values:

  • Clamp numbers. A lowStockLimit of -10 or 100000 should not crash anything.
  • Allow-list selections. If position can only be top-left or top-right, map unknown strings to the default.
  • Escape on output. Twig escapes variables by default; keep it that way and do not use |raw on config text.
  • Treat secrets carefully. An API key stored with a password field is hidden in the form, but it is still stored as normal configuration; do not log it.
  • Fail soft. If a required setting is missing, disable the feature and log a warning instead of throwing an exception on every page view.

A config store with fallback

The stand-in below mimics the lookup order: a sales channel value, then the value for all channels, then a declared default. It uses a plain array as storage. Real Shopware keeps its values in a database table, and real defaults are written at install time, but the lookup order for the stored values is the same idea.

PHP Sales channel fallback

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.

Notice the B2B channel: its limit comes back as an empty string, not the default. A cleared field is a stored value, so the fallback does not apply. That is exactly why the settings class must sanitise.

The second stand-in is that sanitising layer: it reads raw, possibly dirty values and turns them into safe settings.

PHP Sanitising raw settings

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.

Real: config.xml, the key format, SystemConfigService::get, the config() Twig function and the console commands. Stand-in: the two classes above, which only imitate lookup and sanitising.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the key format for a setting named badgeText in the plugin AcmeBadges?

    Keys are built from the plugin name, the fixed segment config and the field name, so this one is AcmeBadges.config.badgeText.
  2. 2. How does SystemConfigService::get behave when you pass a sales channel id?

    A value saved for the specific channel wins; otherwise the shared value for all sales channels is used.
  3. 3. A merchant clears a text field in the settings form. Why might your code still need a fallback?

    An empty string is a stored value. Your code has to decide what an empty value means and apply its own fallback.
  4. 4. Where should defaults be declared for a setting?

    The defaultValue element in config.xml is the place for defaults; they are saved when the plugin is installed.

Summary

  • src/Resources/config/config.xml declares cards and fields; Shopware builds the settings form.
  • Keys have the form PluginName.config.fieldName, and SystemConfigService::get($key, $salesChannelId) reads them with channel fallback.
  • Defaults come from defaultValue; read values defensively because a cleared field is a stored value.
  • Use the config() Twig function for simple values and a PHP service for anything with logic.
  • Validate on use: clamp numbers, allow-list choices, escape output and fail soft.
  • The config store and settings class in the TryIts are stand-ins.

Next: Custom Entities and Definitions