Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 30 ยท Data Abstraction Layer

Entity Extensions and Custom Fields

Add data to Shopware core entities safely: EntityExtension with new fields and associations, custom field sets, translated fields and how to choose.

Sooner or later a plugin needs to attach its own data to something it does not own: a badge on a product, a loyalty number on a customer, a note on an order. You must not edit core tables or core definitions. Shopware gives you two supported tools for this. Entity extensions add fields and associations to a core definition in code. Custom fields store extra values in a JSON column that most core entities already have.

Both solve the same problem and feel similar, but they have different costs. In this lesson you will see how each one works, how translated fields fit in, and a short decision guide. As before, the real Shopware code is read-only, and the runnable parts are stand-ins: a registry that merges extension fields into a base definition, and a custom field store that validates values and queries JSON on SQLite.

Entity extensions

An extension is a class that extends Shopware\Core\Framework\DataAbstractionLayer\EntityExtension. It names the entity it wants to extend and adds fields in extendFields().

PHP
<?php declare(strict_types=1);

namespace Acme\Badges\Extension\Content\Product;

use Acme\Badges\Core\Content\Badge\BadgeDefinition;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityExtension;
use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\ApiAware;
use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToOneAssociationField;
use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;

class ProductExtension extends EntityExtension
{
    public function extendFields(FieldCollection $collection): void
    {
        $collection->add(
            (new OneToOneAssociationField('acmeBadge', 'id', 'product_id', BadgeDefinition::class, true))
                ->addFlags(new ApiAware())
        );
    }

    public function getEntityName(): string
    {
        return ProductDefinition::ENTITY_NAME;
    }
}

Older Shopware versions identify the target with getDefinitionClass() instead of getEntityName(). Check the abstract class of the version you support.

The association above says: a product has one acmeBadge, found in the plugin's own table through its product_id column. The last constructor argument (true) tells the DAL to delete the badge when the product is deleted. The ApiAware flag exposes the field through the Store API, so the storefront can read it. Without it, the field exists but is hidden from sales channel responses.

Register the extension with a tag, like a definition:

XML
<service id="Acme\Badges\Extension\Content\Product\ProductExtension">
    <tag name="shopware.entity.extension"/>
</service>

You also need the table, via a migration, and a normal definition for the badge entity. The extension only wires the two together.

When you load a product with the association, the data is not a property of ProductEntity. It lives in an extension bag:

PHP
$criteria = new Criteria([$productId]);
$criteria->addAssociation('acmeBadge');

$product = $this->productRepository->search($criteria, $context)->first();
$badge = $product->getExtension('acmeBadge');

Extensions use their own bag deliberately, so your field can never overwrite a core property. If your extension is a scalar field instead of an association, you add it the same way: a StringField in extendFields() plus a column on the core table. Adding columns to core tables is allowed through migrations, but it is the more fragile path: prefer your own table with an association, which is easy to drop on uninstall.

Translated fields

Text that differs per language belongs in a translation table. A definition declares new TranslatedField('title') on the main entity and a TranslationsAssociationField linking to a second definition (an EntityTranslationDefinition) whose table holds one row per entity and language. The translation table has its own migration and a composite key of entity id and language id.

When you read, the DAL picks the right language from the Context (with a fallback chain) and fills the translated property. You can also read the translations association to get every language at once. The benefit is that the Administration and the API treat your text exactly like core text. The cost is two definitions, two tables, and more boilerplate. Do not use it for values that are the same in every language.

Custom fields

Most core entities (product, customer, order, category and more) have a custom_fields JSON column. A custom field set is a named group of fields registered in the database, and each field has a name, a type and an Administration form configuration. Values are stored as JSON inside the column, so no schema change is needed.

You create sets in the Administration (Settings, then Custom fields), or from a plugin. In a plugin, the usual place is the install method, using the custom_field_set.repository:

PHP
$this->container->get('custom_field_set.repository')->upsert([[
    'id' => $setId,
    'name' => 'acme_badge',
    'config' => ['label' => ['en-GB' => 'Badge']],
    'relations' => [['id' => $relationId, 'entityName' => 'product']],
    'customFields' => [[
        'id' => $fieldId,
        'name' => 'acme_badge_text',
        'type' => CustomFieldTypes::TEXT,
        'config' => [
            'label' => ['en-GB' => 'Badge text'],
            'customFieldPosition' => 1,
        ],
    ]],
]], $context);

