Skip to main content
Version: 2026.10

Build a product export

Overview​

For the export of products, cross-selling and category assignments, the bundle provides dedicated base classes as of version 12.7.0. They extend the ArrayAdapterAbstract (see "Register a new adapter") and deliver the data in the structure that the ProductModule of the Shopware plugin reads during import (see "Product import").

The product adapter implements the method buildProduct(), which returns the entry of a product or variant as array – like the array of prepare() before. The ProductAdapterAbstract takes care of the structure (main products and variants), adds id and uuid, checks the keys and provides helper methods for translations, prices, visibilities, manufacturers and delivery times. The values are exported exactly as the project returns them: the bundle sets no defaults, applies no fallback and compares no values.

All classes are located in the namespace Twocream\ShopwareConnectorBundle\Transformer\Adapter.

Class / InterfaceDescription
ArrayAdapter\Product\ProductAdapterAbstractBase class for product adapters, calls buildProduct() per product and variant and checks the keys
ArrayAdapter\Product\CrossSellingTraitCollects the cross-selling of the exported products
CrossSellingProviderInterfaceMarks adapters whose cross-selling is exported by the ArrayTransformer as package cross-selling
ArrayAdapter\Product\CategoryAssignmentAdapterAbstractBase class for the export of category assignments

The following steps build a complete product export. A complete example is located at the end of the page.

Note

Answers to frequently asked questions about keys, null values, relations, variants, languages, custom fields, checksums and the migration of existing adapters can be found on the page "Product export: FAQ".


Basic rules​

  • buildProduct() returns the entry: The array corresponds to the export JSON contract. id and uuid (md5(<Pimcore ID>)) are set by the adapter, values returned by buildProduct() are replaced. A different UUID has to be built by overriding generateUuid()
  • Values unchanged: The bundle sets no values, filters no null values and does not convert units. A key that buildProduct() does not return is missing in the export
  • Missing key and null: A missing simple key keeps the current value in Shopware. null empties the value of simple and main products and inherits the value of the main product for variants (see Inheritance)
  • Relations always have to be delivered: properties, visibilities, prices and, for variants, options are always brought to the delivered state in Shopware, a missing key removes all relations of this type (see "State synchronisation")
  • Shopware requires product-number for every entry and tax, price and translations.<locale>.name for simple and main products. The import skips entries without these data with a warning
  • Allowed keys: A key that the importer does not know ends the export with an ExportException (see Allowed keys)

Pimcore language and Shopware locale​

The product export strictly distinguishes between the language in Pimcore and the locale in Shopware. The project only works with Pimcore languages, the mapping to the Shopware locale happens in the helper methods of the ProductAdapterAbstract.

Pimcore languageShopware locale
Examplede, en, de_CHde_DE, en_GB, de_CH
Defined byLanguages of the Pimcore system settings, restricted per export target by supported_languagesTarget of the configuration language_mapping
Used inParameter of the callback of prepareTranslations(), keys of $descriptions (prepareManufacturer()) and $names (prepareDeliveryTime()), $pimcoreLanguages of applyTranslationFallback()Keys of translations, manufacturer.description and delivery-time.name in the export

This results in the following rules:

  • The callback of prepareTranslations() always receives the Pimcore language (e.g., de) and uses it to read the localized fields, e.g., $product->getTitle($language)
  • The helper methods write the values under the Shopware locale from language_mapping (e.g., translations.de_DE)
  • The Pimcore languages of supported_languages of the export target are exported. Without a value, these are all languages valid in Pimcore that are not in disabled_languages. Languages in supported_languages that are not valid or enabled in Pimcore are ignored (TranslationService::getSupportedLanguageMapping()). This also applies to manufacturer descriptions and names of delivery times
  • A language without an entry in language_mapping is written unchanged under its Pimcore key (e.g., fr)
twocream_shopware_connector:
export_targets:
- key: shop_staging
supported_languages:
- de
- en
- de_CH
language_mapping:
de: de_DE
en: en_GB
de_CH: de_CH

With this configuration, prepareTranslations() calls the callback with de, en and de_CH and writes the results under de_DE, en_GB and de_CH. A further Pimcore language such as fr is not exported for this export target. Without supported_languages, it would be exported under the key fr.

caution

