### NPM Installation
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/03-apps.md
Installs the Shopware Administration SDK package using npm. Shows examples of importing specific functionalities or the entire SDK.
```bash
npm install @shopware-ag/meteor-admin-sdk
```
```javascript
// Import specific functionality
import { notification, data, ui } from '@shopware-ag/meteor-admin-sdk';
// Or import everything
import * as sw from '@shopware-ag/meteor-admin-sdk';
```
--------------------------------
### Shopware Administration Build Setup Commands
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/README.md
Commands for installing dependencies, running the development server, building for production, and analyzing bundle size.
```bash
npm install
npm run dev
npm run build
npm run build --report
npm run unit
npm run e2e
npm test
```
--------------------------------
### UserConfigValue Examples
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/types.md
Examples demonstrating different types of user configuration values, such as theme preferences, column visibility, and custom settings.
```php
// Theme preference
'theme' => 'dark' // string
```
```php
// Column visibility
'visibleColumns' => ['id', 'name', 'price'] // array
```
```php
// Collapse state
'collapseAdminMenu' => true // bool
```
```php
// Language preference
'language' => 'de-DE' // string
```
```php
// Custom settings
'customData' => ['key' => 'value'] // object/array
```
--------------------------------
### XML Service Configuration Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/configuration.md
Illustrates how to define a service within an XML configuration file for the Dependency Injection container. This example shows the configuration for the AdministrationController.
```xml
```
--------------------------------
### ViteEntrypointsData Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/types.md
An example of the ViteEntrypointsData structure, showing the base asset path and definitions for the 'administration' entry point.
```php
[
'base' => '/bundles/administration/',
'entryPoints' => [
'administration' => [
'main' => [
'js' => ['/bundles/administration/app.js'],
'css' => ['/bundles/administration/app.css']
],
'legacy' => false
]
]
]
```
--------------------------------
### Install ESLint
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/twigVuePlugin/README.md
Installs ESLint as a development dependency using npm.
```bash
$ npm i eslint --save-dev
```
--------------------------------
### JSON Configuration Structure Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-commands-events.md
Illustrates the structure of a user configuration entry for storing favorite sales channels.
```json
{
"key": "sales-channel-favorites",
"value": ["ch1", "ch2", "ch3"]
}
```
--------------------------------
### Typical Workflow for Asset Management
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-commands-events.md
This workflow demonstrates the typical sequence for managing extension assets, first installing them and then removing local copies.
```bash
# 1. Install assets to public folder
php bin/console assets:install
# 2. Remove local copies
php bin/console administration:delete-extension-local-public-files
```
--------------------------------
### Shopware Service Test Example
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/07-testing/01-overview.md
An example of how to test a Shopware service, specifically the `Sanitizer` helper, to ensure it correctly processes HTML input.
```javascript
import Sanitizer from 'src/core/helper/sanitizer.helper';
describe('core/helper/sanitizer.helper.js', () => {
it('should sanitize HTML correctly', () => {
const result = Sanitizer.sanitize('Hello');
expect(result).toBe('Hello');
});
});
```
--------------------------------
### SyncApiService Usage Example
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/03-api-services.md
Example demonstrating how to use the sync method of SyncApiService to perform multiple 'upsert' and 'delete' operations in a single request.
```typescript
const syncService = Shopware.Service('syncService');
await syncService.sync([
{
action: 'upsert',
entity: 'product',
payload:
[
{ id: 'product-1', name: 'Updated Product 1' },
{ name: 'New Product 2', active: true }
]
},
{
action: 'delete',
entity: 'category',
payload: [{ id: 'category-to-delete' }]
}
]);
```
--------------------------------
### Cross-Module Communication Examples
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/02-architecture/03-module-system.md
Illustrates different methods for modules to communicate with each other, including using services, the repository pattern, and event-based mechanisms.
```javascript
// Service-based communication
const customerService = Shopware.Service('customerService');
const customer = await customerService.getCustomer(customerId);
// Repository pattern for data access
const productRepository = Shopware.Service('repositoryFactory').create('product');
const products = await productRepository.search(criteria, context);
// Event-based communication
Shopware.Application.getApplicationRoot().$emit('product-updated', product);
Shopware.Application.getApplicationRoot().$on('customer-changed', this.handleCustomerChange);
```
--------------------------------
### Define Extendable Component Setup
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/04-composition-extension-system.md
Use `createExtendableSetup` to wrap a component's setup function, making it extendable at runtime. The `originalSetup` callback must return an object with `public` and `private` keys. The `public` keys form the extension API, while `private` keys are for internal state.
```typescript
return createExtendableSetup(
{ name: 'sw-my-component', props },
(props) => {
const title = ref('Hello');
const internalId = ref(null);
return {
public: { title }, // accessible as previousState.title
private: { internalId }, // accessible as previousState._private.internalId
};
},
);
```
--------------------------------
### Make Component Setup Extendable with createExtendableSetup
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/02-plugins.md
Component authors use `createExtendableSetup` to wrap their setup function, defining a public API for extensions. The setup return value is split into `public` and `private` properties.
```typescript
import { createExtendableSetup } from 'src/app/adapter/composition-extension-system';
import { ref, computed } from 'vue';
// Register the component's public API shape in the global type map
declare global {
interface ComponentPublicApiMapping {
'sw-product-list': {
columns: Ref;
totalCount: Ref;
loadData: () => Promise;
};
}
}
export default {
name: 'sw-product-list',
props: { showDrafts: Boolean },
setup(props) {
return createExtendableSetup(
{ name: 'sw-product-list', props },
(props) => {
const columns = ref([]);
const totalCount = ref(0);
const internalCursor = ref(null); // kept private
const loadData = async () => { /* ... */ };
return {
public: { columns, totalCount, loadData },
private: { internalCursor },
};
},
);
},
};
```
--------------------------------
### ApiSearchResponse Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/types.md
An example of the ApiSearchResponse, showing product and customer data retrieved via the search API.
```json
{
"data": {
"product": {
"data": [
{"id": "uuid1", "name": "Blue Shirt", "active": true},
{"id": "uuid2", "name": "Red Shirt", "active": true}
],
"total": 2
},
"customer": {
"data": [
{"id": "uuid3", "firstName": "John", "email": "john@example.com"}
],
"total": 1
}
}
}
```
--------------------------------
### Example Routes for 404 Exception Handling
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-commands-events.md
Illustrates which routes will trigger the custom 404 page and which will not, based on the exception handling logic.
```php
// Routes handled:
// GET /admin/non-existent → Custom 404 page
// GET /admin/products/invalid → Custom 404 page
// Routes NOT handled:
// GET /storefront/page-not-found → Default behavior
// GET /api/invalid → Default behavior
// GET /admin/error/500 → Other exception types
```
--------------------------------
### Implementing a Custom Snippet Finder
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/README.md
Provides an example of how to create a custom snippet finder by implementing the `SnippetFinderInterface`.
```php
class CustomSnippetFinder implements SnippetFinderInterface
{
public function findSnippets(string $locale): array
{
// Custom snippet loading logic
}
}
```
--------------------------------
### Override Component Setup with overrideComponentSetup
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/02-plugins.md
Plugin authors use `Shopware.Component.overrideComponentSetup()` to extend or override existing component setups. This allows for modifying component behavior and state with full type safety.
```javascript
import { ref, computed } from 'vue';
Shopware.Component.overrideComponentSetup()('sw-product-list', (previousState, props, context) => {
const customFilters = ref([]);
const isCustomMode = ref(false);
// Extend an existing computed property — reads from the previous state ref
const columns = computed(() => {
const baseColumns = previousState.columns.value;
if (isCustomMode.value) {
return [
...baseColumns,
{ property: 'customScore', label: 'Custom Score', sortable: true },
];
}
return baseColumns;
});
// Override an existing method, calling the previous implementation
const loadData = async () => {
// Apply custom filters before delegating to the previous implementation
customFilters.value.forEach(f => { /* apply */ });
return previousState.loadData();
};
// Access private state (not part of the public API)
const cursor = previousState._private.internalCursor;
return {
columns, // replaces the existing ref (2-way sync for plain refs)
loadData, // replaces the existing function
customFilters, // new ref added to component state
isCustomMode, // new ref added to component state
};
});
```
--------------------------------
### Common App Exception Examples
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/errors.md
Illustrates common exceptions related to app management, such as app not found, missing secrets, host validation failures, and invalid arguments. Each example shows the method call and its corresponding error code and HTTP status.
```php
AppException::appNotFoundByName($appName)
// FRAMEWORK__APP_NOT_FOUND | 404
AppException::appSecretMissing($appName)
// FRAMEWORK__APP_SECRET_MISSING | 500
AppException::hostNotAllowed($targetUrl, $appName)
// FRAMEWORK__HOST_NOT_ALLOWED | 403
AppException::invalidArgument('Error message')
// FRAMEWORK__INVALID_ARGUMENT | 400
```
--------------------------------
### Wrapper Component Example (mt-card)
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/06-ui/01-meteor-component-library.md
Demonstrates how to wrap a Meteor component (mt-card) in Shopware 6 to maintain backward compatibility and allow for extensions. This example shows the TypeScript configuration for the wrapper.
```typescript
import { MtCard } from '@shopware-ag/meteor-component-library';
import template from './mt-card.html.twig';
export default Shopware.Component.wrapComponentConfig({
template,
components: {
'mt-card-original': MtCard,
},
inheritAttrs: false,
props: {
positionIdentifier: {
type: String,
required: true,
default: null,
},
},
});
```
--------------------------------
### Shopware License Object Initialization
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/10-commercial/01-commercial-plugin.md
Dynamically defines the global `Shopware.License` object and its `get` method if it's not already defined. This ensures license checking capabilities are available.
```javascript
// License system integration (from main Commercial plugin)
if (Shopware.License === undefined) {
Object.defineProperty(Shopware, 'License', {
get() {
return Object.defineProperty({}, 'get', {
get() {
return (flag) => {
return Shopware.Store.get('context').app.config.licenseToggles[flag];
};
},
set() {
updateLicense();
},
});
},
set() {
updateLicense();
},
});
}
```
--------------------------------
### Change Detection Process Example
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/06-change-tracking-errors.md
This example demonstrates the process of detecting changes in an entity by comparing its original and draft states. It shows how to modify draft properties and then generate a changeset using the ChangesetGenerator.
```typescript
// Example of change detection logic
const product = await productRepository.get(productId, context);
// Original state (immutable)
const origin = product.getOrigin();
console.log('Original name:', origin.name);
console.log('Original price:', origin.price);
// Draft state (mutable)
const draft = product.getDraft();
product.name = 'Updated Product Name';
product.price = 29.99;
console.log('Draft name:', draft.name);
console.log('Draft price:', draft.price);
// Generate changeset
const changesetGenerator = new ChangesetGenerator();
const { changes, deletionQueue } = changesetGenerator.generate(product);
console.log('Changes to send to API:', changes);
// Output: { name: 'Updated Product Name', price: 29.99 }
// Note: Only modified fields are included
```
--------------------------------
### Plugin Structure Example (SwagPayPal)
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/02-architecture/02-folder-structure.md
Shows the directory structure for a plugin's administration resources, located within 'custom/plugins/[PluginName]/src/Resources/app/administration/src/'. This structure mirrors the core administration's organization for extensions.
```bash
custom/plugins/SwagPayPal/src/Resources/app/administration/src/
├── app/ # Plugin-specific app extensions
├── constant/ # Plugin constants
├── core/ # Core service extensions
├── init/ # Plugin initialization
├── mixin/ # Plugin mixins
├── module/ # Plugin modules and extensions
├── types/ # TypeScript type definitions
├── main.ts # Plugin entry point
└── global.types.ts # Global type augmentations
```
--------------------------------
### OrderAmountStatistic Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/types.md
Provides an example structure for order amount statistics, detailing the date, total amount, and order count for a given day. This format is used by the OrderAmountService.
```php
[
['date' => '2024-05-20', 'amount' => 1250.50, 'count' => 3],
['date' => '2024-05-21', 'amount' => 2100.00, 'count' => 5],
]
```
--------------------------------
### Pluralization Example in Translation File
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/08-i18n/01-overview.md
Shows how to define plural forms for a translation key within a JSON file. The example uses numbered suffixes and parameter substitution for dynamic counts.
```json
{
"items": {
"count": "No items | One item | {count} items"
}
}
```
--------------------------------
### Custom IPv6 Support Checker Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/configuration.md
Demonstrates how to set a custom IPv6 support checker function, in this case, checking only for the existence of the sockets extension.
```php
$customChecker = static function (): bool {
return extension_loaded('sockets');
};
$collector = new KnownIpsCollector($customChecker);
```
--------------------------------
### Accessing Shopware Services
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/05-global-object/01-global-shopware-object.md
Provides examples of how to retrieve essential services like the HTTP client and repository factory using Shopware.Service(). These services are crucial for interacting with the Shopware API and data layer.
```javascript
const httpClient = Shopware.Service('httpClient');
const repositoryFactory = Shopware.Service('repositoryFactory');
```
--------------------------------
### SystemConfigApiService: Get and Save Values
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/03-api-services.md
Manages system configuration settings. Use getValues to retrieve configurations and saveValues to update them, optionally specifying a sales channel.
```javascript
class SystemConfigApiService extends ApiService {
constructor(httpClient, loginService) {
super(httpClient, loginService, 'system-config');
this.name = 'systemConfigApiService';
}
getValues(domain = null, salesChannelId = null) {
const params = {};
if (domain) params.domain = domain;
if (salesChannelId) params.salesChannelId = salesChannelId;
return this.httpClient.get(`/_action/${this.apiEndpoint}`, { params });
}
saveValues(values, salesChannelId = null) {
const params = {};
if (salesChannelId) params.salesChannelId = salesChannelId;
return this.httpClient.post(`/_action/${this.apiEndpoint}`, values, { params });
}
}
```
--------------------------------
### Get Installed Locales
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Returns a JSON object mapping installed language locale IDs to their corresponding locale codes.
```json
{
"e3d64c98c1de460d9da128d7621eae80": "de-DE",
"e3d64c98c1de460d9da128d7621eae81": "en-GB",
"e3d64c98c1de460d9da128d7621eae82": "fr-FR"
}
```
--------------------------------
### Full Application Initialization Sequence
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/02-architecture/01-boot-process.md
This sequence outlines the steps for booting the full Shopware application after authentication. It includes initializing pre-initializers, main initializers, post-initializers, loading plugins, and setting up the view layer and application root.
```typescript
return this.initializeInitializers(initPreContainer, '-pre')
.then(() => this.initializeInitializers(initContainer))
.then(() => this.initializeInitializers(initPostContainer, '-post'))
.then(() => this.loadPlugins())
.then(() => Promise.all(Shopware.Plugin.getBootPromises()))
.then(() => this.view.initDependencies())
.then(() => this.createApplicationRoot())
```
--------------------------------
### Basic Usage of overrideComponentSetup
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/04-composition-extension-system.md
Use `Shopware.Component.overrideComponentSetup()` to register a Composition API override for a specific component. The override function receives the previous state, props, and setup context.
```javascript
Shopware.Component.overrideComponentSetup()('sw-my-component', (previousState, props, context) => {
// ... return overrides
});
```
--------------------------------
### Get Installed Locales
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-controllers.md
Retrieves a mapping of all installed language locale codes. This is useful for displaying available languages in the administration interface or for other locale-specific operations.
```php
public function getLocales(Request $request, Context $context): Response
```
```php
// Response:
{
"e3d64c98c1de460d9da128d7621eae80": "de-DE",
"e3d64c98c1de460d9da128d7621eae81": "en-GB"
}
```
--------------------------------
### Get Locales
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Returns a list of installed language locales available in the system.
```APIDOC
## GET /api/_admin/locales
### Description
Returns installed language locales.
### Method
GET
### Endpoint
/api/_admin/locales
### Response
JSON object mapping language IDs to locale codes
```json
{
"e3d64c98c1de460d9da128d7621eae80": "de-DE",
"e3d64c98c1de460d9da128d7621eae81": "en-GB",
"e3d64c98c1de460d9da128d7621eae82": "fr-FR"
}
```
### Status Codes
- 200: OK
```
--------------------------------
### ACL Example for System Config Update
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/README.md
Demonstrates how to define Access Control List (ACL) privileges for updating system configuration. This snippet specifies that 'update', 'create', and 'delete' privileges are required for system configuration.
```php
#[Route(
path: '/api/_admin/reset-excluded-search-term',
defaults: [
PlatformRequest::ATTRIBUTE_ACL => [
'system_config:update',
'system_config:create',
'system_config:delete'
]
]
)]
```
--------------------------------
### Build Administration Panel
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/AGENTS.md
Compile and build the administration panel assets.
```bash
composer build:js:admin
```
--------------------------------
### Install ESLint Twig Vue Plugin
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/twigVuePlugin/README.md
Installs the eslint-plugin-twig-vue as a development dependency using npm.
```bash
$ npm install eslint-plugin-twig-vue --save-dev
```
--------------------------------
### Create and Populate CriteriaCollection
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-commands-events.md
Demonstrates how to create a CriteriaCollection, add specific search criteria for different entities (product, customer), and iterate over the collection.
```php
use Shopware
eutrophiles\Administration\Framework\Search\CriteriaCollection;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
$collection = new CriteriaCollection();
$productCriteria = new Criteria();
$productCriteria->addFilter(new ContainsFilter('name', 'shirt'));
$productCriteria->setLimit(10);
$collection->set('product', $productCriteria);
$customerCriteria = new Criteria();
$customerCriteria->addFilter(new ContainsFilter('firstName', 'John'));
$collection->set('customer', $customerCriteria);
// Iterate
foreach ($collection as $entityName => $criteria) {
echo "$entityName: " . $criteria->getLimit();
}
```
--------------------------------
### Fetch Products with Criteria
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/03-apps.md
Demonstrates how to use the repository pattern to fetch a list of products with specific filtering, pagination, and associations. This is the standard way to access entity data.
```javascript
import { data } from '@shopware-ag/meteor-admin-sdk';
// Get products with criteria
const products = await data.get('product', {
page: 1,
limit: 25,
filter: [
{ type: 'equals', field: 'active', value: true }
],
associations: {
manufacturer: {},
categories: {}
}
});
console.log('Products:', products);
```
--------------------------------
### Get Shopware Bundle Vite Data
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-services.md
Gets Vite data specifically for a given Shopware bundle instance.
```php
public function getBundleData(ShopwareBundle $bundle): array
```
--------------------------------
### Shopware Administration Boot and Render Sequence
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/01-overview/02-headless-architecture.md
This sequence diagram illustrates the flow of the Shopware administration application's boot and render process, from the initial browser request to the final rendering of the application or login screen.
```mermaid
sequenceDiagram
autonumber
participant B as Browser
participant T as Twig Shell (/admin)
participant I as index.ts
participant SW as core/shopware (Shopware.Application)
participant M as app/main.ts
participant A as Application.start()
participant L as loginService
participant P as Plugin Loader
participant V as Vue Adapter
B->>T: GET /admin
T-->>B: HTML + apiContext/appContext + _features_
B->>I: Execute index.ts
I->>SW: dynamic import core/shopware (create DI, factories, early Feature.init)
I->>M: dynamic import app/main (register initializers, services, view adapter)
I->>A: call startApplication() -> Application.start()
A->>A: initState + registerConfig + initializeFeatureFlags
A->>L: loginService.isLoggedIn()
alt Not logged in
A->>A: bootLogin() (subset initializers)
A->>V: createApplicationRoot (login route)
else Logged in
A->>A: bootFullApplication()
A->>A: init-pre initializers
A->>A: init initializers
A->>A: init-post initializers
A->>P: loadPlugins() (inject JS/CSS + iframes baseUrl)
P-->>A: boot promises resolved (Shopware.Plugin.getBootPromises)
A->>A: token expiry check & optional refresh
A->>V: initDependencies (i18n, overrides)
V->>V: createApplicationRoot (#app)
end
V-->>B: Render dashboard / redirect to First Run Wizard
```
--------------------------------
### App Layer Boot Sequence
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/src/app/AGENTS.md
Defines the order of initialization for the App Layer. Ensure your modules initialize in the correct sequence: init-pre, init, then init-post.
```text
init-pre/ → init/ → init-post/
```
--------------------------------
### Register and Access Services
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/02-architecture/03-module-system.md
Demonstrates registering custom services and accessing existing Shopware services. Custom services can be composed of existing ones.
```javascript
// Register new services (actual pattern from codebase)
Shopware.Service().register('paypalPaymentService', (container) => {
return {
processPayment: (payment) => {
// Custom PayPal payment processing logic
return this.handlePayPalSpecificFlow(payment);
},
validatePayment: (payment) => {
// PayPal-specific validation
return this.validatePayPalPayment(payment);
}
};
});
// Access existing services (actual pattern from codebase)
const aclService = Shopware.Service('acl');
const repositoryFactory = Shopware.Service('repositoryFactory');
const loginService = Shopware.Service('loginService');
// Service composition pattern - create new services that use existing ones
Shopware.Service().register('extendedPaymentService', (container) => {
const originalPaymentService = Shopware.Service('paymentService');
return {
// Delegate to original service
processStandardPayment: originalPaymentService.processPayment,
// Add new functionality
processPayPalPayment: (payment) => {
// Custom PayPal logic
return this.handlePayPalSpecificFlow(payment);
}
};
});
```
--------------------------------
### PHP Event Subscriber Example: CustomSearchTermSubscriber
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-commands-events.md
Example of a Symfony Event Subscriber that listens to the PreResetExcludedSearchTermEvent. It allows modification of excluded terms before they are saved.
```php
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Administration\Events\PreResetExcludedSearchTermEvent;
class CustomSearchTermSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
PreResetExcludedSearchTermEvent::class => 'onReset',
];
}
public function onReset(PreResetExcludedSearchTermEvent $event): void
{
$customTerms = ['special', 'excluded', 'terms'];
$event->setExcludedTerms($customTerms);
}
}
```
--------------------------------
### Initialize Administration Interface
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-controllers.md
Renders the main administration interface with system configuration. This method is used to load the core administration panel and inject necessary data for its operation.
```php
public function index(Request $request, Context $context): Response
```
```php
$response = $administrationController->index($request, $context);
// Returns rendered HTML with injected configuration
```
--------------------------------
### SearchResultMap Example
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/types.md
An example of the SearchResultMap structure, which associates entity names with their search results, including the collection of found entities and the total count of matching records.
```php
[
'product' => [
'data' => EntityCollection,
'total' => 42
],
'customer' => [
'data' => EntityCollection,
'total' => 8
]
]
```
--------------------------------
### Registering Mock Services for Tests
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/07-testing/01-overview.md
Shows how to register a mock service using `Shopware.Service.register` for testing purposes. This allows you to control the behavior of services during tests.
```javascript
beforeAll(() => {
Shopware.Service.register('customService', () => ({
method: jest.fn(() => Promise.resolve('result'))
}));
});
```
--------------------------------
### Administration Bundle Entry Point
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/configuration.md
The Administration bundle extends the base Bundle class and defines its entry point. It loads service definitions from XML files and registers a compiler pass for migrations.
```php
class Administration extends Bundle
{
public function getTemplatePriority(): int
{
return -1; // Lower priority than other bundles
}
public function build(ContainerBuilder $container): void
{
parent::build($container);
$this->buildDefaultConfig($container);
// Load service definitions
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/DependencyInjection/'));
$loader->load('services.xml');
$loader->load('framework.xml');
// Add compiler pass for migrations
$container->addCompilerPass(new AdministrationMigrationCompilerPass());
}
public function getAdditionalBundles(AdditionalBundleParameters $parameters): array
{
return [
new PentatrionViteBundle(), // Vite build integration
];
}
}
```
--------------------------------
### Translation Key Naming Convention Examples
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/08-i18n/01-overview.md
Examples of translation keys following the hierarchical naming conventions for module-specific, global, and component-specific translations. Adhere to these patterns for consistency.
```javascript
// Module-specific translations
'sw-product.list.title'
'sw-customer.detail.generalCard'
// Global translations
'global.default.save'
'global.error-codes.INVALID_EMAIL'
// Component translations
'sw-data-grid.actions.edit'
'sw-modal.footer.cancel'
```
--------------------------------
### Override Component Setup with TypeScript
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/04-composition-extension-system.md
Use `overrideComponentSetup` to extend or replace a component's setup logic. Type inference is provided for `previousState` based on the declared public API.
```typescript
Shopware.Component.overrideComponentSetup()('sw-my-component', (previousState) => {
// previousState.title is Ref
// previousState.count is ComputedRef
// previousState.save is () => Promise
// previousState._private is the private state object
});
```
--------------------------------
### Runtime Deprecation Warning Example
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/05-global-object/02-feature-flags-deprecations.md
An example demonstrating how to implement runtime deprecation warnings using `console.warn`, controlled by a feature flag, for deprecated functionality like the $tc function.
```typescript
// Example from vue.adapter.ts
this.app.config.globalProperties.$tc = function (...args) {
if (window._features_.V6_8_0_0) {
console.warn(
'Deprecation Warning',
'The $tc function is deprecated and will be removed in future versions. Please use $t instead.',
);
}
return i18n.global.t(...fixI18NParametersOrder(args));
};
```
--------------------------------
### Visualizing Inheritance with `sw-inherit-wrapper`
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/08-inheritance-system.md
This example demonstrates the basic usage of the `sw-inherit-wrapper` component to manage inheritance for a product name field. It shows how to bind the child's value, provide parent values, and integrate a text field component that reacts to inheritance states.
```html
```
--------------------------------
### run
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-services.md
Executes the administration readiness check. This method validates the administration interface's health and build artifacts by rendering the index route, verifying HTTP status, confirming JS module injection, and ensuring all referenced bundles have build artifacts. It returns a Result object indicating the status (OK or FAILURE) and details about the check.
```APIDOC
## run
### Description
Executes the administration readiness check. This method validates the administration interface's health and build artifacts by rendering the index route, verifying HTTP status, confirming JS module injection, and ensuring all referenced bundles have build artifacts. It returns a Result object indicating the status (OK or FAILURE) and details about the check.
### Method
`run(): Result`
### Return Type
`Result`
Returns check result with:
- Status: `OK` or `FAILURE`
- Message describing health status
- Details:
- `indexResponseTime`: Response time in seconds
- `indexPageJsBundlesFound`: Number of JS module script tags found
- `indexPageJsBundles`: Array of bundle URLs
- `missingArtifactsForJsBundles`: Array of bundle names with missing artifacts
### Example
```php
$result = $check->run();
if ($result->status === Status::OK) {
echo "Administration is healthy";
echo "Response time: " . $result->detail['indexResponseTime'];
}
```
### Check Logic
1. Renders administration index route
2. Verifies HTTP status < 400
3. Confirms JS modules are injected
4. Validates all referenced bundles have build artifacts
5. Returns OK only if all checks pass
```
--------------------------------
### Run Stylelint
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/AGENTS.md
Execute Stylelint to check CSS and SCSS files for style consistency.
```bash
composer stylelint:admin
```
--------------------------------
### Registering and Using API Services
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/03-api-services.md
Demonstrates how to register custom API services using the Shopware service factory and how to retrieve and use them for application logic.
```typescript
// Service registration
Shopware.Service().register('serviceName', (container) => {
const initContainer = Shopware.Application.getContainer('init');
return new CustomApiService(
initContainer.httpClient,
container.loginService
);
});
// Service usage
const customService = Shopware.Service('serviceName');
```
--------------------------------
### Example Custom API Service Test
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/03-api-services.md
Unit test for a custom API service. This example demonstrates mocking the HTTP client and verifying that the service calls the correct endpoint with expected headers.
```typescript
// Example service test
describe('CustomApiService', () => {
let service;
let httpClient;
beforeEach(() => {
httpClient = {
get: jest.fn(),
post: jest.fn()
};
service = new CustomApiService(httpClient, {});
});
it('should call correct endpoint with proper headers', async () => {
httpClient.get.mockResolvedValue({ data: 'test' });
await service.customMethod();
expect(httpClient.get).toHaveBeenCalledWith(
'/custom-endpoint',
expect.objectContaining({
headers: expect.objectContaining({
'Content-Type': 'application/json'
})
})
);
});
});
```
--------------------------------
### Access Global Context and Services
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/05-global-object/03-context-auth.md
Demonstrates how to access application context properties like language and environment, and authentication services like the login service from anywhere in the application.
```javascript
// Access context anywhere in the application
Shopware.Context.api.languageId
Shopware.Context.app.environment
// Access authentication service
Shopware.Service('loginService').getToken()
Shopware.Service('loginService').isLoggedIn()
```
--------------------------------
### Get Snippets/Translations
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Retrieves localized translation snippets for the administration interface.
```APIDOC
## GET /api/_admin/snippets
### Description
Retrieves localized translation snippets for the administration interface.
### Method
GET
### Endpoint
/api/_admin/snippets
### Parameters
#### Query Parameters
- **locale** (string) - Optional - Default: `en-GB` - Locale code (e.g., de-DE, en-GB)
### Response
JSON object
```json
{
"de-DE": {
"sw-login": { "title": "Anmelden", "email": "E-Mail", ... },
"global": { "save": "Speichern", "cancel": "Abbrechen", ... },
"sw-product": { ... }
},
"en-GB": { ... }
}
```
### Status Codes
- 200: OK
### Authentication Behavior
- Authenticated users: Full snippet namespaces available
- Unauthenticated users: Only `sw-login` and `global` namespaces available
```
--------------------------------
### List All License Toggles
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/10-commercial/01-commercial-plugin.md
This command logs all available license toggles for the current Shopware context. Useful for debugging and understanding available features.
```javascript
console.log('All toggles:', Shopware.Store.get('context').app.config.licenseToggles);
```
--------------------------------
### ViteFileAccessorDecorator::getBundleData
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-services.md
Gets Vite data for a specific Shopware bundle.
```APIDOC
## ViteFileAccessorDecorator::getBundleData
### Description
Gets Vite data for a specific Shopware bundle.
### Method
`getBundleData(ShopwareBundle $bundle): array`
### Parameters
#### Path Parameters
- **bundle** (ShopwareBundle) - Required - Bundle instance
### Response
#### Success Response
- **array** - Vite data for the bundle.
```
--------------------------------
### Get Known IPs
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Retrieves a list of known IP addresses detected from the request.
```APIDOC
## GET /api/_admin/known-ips
### Description
Returns known IP addresses detected from the request.
### Method
GET
### Endpoint
/api/_admin/known-ips
### Response
JSON object
```json
{
"ips": [
{ "name": "global.sw-multi-tag-ip-select.knownIps.you", "value": "192.168.1.1" },
{ "name": "global.sw-multi-tag-ip-select.knownIps.youIPv6Block64", "value": "2001:db8:123:4567::/64" }
]
}
```
### Status Codes
- 200: OK
```
--------------------------------
### Administration Source Folder Structure
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/02-architecture/02-folder-structure.md
Overview of the main directories within the administration source code.
```bash
src/Administration/Resources/app/administration/src/
├── app/ # Vue application layer
├── core/ # Framework utilities and low-level services
├── meta/ # Metadata, test datasets, and configuration
└── module/ # Business domain modules
```
--------------------------------
### App Action Execution
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/README.md
Executes a specific action defined by an installed app within the Shopware ecosystem.
```APIDOC
## POST /api/_action/extension-sdk/run-action
### Description
Executes an action provided by an app through the extension SDK.
### Method
POST
### Endpoint
`/api/_action/extension-sdk/run-action`
### Request Body
- **action** (string) - Required - The name of the action to execute.
- **payload** (object) - Optional - Data to be passed to the action.
### Authentication
Requires OAuth2 bearer token (authenticated user).
```
--------------------------------
### Registering a Plugin Module
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/05-global-object/01-global-shopware-object.md
Demonstrates how to register a new administration module for a plugin using Shopware.Module.register(). Requires a unique module name and configuration object.
```javascript
// Registering modules
Shopware.Module.register('my-plugin-module', {
routes: { /* ... */ },
navigation: { /* ... */ }
});
```
--------------------------------
### Get Translation Snippets
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Retrieves localized translation snippets for the administration interface. Supports filtering by locale.
```json
{
"de-DE": {
"sw-login": { "title": "Anmelden", "email": "E-Mail", ... },
"global": { "save": "Speichern", "cancel": "Abbrechen", ... },
"sw-product": { ... }
},
"en-GB": { ... }
}
```
--------------------------------
### GET /api/_info/config-me
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Retrieves the current user's configuration values. Optionally, specific configuration keys can be requested.
```APIDOC
## GET /api/_info/config-me
### Description
Retrieves current user's configuration values. Allows fetching specific configuration keys.
### Method
GET
### Endpoint
/api/_info/config-me
### Parameters
#### Query Parameters
- **keys** (array) - Optional - Specific configuration keys to retrieve
### Response
#### Success Response (200)
- **data** (object) - User configuration object
### Response Example
```json
{
"data": {
"theme": "dark",
"language": "de-DE",
"collapseAdminMenu": true
}
}
```
```
--------------------------------
### Get Known IPs
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Retrieves a list of known IP addresses detected from the request, useful for security or network-related configurations.
```json
{
"ips": [
{ "name": "global.sw-multi-tag-ip-select.knownIps.you", "value": "192.168.1.1" },
{ "name": "global.sw-multi-tag-ip-select.knownIps.youIPv6Block64", "value": "2001:db8:123:4567::/64" }
]
}
```
--------------------------------
### Native Block System Implementation
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/02-plugins.md
Demonstrates the structure for the future Native Block System, showing how to define blocks in component templates and extend them within plugins. This system aims for enhanced flexibility and performance.
```html
Basic Information
Advanced Settings
Custom Configuration
```
--------------------------------
### Register Domain-Specific Services
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/10-commercial/01-commercial-plugin.md
Register specialized services for your commercial feature. The service gets registered automatically through the module system.
```typescript
// Register specialized services
import TextToImageGenerationService from './module/sw-media/service/image-generation.service';
// Service gets registered automatically through module system
```
--------------------------------
### Serve Plugin Administration Index
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-controllers.md
Serves the administration index.html file for a specific plugin. If the file is not found, an HTTP 404 response is thrown.
```php
public function pluginIndex(string $pluginName): Response
```
--------------------------------
### Mocking Axios Requests in Unit Tests
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/09-security/axios-migration-guide.md
Demonstrates how to use axios-mock-adapter to mock HTTP requests in unit tests with the Shopware HTTP client.
```javascript
import MockAdapter from 'axios-mock-adapter';
import createHTTPClient from 'src/core/factory/http.factory';
const httpClient = createHTTPClient();
const mock = new MockAdapter(httpClient);
// Mock still works as before
mock.onGet('/api/endpoint').reply(200, { data: 'test' });
```
--------------------------------
### Administration Controller Locales
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-controllers.md
Retrieves all installed language locales. This endpoint provides a mapping of language IDs to their corresponding locale codes.
```APIDOC
## GET /api/_admin/locales
### Description
Retrieves all installed language locales. This endpoint provides a mapping of language IDs to their corresponding locale codes.
### Method
GET
### Endpoint
/api/_admin/locales
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
Returns mapping of language IDs to locale codes.
#### Response Example
```json
{
"e3d64c98c1de460d9da128d7621eae80": "de-DE",
"e3d64c98c1de460d9da128d7621eae81": "en-GB"
}
```
### Auth Required
No
```
--------------------------------
### Accessing System Configuration
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/configuration.md
Shows how to retrieve specific system configuration values using the SystemConfigService. This is useful for checking feature flag states or other settings.
```php
$isCustomerBound = $systemConfigService->get(
'core.systemWideLoginRegistration.isCustomerBoundToSalesChannel'
);
$esEnabled = $systemConfigService->get('elasticsearch.administration.enabled');
```
--------------------------------
### Administration Controller Index
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-controllers.md
Renders the main administration interface template with system configuration. This endpoint is used to initialize the administration panel and inject necessary configuration data.
```APIDOC
## GET /%shopware_administration.path_name%
### Description
Renders the main administration interface template with system configuration. This endpoint is used to initialize the administration panel and inject necessary configuration data.
### Method
GET
### Endpoint
/%shopware_administration.path_name%
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
Returns rendered HTML response with administration interface and configuration data.
#### Response Example
None
### Auth Required
No
```
--------------------------------
### Format Date with Current Locale
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/08-i18n/01-overview.md
Example of formatting a date using Intl.DateTimeFormat with the current locale. Ensure the `currentLocale` variable is defined.
```javascript
const date = new Date();
const formatter = new Intl.DateTimeFormat(currentLocale, {
year: 'numeric',
month: 'long',
day: 'numeric'
});
const formattedDate = formatter.format(date);
```
--------------------------------
### Main Administration Index
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/endpoints.md
Renders the main administration interface, including necessary configuration and UI framework.
```APIDOC
## GET /%shopware_administration.path_name%
### Description
Renders the administration interface with all necessary configuration.
### Method
GET
### Endpoint
/%shopware_administration.path_name%
### Response
HTML document with:
- Administration UI framework
- Configuration variables (features, API version, etc.)
- Injected meta tags and CSP nonce
### Headers
```
X-Shopware-Cache-Id: administration
Cache-Control: public, max-age=0, s-maxage=0
Cache-Control: stale-while-revalidate=86400 (if FRW not running)
```
```
--------------------------------
### Get Single Entity by ID
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/04-data-layer/02-repository-pattern.md
Fetch a single entity by its unique identifier. An optional Criteria object can be provided to load associations.
```typescript
const product = await productRepository.get(productId, context, criteria);
```
--------------------------------
### Register, Extend, and Override Components in JavaScript
Source: https://github.com/shopware/administration/blob/trunk/Resources/app/administration/technical-docs/03-extensibility/01-overview.md
Demonstrates how to register new components, extend existing ones to create new variations, and override existing components to modify their behavior using the Shopware Component Factory.
```javascript
Shopware.Component.register('my-component', {
template: `
{% block card_header %}
Original header
{% endblock %}`
});
// Extend existing component (creates new component based on existing)
Shopware.Component.extend('my-extended-field', 'my-component', {
// Additional functionality
});
// Override existing component (replaces original)
Shopware.Component.override('my-component', {
// Modified behavior
});
```
--------------------------------
### Execute DeleteExtensionLocalPublicFilesCommand
Source: https://github.com/shopware/administration/blob/trunk/_autodocs/api-reference-commands-events.md
This command removes local public files for all extensions. It should be run after assets:install to ensure assets are available in the public folder.
```bash
php bin/console administration:delete-extension-local-public-files
```