Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 30 ยท Administration

Building an Admin Module

Build a Shopware 6 admin module: register routes and navigation, write list and detail pages, save through the repository and handle privileges, with a runnable state model.

An admin module is the unit of "a new area in the Administration". It owns a menu entry, a set of routes, the pages behind them and the snippets that label everything. If your plugin manages its own data, such as badges, vendors or export jobs, a module is how merchants get to that data.

This lesson builds a complete example for a made-up SwagBadge plugin: a list page, a detail page for creating and editing, saving through the JavaScript repository, notifications and privileges. It assumes you have read The Administration at a Glance and have a custom entity such as the one from Custom Entities and Definitions. The real module code is read-only, because the Administration cannot run on this site. The runnable examples are PHP stand-ins that model the page state: which fields changed, what gets sent on save and how validation errors reach the screen.

Registering the module

A module is registered with Shopware.Module.register. You give it a unique name, a type, how it looks in the menu, its routes and its navigation entries (read-only):

JavaScript
import './page/swag-badge-list';
import './page/swag-badge-detail';
import deDE from './snippet/de-DE.json';
import enGB from './snippet/en-GB.json';

Shopware.Module.register('swag-badge', {
    type: 'plugin',
    name: 'swag-badge',
    title: 'swag-badge.general.mainMenuItemGeneral',
    description: 'swag-badge.general.description',
    color: '#ff3d58',
    icon: 'regular-tag',

    snippets: {
        'de-DE': deDE,
        'en-GB': enGB,
    },

    routes: {
        list: {
            component: 'swag-badge-list',
            path: 'list',
            meta: { privilege: 'swag_badge.viewer' },
        },
        detail: {
            component: 'swag-badge-detail',
            path: 'detail/:id',
            meta: {
                parentPath: 'swag.badge.list',
                privilege: 'swag_badge.viewer',
            },
        },
        create: {
            component: 'swag-badge-detail',
            path: 'create',
            meta: {
                parentPath: 'swag.badge.list',
                privilege: 'swag_badge.creator',
            },
        },
    },

    navigation: [{
        label: 'swag-badge.general.mainMenuItemGeneral',
        color: '#ff3d58',
        path: 'swag.badge.list',
        icon: 'regular-tag',
        parent: 'sw-catalogue',
        position: 100,
        privilege: 'swag_badge.viewer',
    }],
});

The route names are built from the module name: swag-badge becomes swag.badge, so the list route is swag.badge.list. The meta.parentPath tells the admin which page the back arrow returns to. Icon names and some navigation options differ between Shopware versions, so check the component library of your target version before copying values.

The module's privilege entries do nothing on their own. The privileges must exist, which you do by registering them with the privilege service in your plugin's admin code, usually in a file like acl/index.js (read-only):

JavaScript
Shopware.Service('privileges').addPrivilegeMappingEntry({
    category: 'permissions',
    parent: null,
    key: 'swag_badge',
    roles: {
        viewer: {
            privileges: [
                'swag_badge:read',
                Shopware.Service('privileges').getPrivileges('VIEWER_COMMON'),
            ],
            dependencies: [],
        },
        editor: {
            privileges: ['swag_badge:update'],
            dependencies: ['swag_badge.viewer'],
        },
        creator: {
            privileges: ['swag_badge:create'],
            dependencies: ['swag_badge.viewer', 'swag_badge.editor'],
        },
        deleter: {
            privileges: ['swag_badge:delete'],
            dependencies: ['swag_badge.viewer'],
        },
    },
});

Each role grants admin API privileges of the form entity:operation. These are what the server enforces. The dependency list means that ticking "creator" in the role editor ticks "viewer" and "editor" too.

The list page

The list page shows rows and links to the detail page. It is a component registered with a Twig template. The script loads the repository and the criteria (read-only):

JavaScript
import template from './swag-badge-list.html.twig';

const { Criteria } = Shopware.Data;

Shopware.Component.register('swag-badge-list', {
    template,

    inject: ['repositoryFactory'],

    data() {
        return { badges: null, isLoading: true };
    },

    computed: {
        repository() {
            return this.repositoryFactory.create('swag_badge');
        },

        columns() {
            return [
                { property: 'name', label: 'swag-badge.list.columnName', routerLink: 'swag.badge.detail', primary: true },
                { property: 'color', label: 'swag-badge.list.columnColor' },
                { property: 'active', label: 'swag-badge.list.columnActive' },
            ];
        },
    },

    created() {
        this.loadBadges();
    },

    methods: {
        async loadBadges() {
            const criteria = new Criteria(1, 25);
            criteria.addSorting(Criteria.sort('name', 'ASC'));
            this.badges = await this.repository.search(criteria);
            this.isLoading = false;
        },
    },
});

The template uses the page and listing components that the core provides:

TWIG
{% block swag_badge_list %}
    <sw-page class="swag-badge-list">
        <template #search-bar></template>
        <template #smart-bar-header>
            <h2>{{ $tc('swag-badge.general.mainMenuItemGeneral') }}</h2>
        </template>
        <template #smart-bar-actions>
            <sw-button variant="primary" :router-link="{ name: 'swag.badge.create' }"
                       :disabled="!acl.can('swag_badge.creator')">
                {{ $tc('swag-badge.list.addButton') }}
            </sw-button>
        </template>
        <template #content>
            <sw-entity-listing v-if="badges"
                               :items="badges"
                               :columns="columns"
                               :repository="repository"
                               :is-loading="isLoading"
                               detail-route="swag.badge.detail"
                               :allow-edit="acl.can('swag_badge.editor')"
                               :allow-delete="acl.can('swag_badge.deleter')"/>
        </template>
    </sw-page>
{% endblock %}

