Custom fields

Version

6.0.0 or newer

Table of contents

Custom fields guide

Shopware's custom field system allows you to extend existing entities, without writing a complete entity extension. This is possible by storing the additional data in a JSON-Field . Custom fields therefore can only be used to store scalar values. If you'd like to create associations between entities, you'll need to use an entity extension .

Adding custom fields

To add custom fields to an entity, you can use the custom fieldset repository, which can be retrieved from the dependency injection container via the custom_field_set.repository key. The class returned implements the EntityRepositoryInterface and can be used like any other repository. You may annotate it accordingly for convenience:

// SwagExamplePlugin/src/Service/SwagCustomFieldSetService.php

<?php declare(strict_types=1);

class SwagCustomFieldSetService {

    /**
     * @var EntityRepositoryInterface
     */
    private $customFieldSetRepository;

    public function __construct(EntityRepositoryInterface $customFieldSetRepository)
    {
        $this->customFieldSetRepository = $customFieldSetRepository;

        // ...
    }

    // ...

}

Now that that's done, you can use the repository to add new custom fields:

$this->customFieldSetRepository->create([
    [
        'name' => 'swag_example',
        'customFields' => [
            ['name' => 'swag_example_size', 'type' => CustomFieldTypes::INT],
            ['name' => 'swag_example_color', 'type' => CustomFieldTypes::TEXT]
        ]
    ]
], $context);

As you may have noticed, the repository used here is the custom_field_set_repository and the data structure encapsulates multiple customFields. This is the case, because these are user-editable custom fields which will be visible in the custom field settings in the administration. If you don't want users of your plugin to change any of the custom field settings, you can also omit the relation to a fieldset, by adding the fields to an entity directly:

$this->productRepository->upsert([[
    'id' => '0a1b1ab305a94debb53d5aedf5349b8c',
    'customFields' => ['swag_example_size' => 15, 'swag_example_color' => '#189eff']
]], $context);

You can now use these custom fields in criteria:

$this->productRepository->search(
    (new Criteria())->addFilter(new EqualsFilter('customFields.swag_example_color', '#189eff'))
, $context);

Was this article helpful?