Without language_mapping, prepareTranslations() writes the Pimcore keys unchanged (e.g., de, en). The import only maps the short forms of its own locale mapping (default: de to de_DE, en to en_GB), other keys without a Shopware language are ignored. If a product therefore has no name in the system language, the import skips it. It is recommended to configure language_mapping with the Shopware locales. Other adapters that use mapTranslations() of the TranslationService are not affected by supported_languages and export all languages (see "Handling of translations").

In Shopware, the delivered keys are mapped to the languages via JsonImportConfiguration::getLocaleMapping(): locales with an underscore (e.g., de_CH) are taken over unchanged, short forms such as de are mapped via the mapping of the plugin and keys with a hyphen (e.g., de-DE) are ignored. The mapping can be adjusted in Shopware via the LocaleMappingEvent (see "Which locales are accepted?"). Configuration of the mapping in Pimcore: see "Configure Language Mapping".


Step 1: Create and register the adapter​

info

Product adapters must inherit from the following abstract class: Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\ProductAdapterAbstract

getTargetClassName() and buildProduct() have to be implemented. The method prepare() is already implemented: it checks isExportable(), calls buildProduct() for the product and its variants and adds id and uuid. The class defines the following defaults, which can be overridden if needed:

  • Package name: products
  • Dependent adapters: attributes, attribute-values and the own package. Adapters that do not exist are ignored
<?php

namespace App\Component\Export\Adapter\Product;

use Pimcore\Model\DataObject\Concrete;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\ProductAdapterAbstract;

class ProductAdapter extends ProductAdapterAbstract
{
public function getTargetClassName(): string
{
return 'Product';
}

protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
return [
'product-number' => $product->getArticleNumber(),
'tax' => 19,
'price' => $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
'translations' => $this->prepareTranslations(fn (string $language) => [
'name' => $product->getTitle($language),
]),
];
}
}

The adapter is registered like every other adapter with the service tag twocream.shopware_connector.adapter, afterwards twocream:shopware-connector:reload-permissions has to be executed (see "Registering the adapter"):

services:
_defaults:
autowire: true
autoconfigure: true
public: false

App\Component\Export\Adapter\Product\ProductAdapter:
public: true
tags: [ 'twocream.shopware_connector.adapter' ]
NameDescription
getTargetClassName(): stringObject class name of the products, e.g., "Product"
buildProduct(Concrete $product, ?Concrete $mainProduct): arrayReturns the entry of a product. $mainProduct is null for simple and main products and the main product for variants
Optional
beforeConvert(): voidCalled once before every export (and by the command preview-product), e.g., to preload data for buildProduct()
prepareListingConditions(string $type): arrayRestricts the exported objects, see Step 4
isExportable(Concrete $product, ?Concrete $mainProduct = null): boolDefault true. false exports no data for the object or variant, see Step 4
getVariants(Concrete $product): ?iterableDefault null. Variants of a main product, see Step 4
getAllowedProductKeys(): ?array, getAllowedTranslationKeys(): ?arrayAllowed keys, see Allowed keys

The ProductAttributeService of the Product-Attribute-Bundle is not injected by the base class. If it is needed, it has to be injected via the constructor of the own adapter (see complete example).


Step 2: Build the product entry​

buildProduct() returns the keys of the entry with their values (formats see export JSON contract). Helper methods are available for the structured values:

protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
return [
'product-number' => $product->getArticleNumber(),
'ean' => $product->getEan(),
'tax' => 19,
'price' => $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
'manufacturer' => $this->prepareManufacturer(
(string) $product->getBrand()?->getName(),
$product->getBrand()?->getWebsite(),
['de' => $product->getBrand()?->getDescription('de')]
),
'delivery-time' => $this->prepareDeliveryTime(1, 3, 'day'),
'length' => $this->getQuantityValueRangeSingleValue($product->getLength()),
'weight' => $this->getNumericValue($product->getWeight()),
'properties' => array_values($this->getRelationIdsByFieldName($product, 'properties')),
];
}

Helper methods​

The following methods are final protected and available in every product adapter:

NameDescription
prepareTranslations(callable $values): arrayCalls $values(string $pimcoreLanguage) per exported language and returns the results with the Shopware locale as key, null omits the language, see Step 3
applyTranslationFallback(array $translations, array $fields, array $pimcoreLanguages = []): arrayFills empty values of the $fields from the first language of $pimcoreLanguages with a value, otherwise from the first language with a value
prepareVisibility(string $market, bool $condition = true, int $visibility = 30): ?array{market, visibility}, null if $condition is false, see Step 5
preparePrice($net, $gross): ?array{net, gross}, null if one of the values is empty
prepareRulePrice($net, ?string $currency): ?array{net, currency}, null without net price or currency
prepareManufacturer(string $name, ?string $link = null, array $descriptions = []): array{name, link?, description?}, $descriptions with the Pimcore language as key. An empty name returns [] and removes the assignment in Shopware
prepareDeliveryTime(int $min, int $max, string $unit, array $names = []): array{min, max, unit, name?}, $names with the Pimcore language as key. Allowed units: hour, day, week, month, year. Alternatively, the UUID of an existing delivery time can be delivered directly
getNumericValue($value): ?floatEmpty string and null result in null, all other values are converted to float
getQuantityValueRangeSingleValue(?QuantityValueRange $range, bool $preferMaximum = true): float|int|nullReturns the maximum (or, with $preferMaximum = false, the minimum) of a quantity value range, if it is empty, the other value

In addition, the ArrayAdapterAbstract provides the methods getRelationIds(iterable $relations): array and getRelationIdsByFieldName(Concrete $object, string $fieldName): array (protected, not final). They return [{id, uuid}] for Pimcore objects, ObjectMetadata and arrays with id (and optionally uuid).

caution

getRelationIds() and getRelationIdsByFieldName() return an array with the Pimcore ID as key. For the relations and lists in the export, convert the result with array_values(), as it is otherwise exported as JSON object.

Allowed keys​

Every key of a product or variant entry and of translations.<locale> must be part of getAllowedProductKeys() or getAllowedTranslationKeys(). The defaults are the constants ProductAdapterAbstract::PRODUCT_KEYS and ProductAdapterAbstract::TRANSLATION_KEYS, i.e., the keys that the ProductModule reads (see export JSON contract). An unknown key – e.g., a typo such as product-numer – ends the export with an ExportException that names the key, the object ID and the adapter:

Unknown key "product-numer" in the product entry of object 4711 (App\Component\Export\Adapter\Product\ProductAdapter). Return [...parent::getAllowedProductKeys(), 'product-numer'] from getAllowedProductKeys() to allow it or null to disable the check

The contents of product-extension and custom-fields are not checked.

// Own key that a product module of the project reads
protected function getAllowedProductKeys(): ?array
{
return [...parent::getAllowedProductKeys(), 'acme-energy-label'];
}

// Disable the check of the translations
protected function getAllowedTranslationKeys(): ?array
{
return null;
}

Step 3: Translations​

prepareTranslations() calls the callback per exported Pimcore language and returns the translations with the Shopware locale as key. If the callback returns null, the language is not exported.

Key in translations.<locale>Description
nameRequired for simple and main products
description, keywords, meta-title, meta-descriptionTexts
custom-search-keywordsList of search keywords
pack-unit, pack-unit-pluralPackaging unit
custom-fieldsTranslated custom fields, see Step 7
'translations' => $this->applyTranslationFallback(
$this->prepareTranslations(fn (string $language) => [
'name' => $product->getTitle($language),
'description' => $product->getLongDescription($language),
'meta-title' => $product->getMetaTitle($language),
]),
['name'],
['de', 'en']
),

Shopware skips simple and main products with an empty name in a delivered language. For such languages, the callback can return null, or the empty values are filled from another language with applyTranslationFallback(). The fallback is optional and only applied if the project calls it – usually not for variants, as a null name inherits the name of the main product (see Inheritance).

Shopware only writes the keys of ProductModule::getProductTranslationKeyMap() (see "Hooks and helper methods").


Step 4: Variants​

Without adjustments, every object is a simple product. Main products and variants are created via the following methods:

NameDefaultDescription
getVariants(Concrete $product): ?iterablenullnull = simple product. An iterable (also empty) makes the object a main product with the key variants
isExportable(Concrete $product, ?Concrete $mainProduct = null): booltrueCalled without for the objects of the listing and with the main product for the variants
prepareListingConditions(string $type): arraySource foldersCondition of the listing, see below
  • Every published variant from getVariants() for which isExportable($variant, $product) returns true is built with buildProduct($variant, $product)
  • The main product does not have to be the parent object in Pimcore, only getVariants() defines the variants
  • Unpublished and non-exportable variants are missing in variants, Shopware deactivates them as stale variants
  • getVariants() is only called for the objects of the listing. Variants have no own variants
  • If isExportable() returns false for an object of the listing, the adapter exports no data – the object is transferred as deleted like an unpublished object (if the export target has has_delta_management), Shopware deactivates the product
  • Shopware only reads options ([{id, uuid}] of the property options) for variants

The check which object is a main product, a variant or a simple product therefore belongs into prepareListingConditions(), isExportable() and getVariants(). In buildProduct(), checking $mainProduct is sufficient.

caution

Every object of the listing is exported as an own entry. Variant objects therefore have to be excluded from the listing via prepareListingConditions(), as they are otherwise exported twice – as own entry and in variants of their main product.

protected function prepareListingConditions(string $type): array
{
[$condition, $params] = parent::prepareListingConditions($type);

return [sprintf('(%s) AND `hierarchyLevel` IN ("master", "single")', $condition), $params];
}

protected function getVariants(Concrete $product): ?iterable
{
return $product->getHierarchyLevel() === 'master' ? $product->getChildren()->getObjects() : null;
}

protected function isExportable(Concrete $product, ?Concrete $mainProduct = null): bool
{
return $product->getState() === 'active';
}

parent::prepareListingConditions() returns the condition of the source folders from the adapter configuration (source_folder_ids) and should therefore always be included.

Inheritance​

In Shopware, variants inherit every value they deliver as null from their main product. The bundle compares no values – buildProduct() decides which values a variant inherits:

Delivered for a variantShopware
null (e.g., tax, price, manufacturer, translations.<locale>.name)The variant inherits the value of the main product
[] or missing relation (properties, visibilities, prices)Own entries are removed, the variant inherits
custom-fields.<name> = nullThe variant inherits the value of the main product per key
Key missingThe current value of the variant is kept (a new variant inherits)
$isVariant = $mainProduct !== null;

$data = [
'product-number' => $product->getArticleNumber(),
'tax' => $isVariant ? null : 19,
'price' => $isVariant ? null : $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
// ...
];

if ($isVariant) {
$data['options'] = array_values($this->getRelationIdsByFieldName($product, 'options'));
}

return $data;

For simple and main products, Shopware writes a null of a simple field as empty value (except stock), a null of tax, price or name skips the product (see "Product import: Variant inheritance"). To keep a value unchanged, omit the key. If a variant should keep its own name, deliver translations in every exported language – a variant without translations keeps its current names and texts in Shopware.


Step 5: Visibilities and rule prices​

Visibilities and rule prices are delivered per market. The market is a freely selectable key, Shopware maps it to a sales channel or a rule via getSalesChannelIdByMarket() or getRuleIdByMarket() (see "Registering the product module").

KeyFormatHelper method
visibilities[{market, visibility}]prepareVisibility() returns null for an inactive market, filter the list with array_values(array_filter([...]))
prices{<market>: {net, currency}}prepareRulePrice() returns null without price, filter the map with array_filter([...])
properties[{id, uuid}]array_values($this->getRelationIdsByFieldName($product, 'properties'))
'visibilities' => array_values(array_filter([
$this->prepareVisibility('shop-de', (bool) $product->getActiveShopDe()),
$this->prepareVisibility('shop-at', (bool) $product->getActiveShopAt()),
])),
'prices' => array_filter([
'shop-de' => $this->prepareRulePrice($product->getPriceNetDe(), 'EUR'),
'shop-at' => $this->prepareRulePrice($product->getPriceNetAt(), 'EUR'),
]),

If a market is omitted, Shopware removes an existing rule price or an existing visibility of this market.

caution

The relations are always brought to the delivered state in Shopware. A product without an active market exports "visibilities": [] and loses all visibilities in Shopware. Relations therefore have to be maintained in Pimcore only.

caution