Use a vendor prefix in names (acme_badge_text), because all plugins share one JSON object per entity. Remove your sets when the plugin is uninstalled and the user chooses not to keep data.

Reading and writing follows the normal repository calls. You write into the customFields property:

PHP
$this->productRepository->update([
    ['id' => $productId, 'customFields' => ['acme_badge_text' => 'New']],
], $context);

$text = $product->getCustomFields()['acme_badge_text'] ?? null;

Custom fields have limits. You cannot index or filter them as cheaply as real columns, you cannot make them a foreign key, and a huge number of them bloats every product row. They also do not reach the Store API unless the field set is allowed for it. Check the exposure rules in the version you use before depending on them in the storefront.

Which one should I use?

Question Custom field Entity extension
A few scalar values per product? Yes Overkill
Needs its own list, many rows per product? No Yes (association)
Needs a foreign key or joins? No Yes
Filtered or sorted a lot in the shop? Weak Yes, with a real column
Editable by the merchant without a deploy? Yes Needs your own admin UI
Schema change and migration? None Yes

A good default: start with a custom field for simple per-entity values the merchant edits. Use an extension with your own table when the data has its own lifecycle, many rows, or serious query needs.

flowchart TD
    A["Need to attach data<br/>to a core entity"] --> B{"Many rows per entity<br/>or joins and filters?"}
    B -- Yes --> C["EntityExtension<br/>+ own table + migration"]
    B -- No --> D{"Merchant edits it<br/>in the Administration?"}
    D -- Yes --> E["Custom field set"]
    D -- No --> F["Either works.<br/>Prefer custom field"]

A quick decision path. When in doubt, custom fields are cheaper; extensions are more powerful.

Indexers and inheritance caveats

Two behaviors surprise newcomers:

  • Indexers. Shopware precomputes some data (search keywords, inherited values, ranking) in background indexers after writes. If your extension or custom field depends on indexed data, the value may lag until the indexer runs. After bulk imports you can run bin/console dal:refresh:index to rebuild. Writing a custom indexer is only needed for heavy derived data.
  • Inheritance. Product variants can inherit values from their main product. A field flagged Inherited reads from the parent when the variant has no own value, and this applies to the product's customFields too. If you extend products, decide whether your data is per product, per variant, or inherited, and test it with a variant. Forgetting this leads to "the badge shows on the main product but not on the variants".

Try it: an extension registry

Real extensions are applied while the DAL builds its definition registry: the base definition gives its fields, and every tagged extension may add more. This stand-in does the same with plain arrays and shows how reading an extension differs from reading a core property.

PHP Merging extension fields into a definition

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.

What is stand-in: the registry (the real one is built by the container and compiler passes) and the entity bag. What is real: the idea that an extension adds fields to a definition owned by someone else, and that its data is read through getExtension().

Try it: custom field sets with validation

This stand-in registers a field set, validates writes against the declared types, stores the values as JSON in one column, and queries them with SQLite's JSON functions. Real Shopware validates according to the field type and its Administration config; MySQL has comparable JSON functions, but filtering on them is slower than on a real column.

PHP Custom fields stored as JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the unknown or mistyped values never reach the column, and that merging keeps values written earlier. A real column would be faster to filter, which is the main reason to choose an extension for data you query heavily.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you read the data of an association added by an EntityExtension?

    Extension data lives in an extension bag, so it can never overwrite a core property.
  2. 2. Which tag registers an EntityExtension?

    shopware.entity.extension is the tag for extensions; shopware.entity.definition is for new entity definitions.
  3. 3. A merchant needs to edit one short text per product in the Administration, without a deployment. What fits best?

    A custom field needs no schema change and gets an edit form in the Administration automatically.
  4. 4. Why should custom field names carry a vendor prefix?

    Names such as acme_badge_text avoid clashes with fields from other plugins or the core.
  5. 5. What problem does the Inherited flag address?

    Variants can inherit values from the parent, and your extension has to decide how it behaves with variants.

Summary

  • An EntityExtension adds fields and associations to a core definition; its data is read with getExtension().
  • Register extensions with the shopware.entity.extension tag, and create the tables in a migration.
  • Custom fields store values in an existing JSON column, need no migration, and are editable in the Administration, but are weak for heavy filtering and joins.
  • Translated fields need a translation definition and table; use them only for text that differs per language.
  • Plan for indexers (derived data may lag) and for inheritance between variants.

Next, react to what happens in the platform in Subscribers and Core Events.