{"id":12920,"date":"2021-09-16T01:17:49","date_gmt":"2021-09-16T06:47:49","guid":{"rendered":"https:\/\/emizentech.com\/blog\/?p=12920"},"modified":"2024-12-31T11:35:32","modified_gmt":"2024-12-31T11:35:32","slug":"create-custom-field-in-database-entity-in-shopware","status":"publish","type":"post","link":"https:\/\/emizentech.com\/blog\/create-custom-field-in-database-entity-in-shopware.html","title":{"rendered":"How To Create Custom Field In Database Entity In Shopware"},"content":{"rendered":"<p>Shopware&#8217;s custom field system allows you to extend 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&#8217;d like to create associations between entities, you&#8217;ll need to use an Entity extension.<\/p>\r\n<p>Supporting custom fields with your entity<\/p>\r\n<p>For creating custom fields in database we need to extend any entity definition which is already created in shopware.<\/p>\r\n<p>In order to support custom fields with your custom entity, there are two steps necessary:<\/p>\r\n<ul>\r\n<li>1) Add a CustomFields field to your EntityDefinition<\/li>\r\n<li>2) Add a column custom_fields to your entities&#8217; database table via migration<\/li>\r\n<\/ul>\r\n<p>Also, you may want to add translatable custom fields, which is also covered in very short here.<\/p>\r\n<h3>Add custom field to entity definition<\/h3>\r\n<pre>&lt;plugin root&gt;\/src\/Core\/Content\/Example\/ExampleDefinition.php\r\n\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Field\\CustomFields;                                                                    \r\n\u200b\r\n[...]\r\nclass ExampleDefinition extends EntityDefinition\r\n{\r\n    [...]\r\n    protected function defineFields(): FieldCollection\r\n    {\r\n        return new FieldCollection([\r\n            (new IdField('id', 'id'))-&gt;addFlags(new Required(), new PrimaryKey()),\r\n            (new StringField('name', 'name')),\r\n            (new StringField('description', 'description')),\r\n            (new BoolField('active', 'active')),\r\n            new CustomFields()\r\n        ]);\r\n    }\r\n}\r\n<\/pre>\r\n<p>Note the new field that was added in the FieldCollection. That&#8217;s already it for your custom entity definition. Now go ahead and add the column to the database.<\/p>\r\n<h3>Add column in database table<\/h3>\r\n<p>If you want to support custom fields now, you have to add a new column custom_fields of type JSON to your migration.<\/p>\r\n<pre>&lt;plugin root&gt;\/src\/Migration\/Migration1611664789Example.php\r\npublic function update(Connection $connection): void\r\n{\r\n    $sql = &lt;&lt;&lt;SQL\r\n        CREATE TABLE IF NOT EXISTS `swag_example` (\r\n        `id` BINARY(16) NOT NULL,\r\n        `name` VARCHAR(255) COLLATE utf8mb4_unicode_ci,\r\n        `description` VARCHAR(255) COLLATE utf8mb4_unicode_ci,\r\n        `active` TINYINT(1) COLLATE utf8mb4_unicode_ci,\r\n\u200b\r\n        `custom_fields` json DEFAULT NULL,\r\n\u200b\r\n        `created_at` DATETIME(3) NOT NULL,\r\n        `updated_at` DATETIME(3),\r\n        PRIMARY KEY (`id`)\r\n        )\r\n        ENGINE = InnoDB\r\n        DEFAULT CHARSET = utf8mb4\r\n        COLLATE = utf8mb4_unicode_ci;\r\n    SQL;\r\n    $connection-&gt;executeStatement($sql);\r\n}\r\n<\/pre>\r\n<p>Custom field always must be json field and it should default to null, since it doesn&#8217;t have to contain values.<\/p>\r\n<h3>Add translatable custom field to entity definition<\/h3>\r\n<p>Make sure to understand entity translations in general first, which is explained here Add data translations. If you want your custom fields to be translatable, you can simply work with a TranslatedField here as well.<\/p>\r\n<pre>&lt;plugin root&gt;\/src\/Core\/Content\/Example\/ExampleDefinition.php\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Field\\TranslatedField;                                                               \r\n\u200b\r\n[...]\r\n\u200b\r\nclass ExampleDefinition extends EntityDefinition\r\n{\r\n    [...]\r\n\u200b\r\n    protected function defineFields(): FieldCollection\r\n    {\r\n        return new FieldCollection([\r\n            (new IdField('id', 'id'))-&gt;addFlags(new Required(), new PrimaryKey()),\r\n            (new StringField('name', 'name')),\r\n            (new StringField('description', 'description')),\r\n            (new BoolField('active', 'active')),\r\n\u200b\r\n            new TranslatedField('customFields'),\r\n        ]);\r\n    }\r\n}\r\n<\/pre>\r\n<p>Just add the TranslatedField and apply customFields as a parameter.<br \/>In your translated entity definition, you then add the CustomFields field instead.<\/p>\r\n<pre>&lt;plugin root&gt;\/src\/Core\/Content\/Example\/Aggregate\/ExampleTranslation\/ExampleTranslationDefinition.php\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Field\\CustomFields;                                                                    \r\n[...]\r\nclass ExampleTranslationDefinition extends EntityTranslationDefinition\r\n{\r\n    [...]\r\n\u200b\r\n    protected function defineFields(): FieldCollection\r\n    {\r\n        return new FieldCollection([\r\n            (new StringField('name', 'name'))-&gt;addFlags(new Required()),\r\n\u200b\r\n            new CustomFields()\r\n        ]);\r\n    }\r\n}\r\n<\/pre>\r\n<h3>Add custom fields to an entity<\/h3>\r\n<p>Defining a custom field set is not necessary it is only necessary, if you want it to be editable in the administration or if you need validation when writing your custom field.<\/p>\r\n<p>Because of that, we&#8217;ll start with filling data to an actual entities&#8217; custom field, before actually defining it.<\/p>\r\n<h4>Filling data into custom fields<\/h4>\r\n<pre>$this-&gt;swagExampleRepository-&gt;upsert([[\r\n    'id' =&gt; '&lt;your ID here&gt;',\r\n    'customFields' =&gt; ['swag_example_size' =&gt; 15]\r\n]], $context);\r\n<\/pre>\r\n<p>You can write any valid json you want to write in custom Field. Example:<\/p>\r\n<pre>$this-&gt;swagExampleRepository-&gt;upsert([[\r\n    'id' =&gt; '&lt;your ID here&gt;',\r\n    'customFields' =&gt; [ 'foo' =&gt; 'bar', 'baz' =&gt; [] ]\r\n]], $context);\r\n<\/pre>\r\n<h4>Adding an actual custom field<\/h4>\r\n<p>You can skip this section if you do not want your new custom field to be editable in the administration.<\/p>\r\n<p>use Shopware\\Core\\System\\CustomField\\CustomFieldTypes;<\/p>\r\n<pre>[...]\r\n\r\n$this-&gt;customFieldSetRepository-&gt;create([\r\n    [\r\n        'name' =&gt; 'swag_example_set',\r\n        'config' =&gt; [\r\n            'label' =&gt; [\r\n                'en-GB' =&gt; 'English custom field set label',\r\n                'de-DE' =&gt; 'German custom field set label'\r\n            ]\r\n        ],\r\n        'customFields' =&gt; [\r\n            [\r\n                'name' =&gt; 'swag_example_size',\r\n                'type' =&gt; CustomFieldTypes::INT,\r\n                'config' =&gt; [\r\n                    'label' =&gt; [\r\n                        'en-GB' =&gt; 'English custom field label',\r\n                        'de-DE' =&gt; 'German custom field label'\r\n                    ],\r\n                    'customFieldPosition' =&gt; 1\r\n                ]\r\n            ]\r\n        ]\r\n    ]\r\n], $context);\r\n<\/pre>\r\n<h3>Here is the example of removing some categories from navigation menu.<\/h3>\r\n<p>I am adding a custom field which will hide menu from sidebar.<\/p>\r\n<p>custom\/plugin\/pluginRoot\/src\/pluginName.php<\/p>\r\n<p>Have a look on the screenshot:<br \/><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-12258\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/shopware-remove-categories-1.png\" alt=\"shopware remove categories 1\" width=\"801\" height=\"355\" \/><\/p>\r\n<p>Here my plugin name is SidebarNavigation<\/p>\r\n<p><strong>This class will perform operation on custom_field_set<\/strong><\/p>\r\n<pre>&lt;?php declare(strict_types=1);\r\n\r\nnamespace SidebarNavigation;\r\n\r\nuse Doctrine\\DBAL\\Connection;\r\nuse Shopware\\Core\\Framework\\Plugin;\r\nuse Shopware\\Core\\Framework\\Plugin\\Context\\UninstallContext;\r\nuse Shopware\\Core\\Framework\\Plugin\\Context\\InstallContext;\r\nuse Shopware\\Core\\Framework\\Context;\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\IdSearchResult;\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Criteria;\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Filter\\EqualsAnyFilter;\r\nuse SidebarNavigation\\Services\\SidebarNavigationCustomFieldSetService;\r\n\r\nclass SidebarNavigation extends Plugin\r\n{\r\n    public function install(InstallContext $installContext): void\r\n    {\r\n        parent::install($installContext);\r\n\r\n        $SidebarNavigationCustomFieldSetService = new SidebarNavigationCustomFieldSetService(\r\n            $this-&gt;container-&gt;get('custom_field_set.repository')\r\n        );\r\n\r\n        \/** @var Context $context *\/\r\n        $context = $installContext-&gt;getContext();\r\n\r\n        $SidebarNavigationCustomFieldSetService-&gt;createCategoryCustomFieldSet($context);\r\n    }\r\n\r\n    public function uninstall(UninstallContext $context): void\r\n    {\r\n        parent::uninstall($context);\r\n        if ($context-&gt;keepUserData()) {\r\n            return;\r\n        }\r\n\r\n        $this-&gt;removeCustomFields($context);\r\n    }\r\n\r\n    private function removeCustomFields(UninstallContext $uninstallContext)\r\n    {\r\n        $customFieldSetRepository = $this-&gt;container-&gt;get('custom_field_set.repository');\r\n\r\n        \/** @var Context $context *\/\r\n        $context = $uninstallContext-&gt;getContext();\r\n\r\n        \/\/ Delete custom field set\r\n\r\n        $this-&gt;deleteCustomFieldSet(\r\n            $context,\r\n            $customFieldSetRepository,\r\n            SidebarNavigationCustomFieldSetService::SIDEBAR_CATEGORY_NAVIGATION_CUSTOM_FIELD_SET\r\n        );\r\n    }\r\n\r\n    private function deleteCustomFieldSet(Context $context, $customFieldSetRepository, string $customFieldSet): void\r\n    {\r\n        $customFieldIds = $this-&gt;getCustomFieldSetIds($context, $customFieldSet);\r\n\r\n        if ($customFieldIds) {\r\n            $customFieldSetRepository-&gt;delete(array_values($customFieldIds-&gt;getData()), $context);\r\n        }\r\n    }\r\n\r\n    private function getCustomFieldSetIds(Context $context, string $customFieldSet): ?IdSearchResult\r\n    {\r\n        $customFieldSetRepository = $this-&gt;container-&gt;get('custom_field_set.repository');\r\n\r\n        $criteria = new Criteria();\r\n        $criteria-&gt;addFilter(new EqualsAnyFilter('name', [$customFieldSet]));\r\n\r\n        $customFieldIds = $customFieldSetRepository-&gt;searchIds($criteria, $context);\r\n\r\n        return $customFieldIds-&gt;getTotal() &gt; 0 ? $customFieldIds : null;\r\n    }\r\n}\r\n<\/pre>\r\n<p>Then create a service on the given location which will create custom field:<\/p>\r\n<p>\/custom\/plugins\/PluginRoot\/src\/Services<\/p>\r\n<pre>&lt;?php declare(strict_types=1);\r\n\r\nnamespace SidebarNavigation\\Services;\r\n\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\EntityRepositoryInterface;\r\nuse Shopware\\Core\\System\\CustomField\\CustomFieldTypes;\r\nuse Shopware\\Core\\Framework\\Context;\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Criteria;\r\nuse Shopware\\Core\\Framework\\DataAbstractionLayer\\Search\\Filter\\EqualsFilter;\r\nuse Shopware\\Core\\System\\CustomField\\Aggregate\\CustomFieldSet\\CustomFieldSetCollection;\r\nuse Shopware\\Core\\Framework\\Uuid\\Uuid;\r\n\r\nclass SidebarNavigationCustomFieldSetService {\r\n    \/\/custom field set\r\n    public const SIDEBAR_CATEGORY_NAVIGATION_CUSTOM_FIELD_SET = 'sidebar_category_navigation_custom_field_set';\r\n\r\n    public const SIDEBAR_CATEGORY_ACTIVE_CUSTOM_FIELD = 'sidebar_category_active_custom_field';\r\n    \/**\r\n     * @var EntityRepositoryInterface\r\n     *\/\r\n    private $customFieldSetRepository;\r\n\r\n    public function __construct(EntityRepositoryInterface $customFieldSetRepository)\r\n    {\r\n        $this-&gt;customFieldSetRepository = $customFieldSetRepository;\r\n    }\r\n\r\n    public function createCategoryCustomFieldSet(Context $context): void\r\n    {\r\n        $criteria = new Criteria();\r\n        $criteria-&gt;addFilter(new EqualsFilter('name', self::SIDEBAR_CATEGORY_NAVIGATION_CUSTOM_FIELD_SET));\r\n\r\n        \/** @var CustomFieldSetCollection $customFieldSets *\/\r\n        $customFieldSets = $this-&gt;customFieldSetRepository-&gt;search($criteria, $context)-&gt;getEntities();\r\n\r\n        if (!count($customFieldSets)) {\r\n            $this-&gt;customFieldSetRepository-&gt;create([\r\n                [\r\n                    'name' =&gt; self::SIDEBAR_CATEGORY_NAVIGATION_CUSTOM_FIELD_SET,\r\n                    'global' =&gt; true,\r\n                    'config' =&gt; [\r\n                        'label' =&gt; [\r\n                            'de-DE' =&gt; 'Sidebar (Navigation)',\r\n                            'en-GB' =&gt; 'Sidebar (Navigation)'\r\n                        ]\r\n                    ],\r\n                'customFields' =&gt; [\r\n                    [\r\n                        'name' =&gt; self::SIDEBAR_CATEGORY_ACTIVE_CUSTOM_FIELD,\r\n                        'type' =&gt; CustomFieldTypes::SWITCH,\r\n                        'config' =&gt; [\r\n                            'label' =&gt; [\r\n                                'de-DE' =&gt; 'Hide in sidebar navigation',\r\n                                'en-GB' =&gt; 'Hide in sidebar navigation'\r\n                            ],\r\n\/\/Here I am creating SWITCH type field, we can create any field you want.\r\n                            'componentName' =&gt; 'sw-field',\r\n                            'type' =&gt; CustomFieldTypes::SWITCH,\r\n                            'customFieldType' =&gt; CustomFieldTypes::SWITCH,\r\n                            'customFieldPosition' =&gt; 1\r\n                        ]\r\n                    ]\r\n                ],\r\n                'relations' =&gt; [\r\n                    [\r\n                        'id' =&gt; Uuid::randomHex(),\r\n                        'entityName' =&gt; 'category' \/\/ You can use any entity where you want to create custom field.\r\n                    ]\r\n                ]\r\n                ]\r\n            ], $context);\r\n\r\n            \r\n        }\r\n    }\r\n}\r\n<\/pre>\r\n<p>Here are some more types of custom fields:<\/p>\r\n<div class=\"blog-innertxt\">\r\n<ul class=\"benefits-points\">\r\n<li>1) CustomFieldTypes::TEXT<\/li>\r\n<li>2) CustomFieldTypes::JSON<\/li>\r\n<li>3) CustomFieldTypes::INT<\/li>\r\n<li>4) CustomFieldTypes::BOOL<\/li>\r\n<\/ul>\r\n<\/div>\r\n<p>I have removed the categories from storefront for this I have extended the category navigation file. Follow the given location<br \/>custom\/plugins\/PluginRoot\/src\/Resources\/views\/storefront\/layout\/sidebar<\/p>\r\n<pre>{% sw_extends '@Storefront\/storefront\/layout\/sidebar\/category-navigation.html.twig' %}\r\n\r\n{% block layout_navigation_categories_list_entry %}\r\n{% if not item.category.customFields.sidebar_category_active_custom_field is defined %}\r\n    &lt;li class=\"category-navigation-entry\"&gt;\r\n        {% block layout_navigation_categories_link_children %}\r\n           {{parent()}}\r\n        {% endblock %}\r\n        {% block layout_navigation_categories_recoursion %}\r\n            {{parent()}}\r\n        {% endblock %}\r\n    &lt;\/li&gt;\r\n{% endif %}\r\n{% endblock %}\r\n<\/pre>\r\n<p>Look into Screenshot on Category for new Custom Field:<\/p>\r\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-12257\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/Shopware-custom-field-2-1.png\" alt=\"Shopware custom field 2\" width=\"1394\" height=\"528\" \/><br \/>Here is the screenshot of the categories with removed menus:<br \/><img decoding=\"async\" class=\"aligncenter size-full wp-image-12259\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/shopware-removed-menus.png\" alt=\"shopware removed menus\" width=\"537\" height=\"533\" \/><\/p>\r\n","protected":false},"excerpt":{"rendered":"<p>Shopware&#8217;s custom field system allows you to extend 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&#8217;d like to create associations between entities, you&#8217;ll need to use an Entity extension. Supporting custom fields with<\/p>\n","protected":false},"author":36,"featured_media":12334,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_seo_llms_txt_always_include":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_wpcom_ai_launchpad_first_post":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[85],"tags":[84],"class_list":["post-12920","post","type-post","status-publish","format-standard","has-post-thumbnail","category-shopware","tag-shopware"],"featured_image_src":"https:\/\/emizentech.com\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/How-To-Override-A-Controller-In-Shopware-6-1.png","featured_image_src_square":"https:\/\/emizentech.com\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/How-To-Override-A-Controller-In-Shopware-6-1.png","author_info":{"display_name":"Vivek Khatri","author_link":"https:\/\/emizentech.com\/blog\/author\/vivek"},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/emizentech.com\/blog\/wp-content\/uploads\/sites\/2\/2021\/09\/How-To-Override-A-Controller-In-Shopware-6-1.png","_links":{"self":[{"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/posts\/12920","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/users\/36"}],"replies":[{"embeddable":true,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/comments?post=12920"}],"version-history":[{"count":1,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/posts\/12920\/revisions"}],"predecessor-version":[{"id":44534,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/posts\/12920\/revisions\/44534"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/media\/12334"}],"wp:attachment":[{"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/media?parent=12920"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/categories?post=12920"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/emizentech.com\/blog\/wp-json\/wp\/v2\/tags?post=12920"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}