Shopware only writes rule prices in the default currency (e.g., EUR). A rule price in another currency is skipped with Price has no value in the default currency, price is skipped, prices in several currencies are not supported yet (see "Why is a rule price in another currency skipped?").


Step 6: Product extension​

Fields of the product extension (in Shopware the entity twocream_product_extension, see "Product extension") are delivered as plain array under product-extension, translated fields under product-extension.translations.<locale>:

'product-extension' => [
'business-area' => $product->getBusinessArea(),
'videos' => array_values($this->getRelationIdsByFieldName($product, 'videos')),
'translations' => $this->prepareTranslations(fn (string $language) => [
'subtitle' => $product->getSubtitle($language),
]),
],

The bundle does not check the contents and exports them unchanged. In Shopware, the keys are mapped to the fields of the product extension via getProductExtensionFieldMap() and getProductExtensionTranslationKeyMap() of the ProductModule. Keys that are not mapped are ignored, nested structures such as videos require an override of getProductExtensionData() (see "Product import: Product extension").


Step 7: Custom fields​

Custom fields of the Shopware products are delivered via their technical name in Shopware. No mapping is necessary.

KeyMeaning
custom-fields.<name>Non-translated value
translations.<locale>.custom-fields.<name>Translated value
'custom-fields' => [
'acme_is_new' => (bool) $product->getIsNew(),
'acme_dimensions' => ['a' => $product->getDimensionA(), 'b' => $product->getDimensionB()],
],
'translations' => $this->prepareTranslations(fn (string $language) => [
'name' => $product->getTitle($language),
'custom-fields' => ['acme_claim' => $product->getClaim($language)],
]),
  • A value can itself be an array or JSON object. Whether a value is translated is decided only by its position in the export, never by the shape of the value
  • If a name is delivered in both places, the translated value applies in Shopware in its language, all other languages receive the non-translated value
  • null removes the value in Shopware, a variant then inherits the value of the main product. A name that is not delivered keeps its value
  • Shopware checks the value against the type of the custom field, unknown names and invalid values are reported as warning and not written (see "Product import: Custom fields")

Step 8: Cross-selling​

The cross-selling is not exported via an own adapter, but via the product adapter. The following steps are necessary:

  1. Include the trait ArrayAdapter\Product\CrossSellingTrait in the product adapter
  2. Implement the interface CrossSellingProviderInterface
  3. Implement the method getCrossSellingFields(): array
  4. Return getCrossSellingChecksum($product) as cross-selling-checksum in buildProduct() – the call also collects the cross-selling of the entry
info

The trait alone is not sufficient: only the CrossSellingProviderInterface makes the ArrayTransformer take over the collected data as package cross-selling into the export after the conversion of the adapter. Only the cross-selling of the entries for which getCrossSellingChecksum() or prepareCrossSelling() was called is collected.

NameDescription
getCrossSellingFields(): arrayMapping of relation field to cross-selling name, e.g., ['accessories' => 'Accessories']. If the mapping is invalid or the field does not exist, an ExportException is thrown
Optional
prepareAdditionalCrossSelling(Concrete $object): voidAdds further entries to $this->crossSelling[$object->getId()] that cannot be mapped via a relation field
Provided (final protected)
prepareCrossSelling(Concrete $object): arrayCollects the cross-selling of an object (including inherited values) and returns it
getCrossSellingChecksum(Concrete $object): stringChecksum of the result of prepareCrossSelling()
class ProductAdapter extends ProductAdapterAbstract implements CrossSellingProviderInterface
{
use CrossSellingTrait;

protected function getCrossSellingFields(): array
{
return ['accessories' => 'Accessories'];
}

protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
return [
// ...
'cross-selling-checksum' => $this->getCrossSellingChecksum($product),
];
}
}

prepareCrossSelling() is idempotent per object, calling it multiple times therefore does not create duplicates. The ArrayTransformer calls resetCrossSelling() before every convert() of an adapter with CrossSellingProviderInterface, so the collected cross-selling starts empty in every export.

Delta export​

A pure change of the cross-selling does not change the product data itself. As the checksum cross-selling-checksum is part of the product data, the product is nevertheless considered changed when the cross-selling changes and is transferred in the delta export. The importer ignores this field.