sw-entity-listing already knows how to paginate, sort, inline-edit and delete through the repository you pass in. You rarely need a hand-written table. The acl.can() calls disable the buttons the user may not use, and the server still checks every request.

The detail page

The detail page does three jobs: it loads an existing entity or creates a new one, shows form fields bound to it, and saves. The key idea is that the repository gives you an entity proxy that tracks which fields you changed. On save, only the changes are sent (read-only):

JavaScript
Shopware.Component.register('swag-badge-detail', {
    template,

    inject: ['repositoryFactory'],
    mixins: [Shopware.Mixin.getByName('notification')],

    props: {
        badgeId: { type: String, required: false, default: null },
    },

    data() {
        return { badge: null, isLoading: false, isSaving: false };
    },

    computed: {
        repository() {
            return this.repositoryFactory.create('swag_badge');
        },
    },

    created() {
        this.getBadge();
    },

    methods: {
        async getBadge() {
            this.isLoading = true;
            this.badge = this.badgeId
                ? await this.repository.get(this.badgeId)
                : this.repository.create();
            this.isLoading = false;
        },

        async onSave() {
            this.isSaving = true;
            try {
                await this.repository.save(this.badge);
                this.createNotificationSuccess({
                    message: this.$tc('swag-badge.detail.saved'),
                });
                if (!this.badgeId) {
                    this.$router.push({ name: 'swag.badge.detail', params: { id: this.badge.id } });
                } else {
                    await this.getBadge();
                }
            } catch (error) {
                this.createNotificationError({
                    message: this.$tc('swag-badge.detail.saveError'),
                });
            } finally {
                this.isSaving = false;
            }
        },
    },
});

Notice how the code handles the two cases. repository.create() makes a new entity with a client-generated id. After saving you navigate to the detail route, so the page reloads in edit mode. After editing an existing entity you reload it, so that fields set by the server (such as updatedAt or computed values) are fresh.

Validation comes from the server. If the DAL rejects a write, for example because a Required flag is violated, the API answers with a list of errors that carry JSON pointers like /0/name. The admin maps those pointers back to your fields, so a form field can show its own error. Many projects also add a small client-side check for obvious mistakes, such as an empty name, before calling save, which saves a round trip. The server check remains the one that counts.

Before you rely on field components, look at the admin's component library for your version. Names such as sw-text-field, sw-colorpicker and sw-switch-field have been stable for a long time, but their props and slots occasionally change between major versions.

The page state, as a stand-in

The state model of a detail page is easy to demonstrate without a browser. The PHP stand-in below has an Entity that tracks changes, a Repository that stores rows in memory and applies required-field rules, and a DetailPage that mirrors onSave(). It is a model of the behavior, not Shopware's JavaScript.

flowchart LR
    L["List page<br/>search with Criteria"] --> D["Detail page<br/>get or create"]
    D --> E["Edit fields<br/>entity tracks changes"]
    E --> S["repository.save()<br/>sends changeset"]
    S -->|"ok"| N["Success notification<br/>reload or navigate"]
    S -->|"error"| X["Error notification<br/>field errors shown"]
    N --> L

A save sends only the changed fields and ends with a notification and a reload or navigation.

PHP Entity changeset and repository 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 first save fails and sends nothing, the second sends both fields because the entity was new, and the third sends only color. This change tracking is why repository.save is cheap and why you should edit the entity you got from the repository rather than copying it into a plain object.

Wiring list and detail together

The last stand-in models a whole session: a list built with criteria-like sorting and paging, a page of results, and navigation by privilege. It shows that creating a record requires the creator privilege while listing requires only the viewer one.

PHP List paging and privilege checks

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.

Common pitfalls

  • Forgetting to import page folders in the module's index.js. The route refers to a component name that was never registered, and the page stays blank.
  • Wrong route names. The dots in swag.badge.list come from the module name, and a typo in router-link only shows up when you click.
  • Skipping the privilege mapping. Navigation hides the entry for everyone but admins, or the API answers 403.
  • Loading all rows. Always give Criteria a limit, as in the list page.
  • Hard-coded strings. Use snippets, so German and English users both understand the page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the meta privilege on a module route do?

    The admin router checks the privilege before showing the page. The Admin API still enforces its own entity privileges on every request.
  2. 2. Why does repository.save usually send only a few fields for an existing entity?

    The entity from repository.get() records your edits, so the save payload is the changeset. A plain object copy loses that tracking.
  3. 3. Where does the authoritative validation of a badge's required name happen?

    Client checks save a round trip, but anyone can call the API directly. The DAL's field flags are the check that always applies.
  4. 4. After saving a newly created entity, what does the detail page typically do?

    Navigating to swag.badge.detail with the new id reloads the entity from the server, so later edits update it instead of creating another record.

Summary

  • A module bundles a name, menu entry, routes, snippets and privileges through Shopware.Module.register.
  • The list page uses sw-page and sw-entity-listing with a repository and a Criteria that has a limit.
  • The detail page gets or creates an entity, edits it in place, saves through the repository and tells the user the result with notifications.
  • The entity tracks changes, so a save sends only what changed, and server-side validation is the authority.
  • Privileges are registered with the privilege service and checked in routes, navigation and templates.

Next: Testing Plugins.