Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 30 ยท Projects

Project: Product Badges

Build a Shopware 6 plugin that shows product badges: a custom field, a page subscriber, a Twig block, SCSS and color configuration, with runnable data-flow stand-ins.

In this project you build a small but complete plugin, SwagProductBadge. A merchant can type a short label into a product, such as "Sale", "Limited" or "Vegan", and the storefront shows it as a colored badge on the product page. The badge color comes from the plugin configuration and can be overridden per product.

The project touches most of what you have learned: a custom field (Entity Extensions and Custom Fields), a subscriber (Subscribers and Core Events), a Twig block (Storefront Templates with Twig), SCSS (Styling and JavaScript in the Storefront) and configuration (Plugin Configuration). The plugin code below is read-only, because Shopware cannot run on this site. The runnable stand-ins model the data flow, so you can see how the label and color travel from the database to the HTML. Namespaces and some block names can differ between Shopware versions, so check your version's templates and events before copying.

The design

flowchart LR
    A["Merchant edits product<br/>custom field swag_badge_label"] --> DB[("product.custom_fields")]
    DB --> P["ProductPageLoadedEvent"]
    CFG["Plugin config<br/>badgeColor"] --> SUB["Subscriber"]
    P --> SUB
    SUB -->|"page extension 'swagBadge'"| T["Twig block<br/>product detail"]
    T --> H["HTML badge<br/>+ CSS custom property"]
    SCSS["SCSS<br/>.swag-badge"] --> H

A subscriber reads the custom field and the config, prepares one small object and the template only renders it.

The principle: do the thinking in PHP, keep the template dumb. The subscriber decides whether a badge exists, which color it has and whether the color is valid. The template just prints what it was given.

Step 1: the plugin skeleton

The file layout (read-only):

TEXT
SwagProductBadge/
  composer.json
  src/
    SwagProductBadge.php
    Subscriber/ProductPageSubscriber.php
    Service/BadgeFactory.php
    Resources/
      config/config.xml
      config/services.xml
      views/storefront/page/product-detail/buy-widget.html.twig
      app/storefront/src/scss/base.scss

composer.json follows Packaging, Deployment and Updates. The base class creates the custom field when the plugin is installed and removes it only when the merchant asks to delete user data (read-only):

PHP
namespace Swag\ProductBadge;

use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\CustomField\CustomFieldTypes;

class SwagProductBadge extends Plugin
{
    public function install(InstallContext $installContext): void
    {
        /** @var EntityRepository $repository */
        $repository = $this->container->get('custom_field_set.repository');

        $repository->upsert([[
            'id' => Uuid::fromStringToHex('swag_product_badge_set'),
            'name' => 'swag_product_badge',
            'config' => [
                'label' => [
                    'en-GB' => 'Badge',
                    'de-DE' => 'Badge',
                ],
            ],
            'relations' => [['entityName' => 'product']],
            'customFields' => [
                [
                    'name' => 'swag_badge_label',
                    'type' => CustomFieldTypes::TEXT,
                    'config' => [
                        'label' => ['en-GB' => 'Badge text', 'de-DE' => 'Badge-Text'],
                        'componentName' => 'sw-field',
                        'customFieldType' => 'text',
                        'customFieldPosition' => 1,
                    ],
                ],
                [
                    'name' => 'swag_badge_color',
                    'type' => CustomFieldTypes::TEXT,
                    'config' => [
                        'label' => ['en-GB' => 'Badge color (hex)', 'de-DE' => 'Badge-Farbe (Hex)'],
                        'componentName' => 'sw-field',
                        'customFieldType' => 'text',
                        'customFieldPosition' => 2,
                    ],
                ],
            ],
        ]], $installContext->getContext());
    }
}

Using a stable id from Uuid::fromStringToHex() makes upsert safe to run on re-install, since it updates the same set instead of creating a second one. Custom field names should carry a plugin prefix, here swag_, so they never clash with other plugins. The merchant now finds the fields under the product's custom fields card in the Administration. For anything more structured than two text values, prefer a real entity extension instead of a custom field.

Step 2: configuration

The default color lives in the plugin's config.xml (read-only):

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>Badges</title>
        <title lang="de-DE">Badges</title>

        <input-field type="colorpicker">
            <name>badgeColor</name>
            <label>Default badge color</label>
            <label lang="de-DE">Standardfarbe</label>
            <defaultValue>#d6336c</defaultValue>
        </input-field>
    </card>
</config>

The value is read with the SystemConfigService, using the key SwagProductBadge.config.badgeColor and the sales channel id, so each shop front can have its own color with a fallback to the global value.

Step 3: a factory and a subscriber

Put the decisions into a small class that you can unit test. It receives the custom fields and the configured color and returns either null or a tiny array (read-only):

PHP
namespace Swag\ProductBadge\Service;

final class BadgeFactory
{
    private const HEX = '/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/';

    public function create(array $customFields, ?string $defaultColor): ?array
    {
        $label = trim((string) ($customFields['swag_badge_label'] ?? ''));
        if ($label === '') {
            return null;
        }

        $color = (string) ($customFields['swag_badge_color'] ?? '');
        if (!preg_match(self::HEX, $color)) {
            $color = preg_match(self::HEX, (string) $defaultColor) ? (string) $defaultColor : '#555555';
        }

        return ['label' => mb_substr($label, 0, 24), 'color' => $color];
    }
}