ExportContent of the package cross-selling
Delta exportOnly the cross-selling of the products exported in this run including their variants
Full export (--skip-delta)The cross-selling of all products

Variants are taken into account via variants[*].id of the product entry. For products that are exported as deleted (.meta.deleted), no cross-selling is transferred, neither in the delta nor in the full export.


Step 9: Category assignments​

info

Adapters for category assignments must inherit from the following abstract class: Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\CategoryAssignmentAdapterAbstract

The package name is category-assignments by default. With several category trees, getPackageName() can be overridden. The method prepare() is already implemented and creates one entry {id, identifier, products: [{id, uuid}]} per category object via getRelationIds(). Products assigned multiple times are only transferred once.

NameDescription
getTargetClassName(): stringCorresponding object class name of the category, e.g., "Category"
getCategoryIdentifier(Concrete $object): ?stringIdentifier of the Shopware category to which the products are assigned. If the identifier is empty, prepare() returns no data and the object is transferred as deleted – like an unpublished object
getAssignedProducts(Concrete $object): iterableReturns the product objects (or ObjectMetadata) to be assigned. Rules for hierarchy and variants remain in the project
Optional
prepareListingConditions(string $type): arrayCan be overridden to restrict the exported category objects, e.g., via the path
<?php

namespace App\Component\Export\Adapter\Product;

use Pimcore\Model\DataObject\Concrete;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\CategoryAssignmentAdapterAbstract;

class CategoryAssignmentAdapter extends CategoryAssignmentAdapterAbstract
{
public function getTargetClassName(): string
{
return 'Category';
}

protected function getCategoryIdentifier(Concrete $object): ?string
{
return $object->getIdentifier();
}

protected function getAssignedProducts(Concrete $object): iterable
{
return $object->getProducts();
}
}

Step 10: Preview the product​

The command twocream:shopware-connector:preview-product prints the entry that the product adapters of the class export for an object – without storing checksums or writing an export file.

php bin/console twocream:shopware-connector:preview-product 4711 --system=shop_staging
  • --system is required, as buildProduct() may use the export target (e.g., assetHelper())
  • Errors, e.g., an unknown key, are printed without stack trace and end the command with an error code
  • An unpublished object is built anyway with a warning, the export skips it

Arguments and options are described on the page "Commands".


Complete example​

The following example shows a product adapter with main products and variants, two markets, properties from the Product-Attribute-Bundle, preloaded positions, product extension, custom fields and cross-selling. The field names of the Pimcore class are examples.

<?php

namespace App\Component\Export\Adapter\Product;

use Pimcore\Db;
use Pimcore\Model\DataObject\Concrete;
use Pimcore\Model\DataObject\ProductAttributeValue;
use Twocream\ProductAttributeBundle\Components\Export\Service\ProductAttributeService;
use Twocream\ShopwareConnectorBundle\Service\AdapterConfigurationService;
use Twocream\ShopwareConnectorBundle\Service\ExportTargetService;
use Twocream\ShopwareConnectorBundle\Service\TranslationService;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\ConditionManager;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\CrossSellingTrait;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\ProductAdapterAbstract;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\CrossSellingProviderInterface;

class ProductAdapter extends ProductAdapterAbstract implements CrossSellingProviderInterface
{
use CrossSellingTrait;

private array $positions = [];

private ProductAttributeService $productAttributeService;

public function __construct(
TranslationService $translationService,
ExportTargetService $exportTargetService,
AdapterConfigurationService $adapterConfigurationService,
ConditionManager $manager,
ProductAttributeService $productAttributeService
) {
$this->productAttributeService = $productAttributeService;

parent::__construct($translationService, $exportTargetService, $adapterConfigurationService, $manager);
}

public function getTargetClassName(): string
{
return 'Product';
}

protected function beforeConvert(): void
{
$this->positions = Db::get()->fetchAllKeyValue('SELECT `productId`, `position` FROM `app_product_position`');
}

protected function prepareListingConditions(string $type): array
{
[$condition, $params] = parent::prepareListingConditions($type);

return [sprintf('(%s) AND `hierarchyLevel` IN ("master", "single")', $condition), $params];
}

protected function isExportable(Concrete $product, ?Concrete $mainProduct = null): bool
{
return $product->getState() === 'active';
}

protected function getVariants(Concrete $product): ?iterable
{
return $product->getHierarchyLevel() === 'master' ? $product->getChildren()->getObjects() : null;
}

protected function getCrossSellingFields(): array
{
return ['accessories' => 'accessories'];
}

protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
$isVariant = $mainProduct !== null;

$translations = $this->prepareTranslations(fn (string $language) => [
'name' => $isVariant ? $product->getVariantTitle($language) : $product->getTitle($language),
'description' => $isVariant ? null : $product->getLongText($language),
'custom-fields' => ['acme_claim' => $isVariant ? null : $product->getClaim($language)],
]);

$data = [
'product-number' => $isVariant ? $product->getArticleNumber() : 'M-' . $product->getId(),
'ean' => $product->getEan(),
'tax' => $isVariant ? null : 19,
'price' => $isVariant ? null : $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
'manufacturer' => $isVariant ? null : $this->prepareManufacturer((string) $product->getManufacturerName()),
'weight' => $this->getNumericValue($product->getWeight()),
'properties' => $this->productAttributeService->getArticleAssignmentByProductId(
new ProductAttributeValue\Listing(),
$product->getId()
),
'prices' => $isVariant ? [] : array_filter([
'shop-de' => $this->prepareRulePrice($product->getPriceNetDe(), 'EUR'),
'shop-at' => $this->prepareRulePrice($product->getPriceNetAt(), 'EUR'),
]),
'visibilities' => $isVariant ? [] : array_values(array_filter([
$this->prepareVisibility('shop-de', (bool) $product->getActiveShopDe()),
$this->prepareVisibility('shop-at', (bool) $product->getActiveShopAt()),
])),
'custom-fields' => ['acme_is_new' => $isVariant ? null : (bool) $product->getIsNew()],
'translations' => $isVariant ? $translations : $this->applyTranslationFallback($translations, ['name'], ['de']),
'product-extension' => [
'position' => $this->positions[$isVariant ? $mainProduct->getId() : $product->getId()] ?? 999999,
'videos' => array_values($this->getRelationIdsByFieldName($product, 'videos')),
],
'cross-selling-checksum' => $this->getCrossSellingChecksum($product),
];

if ($isVariant) {
$data['options'] = array_values($this->getRelationIdsByFieldName($product, 'variantOptions'));
}

return $data;
}
}

A main product with one variant results, e.g., in the following entry (with language_mapping de: de_DE, en: en_GB):

{
"id": 4711,
"uuid": "...",
"product-number": "M-4711",
"ean": null,
"tax": 19,
"price": { "net": 100.0, "gross": 119.0 },
"manufacturer": { "name": "ACME" },
"weight": null,
"properties": [{ "id": 301, "uuid": "..." }],
"prices": { "shop-de": { "net": 89.0, "currency": "EUR" } },
"visibilities": [{ "market": "shop-de", "visibility": 30 }],
"custom-fields": { "acme_is_new": true },
"translations": {
"de_DE": { "name": "Bohrmaschine", "description": "…", "custom-fields": { "acme_claim": "Neu" } },
"en_GB": { "name": "Drill", "description": "…", "custom-fields": { "acme_claim": "New" } }
},
"product-extension": { "position": 4, "videos": [] },
"cross-selling-checksum": "...",
"variants": [
{
"id": 4712,
"uuid": "...",
"product-number": "4711-1",
"ean": "4006381333931",
"tax": null,
"price": null,
"manufacturer": null,
"weight": 2.7,
"properties": [{ "id": 302, "uuid": "..." }],
"prices": [],
"visibilities": [],
"custom-fields": { "acme_is_new": null },
"translations": {
"de_DE": { "name": "Bohrmaschine 18 V", "description": null, "custom-fields": { "acme_claim": null } },
"en_GB": { "name": "Drill 18 V", "description": null, "custom-fields": { "acme_claim": null } }
},
"product-extension": { "position": 4, "videos": [] },
"cross-selling-checksum": "...",
"options": [{ "id": 905, "uuid": "..." }]
}
]
}

In Shopware, the variant inherits tax rate, price, manufacturer, description, visibilities, rule prices and the custom fields of the main product. For simple and main products, "ean": null or "weight": null empties the value in Shopware.