The subscriber listens for the product page and attaches the result as a page extension, which is Shopware's way to hand extra data to a template without touching core structs:

PHP
namespace Swag\ProductBadge\Subscriber;

use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Swag\ProductBadge\Service\BadgeFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\Struct\ArrayStruct;

class ProductPageSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly SystemConfigService $config,
        private readonly BadgeFactory $badges,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [ProductPageLoadedEvent::class => 'onProductPageLoaded'];
    }

    public function onProductPageLoaded(ProductPageLoadedEvent $event): void
    {
        $page = $event->getPage();
        $product = $page->getProduct();

        $defaultColor = $this->config->get(
            'SwagProductBadge.config.badgeColor',
            $event->getSalesChannelContext()->getSalesChannelId(),
        );

        $badge = $this->badges->create($product->getCustomFields() ?? [], is_string($defaultColor) ? $defaultColor : null);

        if ($badge !== null) {
            $page->addExtension('swagBadge', new ArrayStruct($badge));
        }
    }
}

Both classes are registered in services.xml as in Services and the Dependency Injection Container, the subscriber with the kernel.event_subscriber tag. Notice that the subscriber does no database queries of its own. The product with its custom fields is already loaded, so the cost is a few array lookups per product page. That keeps it safe under the performance rules of Security and Performance.

Step 4: the Twig block

Create a template that extends the core one and adds the badge next to the buy box (read-only):

TWIG
{% sw_extends '@Storefront/storefront/component/buy-widget/buy-widget.html.twig' %}

{% block buy_widget_price %}
    {% set badge = page.extensions.swagBadge %}
    {% if badge %}
        <span class="swag-badge"
              style="--swag-badge-color: {{ badge.class="hl-keyword">get('color') }};"
              data-swag-badge>
            {{ badge.get('label') }}
        </span>
    {% endif %}

    {% parent %}
{% endblock %}

Block names change between versions, so open the parent template of your Shopware version and pick a block that matches the position you want. Twig's automatic escaping handles label and color. There is no |raw anywhere, and the hex validation in the factory means even a hostile value cannot break out of the style attribute. Both checks matter: escaping protects HTML, validation protects the CSS context.

Step 5: SCSS

Styles go in Resources/app/storefront/src/scss/base.scss. The color is dynamic, so it cannot be a compile-time SCSS variable. Config values are read at runtime, while SCSS is compiled in theme:compile. Passing the color through a CSS custom property, as the template does, solves this:

SCSS
.swag-badge {
    display: inline-block;
    margin-bottom: 0.5rem;
    padding: 0.2rem 0.6rem;
    border-radius: 999px;
    background: var(--swag-badge-color, #d6336c);
    color: #fff;
    font-size: 0.8125rem;
    font-weight: 600;
    letter-spacing: 0.02em;
}

Check the contrast of white text on the chosen colors. A light yellow badge with white text fails accessibility guidelines, so a nice extension is computing a readable text color in the factory. Rebuild with bin/console theme:compile and clear the cache to see the result.

The data flow, as a stand-in

The first stand-in recreates the factory, the subscriber and the template in plain PHP, so you can follow one product from custom field to HTML. It uses htmlspecialchars to mirror Twig's autoescape.

PHP From custom field to badge HTML

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 "Plain Socks" product gets no badge and no markup, the "Trail Shoes" product keeps its own color, and the hostile label is shown as text instead of being interpreted.

Edge cases and hardening

The second stand-in feeds the factory the awkward inputs a real shop will eventually contain: invalid colors, a script in the color field, an empty label, whitespace and a very long label.

PHP Hardening the badge factory

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.

Testing the plugin

The factory is a pure class, so it deserves unit tests like the examples above, using the approach from Testing Plugins: one test per row of that table. The subscriber needs one integration test that loads a product page event and asserts that the extension exists. Do not skip the "no label" test, because it protects the common case where nothing should change.

Ideas to extend it

  • Show the badge on listing cards by also subscribing to the product listing event, and loading nothing extra.
  • Add translated labels with a translated custom field.
  • Use a computed text color for contrast.
  • Add an admin module page that lists all badged products (Building an Admin Module).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the badge color travel to the template as a CSS custom property?

    theme:compile builds the CSS once. Values from plugin configuration or custom fields are known at request time, so a custom property set inline carries them.
  2. 2. What is the role of the page extension 'swagBadge'?

    Extensions are named additions to the page struct. The template reads page.extensions.swagBadge.
  3. 3. Why validate the color with a hex pattern even though Twig escapes output?

    Each output context has its own rules. A strict allow-list for colors keeps unexpected CSS out of the style attribute.
  4. 4. Why is upsert with a stable id used for the custom field set in install()?

    A fixed id makes the install idempotent. Running it twice leads to one set, not two.

Summary

  • Custom fields store the label and optional color on the product, with a plugin prefix in the names.
  • A small factory validates and prepares the data, and a subscriber attaches it to the product page as an extension.
  • The Twig block only prints what the subscriber prepared, and autoescaping plus a hex allow-list keep output safe.
  • Colors that change at runtime reach the CSS through a custom property, not through SCSS variables.
  • Configuration provides the default color with sales channel fallback, and pure classes keep tests easy.

Next: Project: A Custom Wishlist API.