The corresponding product module in Shopware maps the markets and the fields of the product extension (see "Product import"), the custom fields are written without mapping via their technical name.


Virtual adapters (groups)​

Virtual adapters bundle several adapters into one selectable entry in the export mask. They are not product-specific, see "Virtual adapters (groups)".


Deletion data​

If an object is deleted in Pimcore, the deletion data are determined via the adapters registered for the class of the object:

  1. Virtual adapters and adapters that do not override getDeletedData() (i.e., inherit AdapterAbstract::getDeletedData()) are skipped
  2. The first result of getDeletedData($object) of an overriding adapter that is not null applies. The registration order is only relevant among the adapters that override getDeletedData()
  3. If no adapter returns data, AdapterAbstract::getDeletedData($object) is used

This way, project-specific implementations of getDeletedData() are taken into account, e.g., if the Shopware UUID is not built from the Pimcore ID.

use Pimcore\Model\DataObject;

public static function getDeletedData(DataObject $object): ?string
{
return json_encode(['uuid' => $object->getAttributeUuid()]);
}

If the deletion data contain a uuid, it is used instead of the generated UUID for the deletion entry.


Export JSON contract​

The product export must correspond to the structure that the JSON importer of the Shopware plugin expects:

{
".meta": { "id": "...", "mail": "...", "delta": true },
"<package>": { "<pimcoreId>": { } },
"cross-selling": {
"<pimcoreId>": { "id": 1, "uuid": "...", "items": { "<name>": [ { "id": 2, "uuid": "..." } ] } }
}
}
  • The UUID corresponds to md5(<pimcoreId>), use generateUuid() of the adapter for this
  • Deleted entries: { "id", "uuid", ".meta": { "deleted": true } }

products​

The keys of the table are the allowed keys (ProductAdapterAbstract::PRODUCT_KEYS and ProductAdapterAbstract::TRANSLATION_KEYS, see Allowed keys).

KeyFormat
id, uuidSet by the adapter
product-numberString, required
taxNumber, required for simple and main products
price{net, gross}, required for simple and main products
purchase-price{net, gross} in the default currency
translations{<locale>: {name, description, keywords, custom-search-keywords, meta-title, meta-description, pack-unit, pack-unit-plural, custom-fields}}, name required for simple and main products, custom-search-keywords as list
ean, manufacturer-number, unitString
active, is-closeout, shipping-free, mark-as-topsellerBoolean (without active, main products are active, variants inherit)
stock, min-purchase, max-purchase, purchase-steps, restock-timeInteger
purchase-unit, reference-unit, length, width, height, weightNumber
release-dateDate as string
manufacturerName, [] or '' (removes the assignment) or {name, link?, description?} with description per locale
delivery-timeUUID, null or '' (removes the assignment) or {min, max, unit, name?} with name per locale
canonical-product{id, uuid} of another product, null or [] (removes the assignment)
cms-page, feature-setUUID of an existing Shopware layout or feature set, null or '' (removes the assignment)
variant-listing-config (main products only){display-parent?, main-variant?{id, uuid}, configurator-group-config?[{uuid, representation, expression-for-listings}]}
properties, options (variants only)[{id, uuid}]
visibilities[{market, visibility}]
prices{<market>: {net, currency}}
custom-fields{<technical name>: value}, not checked
product-extension{<key>: value, translations?} with translations per locale, not checked
variantsList of the variant entries (also empty), marks a main product
cross-selling-checksumString, ignored by the importer
  • Variants have the same structure. For variants, only id, uuid and product-number are required, null inherits the value of the main product (also tax, price and names)
  • As <locale>, prepareTranslations() writes the target from language_mapping (see Pimcore language and Shopware locale). Keys with a hyphen (e.g., de-DE) are ignored in Shopware (see "Which locales are accepted?")
Note

The source system is leading: the relations properties, visibilities, prices, options and variants of an entry are always brought to the state of the export in Shopware. A missing key removes the existing relations, existing variants that are no longer part of the export are deactivated. Every entry therefore has to deliver its complete relations. Missing simple fields, however, are not written (see "State synchronisation").

cross-selling​

{ pimcoreId: { id, uuid, items: { name: [ {id, uuid} ] } } }

category-assignments​

{ id, identifier, products: [ {id, uuid} ] }