# OpenDXP Documentation This file contains all documentation content in a single document following the llmstxt.org standard. ## Changelog ### 1.1.1 - [ENHANCEMENT] Sign ins through a provider and changes of users are written to a security log. See [Security Log](README.md#security-log) - [SECURITY] [OPENDXP-SA-2026-010] The sign in through a provider checks its state with a cookie of its own. It works with a strict and a lax session cookie - [SECURITY] [FOLLOW-UP] [OPENDXP-SA-2026-009] An Azure mandate without a tenant id no longer gives roles to every Microsoft account. Its sign in is refused when a scope has no condition or the mandate has default roles 1. Set the id of your tenant in `client.tenant` of every Azure mandate. - [ENHANCEMENT] Users of a mandate sign in through the provider only. They no longer receive a lost password mail and cannot sign in with a password - [SECURITY] [MIGRATION] [OPENDXP-SA-2026-011] Users are linked to their provider account by its id instead of their username. A new account with the same username no longer takes over an existing user ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] Change to new css color variable prefix naming ### 1.0.1 - [ENHANCEMENT] PHP 8.5 support added ### 1.0.0 - [NEW FEATURE] Initial release - [ENHANCEMENT] UI update [#1](https://github.com/open-dxp/admin-auth-bundle/pull/1) - [CHORE] Unify test infrastructure across bundles [#2](https://github.com/open-dxp/admin-auth-bundle/pull/2) --- ## Migrating to OpenDXP ### Migrating from `dachcom/pimcore-admin-auth:2.x` to `open-dxp/admin-auth-bundle:^1.0` * Moved Bundle to new namespace: `OpenDxp\Bundle\AdminAuthBundle` * Renamed Bundle to `OpenDxpAdminAuthBundle` * Change top-level config node to `opendxp_admin_auth` --- ## Admin Auth Bundle ### Rules - If no roles can be assigned (no remote nor default roles found), - and the user does not exist, an exception will be thrown, no data will be created - and the user exists, login is no longer possible ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.0` | `^7.3` | 2025 | Feature Branch | 1.x | ### Supported Clients - Azure ### Installation #### I. Add Dependency ```json { "require" : { "open-dxp/admin-auth-bundle" : "~1.0.0" }, "repositories": [ { "type": "composer", "url": "https://open-dxp.repo.repman.io" } ] } ``` #### II. Register Bundle Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\AdminAuthBundle\OpenDxpAdminAuthBundle::class => ['all' => true], ]; ``` #### III. Configuration ```yaml opendxp_admin_auth: mandates: # Mandate name azure: # Scopes will be merged! If there are multiple matches, the user will be assigned to multiple roles! scopes: # scenario I: all members of group "digital" are allowed to log in as "editor" - required_groups: - 'DIGITAL' assigned_roles: - 'editor' # scenario II: all members of group "digital" AND "project_a" are allowed to log in as "editor" - required_groups: - 'DIGITAL' - 'SWISSOLAR' assigned_roles: - 'editor' # scenario III: all members of group "digital" AND "project_a" AND "opendxp_admin" are allowed to log in as Admin-User - required_groups: - 'DIGITAL' - 'SWISSOLAR' assigned_roles: # magic variable: the user will be treated as admin (which can't be defined by roles) - !php/const OpenDxp\Bundle\AdminAuthBundle\Manager\ClientManager::ADMIN_ROLE_IDENTIFIER # scenario IV: all members of group "digital" AND "project_a" AND role "special_role" are allowed to log in as "editor" # [NOT AVAILABLE IN DACHCOM CONTEXT] - required_groups: - 'DIGITAL' - 'SWISSOLAR' required_roles: - 'special_role' assigned_roles: - 'editor' user: # opendxp_user_folder_name: 'Remote Users' role: # opendxp_role_folder_name: 'Remote Groups' # Set default roles, if you want to add them if no remote roles are available # default_roles: # - MyRole # If false (default), an exception will be thrown if role can't be found # create_role_if_not_exists: true client: type: azure client_id: '%env(AZURE_CLIENT_ID)%' client_secret: '%env(AZURE_CLIENT_SECRET)%' redirect_route: opendxp_auth_connect_check redirect_params: { client: azure } scope: - 'openid' tenant: '%env(AZURE_TENANT)%' # template: ## If you want to disable the default opendxp login form, set this to true # render_default_opendxp_login_form: false ## set add_twig_paths to false, if you need to override opendxp admin templates within your projects ## [ATTENTION!] You have to extend your twig files from @!OpenDxpAdminAuth/bundles/OpenDxpAdminBundle/Admin/*/*.html.twig (if existing) # add_twig_paths: true ``` #### VI. Security Configuration ```diff # app/config/packages/security.yaml security: # ... access_control: + - { path: ^/admin/auth/connect/azure/check$, roles: PUBLIC_ACCESS } ``` #### V. Add Translations Each client will create a admin translation label, which needs to be translated by you: `opendxp_auth.label.login_with_*`. If the `azure` client is active, a translation key `opendxp_auth.label.login_with_azure` will be created. ### Remote Users Users of a mandate sign in through the provider only. OpenDXP sends them no lost password mail and refuses their password. The bundle links each user to their account at the provider. It stores the mandate and the account id in the `provider` field of the user, for example `admin_auth:azure:5d6e7f80-1a2b-4c3d-8e9f-0a1b2c3d4e5f`. A new account with the same username cannot take over an existing user. To rename a mandate or to move its users to another mandate, set their `provider` field to `admin_auth:`. The bundle links them to their account again on their next sign in. ### Security Log The bundle writes security events to the Monolog channel `admin_auth`. The handler `admin_auth` stores them in `var/log/admin_auth-.log` and deletes a file after 30 days. | Event | Level | Context | |-----------------------------------------|-----------|----------------------------------------------------------------------| | A sign in through a provider failed | `warning` | `mandate`, `reason` | | A provider sign in created a user | `info` | `user`, `mandate` | | A user was linked to a provider account | `info` | `user`, `mandate` | | The roles of a user changed | `info` | `user`, `roles_before`, `roles_after`, `admin_before`, `admin_after` | Every entry also contains the IP address of the request as `ip`. The log contains IP addresses. Mention it in your privacy policy. The purpose is the detection and the investigation of attacks on backend accounts. Change the retention in your `config/config.yaml`: ```yaml monolog: handlers: admin_auth: max_files: 14 ``` Disable the log: ```yaml opendxp_admin_auth: security_log: enabled: false ``` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\AdminAuthBundle\Migrations'` - Read the [changelog](CHANGELOG.md) before you update. - Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Setup After you have enabled this Bundle, there are some global steps to define. ### Frontend First, setup your twig layout. #### Default Layout Your default layout metadata head should look like this. If you've enabled the `auto_detect_documents` [feature](./MetaData/10_Integrator.md), all documents will be automatically rendered with corresponding metadata values. ```twig {# layout.html.twig #} {% block metadata %} {{ opendxp_head_title() }} {{ opendxp_head_meta() }} {{ opendxp_head_link() }} {% endblock metadata %} {% block content %}

Some page body.

{% endblock content %} ``` #### Sub-Layout On a special route - mostly a static route - you need to inform the meta provider to extract metadata from your object. ```twig {# product/detail.html.twig #} {% extends 'layout.html.twig' %} {% block metadata %} {% do seo_update_metadata(object, app.request.locale) %} {{ parent() }} {% endblock metadata %} {% block content %} {# my object layout #} {% endblock content %} ``` ### Deprecate OpenDxp SEO Features With this bundle, you may don't want to use the default SEO panel in opendxp documents. To disable the panel in backend you need to set `hide_opendxp_default_seo_panel` to `true`. > **Note**: Already populated fields like title, description and all meta fields will automatically moved to the seo bundle context. No migration needed! ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: documents: enabled: true hide_opendxp_default_seo_panel: true ``` ### Next Steps Learn more about metadata or the index notification. - [Meta Data](./10_MetaData.md) [Set Title, Description, ...] - [Index Notification](./20_IndexNotification.md) [Push Data to Google Index] ### Configuration A full configuration layout could look like this: ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_provider: auto_detect_documents: true meta_data_integrator: documents: enabled: true hide_opendxp_default_seo_panel: true objects: enabled: true data_classes: - MyObject enabled_integrator: - integrator_name: title_description - integrator_name: open_graph integrator_config: facebook_image_thumbnail: 'socialThumb' - integrator_name: twitter_card integrator_config: twitter_image_thumbnail: 'socialThumb' - integrator_name: schema - integrator_name: html_tag index_provider_configuration: enabled_worker: - worker_name: google_index worker_config: auth_config: config/opendxp/google-api-private-key.json # default opendxp: config/opendxp/google-api-private-key.json opendxp_element_watcher: enabled: true ``` --- ## Metadata Section There are two important things within the metadata section: integrators and extractors. ### Integrators Integrator allows you to define metadata in backend context. There are several pre-configured integrators, but it's also possible to add your own. It's possible to enable a dedicated SEO panel on documents and/or objects. Enable the SEO panel on documents/objects: ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: documents: enabled: true objects: enabled: true data_classes: - MyObjectClass ``` This will add an additional `SEO` tab on your documents and objects of type `MyObjectClass`. If you want to render integrator as `fieldset` instead of `tab` (default), you need to change it like that: ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: integrator_rendering_type: 'fieldset' ``` Read more about integrators and how to use them [here](./MetaData/10_Integrator.md). ### Extractors Every extractor will extract structured data from a given object/document. Read more about integrators and how to use them [here](./MetaData/20_Extractors.md). ### More Information - [Integrators](./MetaData/10_Integrator.md) - [Title & Description Integrator](./MetaData/Integrator/10_TitleDescriptionIntegrator.md) - [Open Graph Integrator](./MetaData/Integrator/11_OpenGraphIntegrator.md) - [Twitter Card Integrator](./MetaData/Integrator/12_TwitterCardIntegrator.md) - [Schema Integrator](./MetaData/Integrator/13_SchemaIntegrator.md) - [HTML-Tag Integrator](./MetaData/Integrator/14_HtmlTagIntegrator.md) - [Extractors](./MetaData/20_Extractors.md) - [Custom Extractor](./MetaData/Extractor/10_CustomExtractor.md) ### Full Configuration Example ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_provider: auto_detect_documents: true meta_data_integrator: documents: enabled: true hide_opendxp_default_seo_panel: true objects: enabled: true data_classes: - MyObjectClass enabled_integrator: - integrator_name: title_description - integrator_name: open_graph integrator_config: facebook_image_thumbnail: 'socialThumb' - integrator_name: html_tag ``` --- ## Index Notification Section This bundle allows you to submit your updated/removed documents/objects to a given index - a so called `worker`. Currently, we only support [google](./IndexNotification/Worker/01_GoogleWorker.md) via the google index API. To use this feature, you need to enable it and you also need to add your own resource processor. ### Enable Index Notifications ```yaml opendxp_advanced_seo: index_provider_configuration: enabled_worker: - worker_name: google_index worker_config: auth_config: config/opendxp/google-api-private-key.json ``` ### Enable OpenDxp Element Watcher It's a good idea to enable the `opendxp_element_watcher` by default. It will auto-submit changed/delete objects/documents to all available processors. The object/documents will be added to a queue automatically (but only if a processor has been found). ```yaml opendxp_advanced_seo: index_provider_configuration: opendxp_element_watcher: enabled: true ``` , ### Register Service ```yaml App\Seo\ResourceProcessor\MyProcessor: tags: - { name: seo.index.resource_processor, identifier: my_processor } ``` ### Service ````php $locale]; } return $queueContext; } /** * {@inheritDoc} */ public function processQueueEntry(QueueEntryInterface $queueEntry, string $workerIdentifier, array $context, $resource) { $dataUrl = null; $locale = $context['locale']; $linkGenerator = $this->fetchMyObjectLinkGenerator(); $link = $linkGenerator->generate($resource, ['locale' => $locale]); $queueEntry->setDataType('object'); $queueEntry->setDataId($resource->getId()); $queueEntry->setDataUrl($link); return $queueEntry; } /** * {@inheritDoc} */ public function processWorkerResponse(WorkerResponseInterface $workerResponse) { // There are already some basic logs in your application logger! // @todo: add custom "nice" log to a specific output... // throw intercepted response exception. // this will stop SEO Bundle from logging default data to application logger. // if you want to keep the logging, just remove this exception. throw new WorkerResponseInterceptException(); } } ```` --- ## Genius Content Crafter reads, filters and writes the SEO metadata this bundle stores. There is no query domain and no tool of its own. SEO data is a field on documents and objects, reached through `query_documents`, `query_objects`, `query_elements` and the `get_*` tools, under the permissions those already need. The integration is only loaded where the Content Crafter bundle is installed. These are questions an editor types into Genius. Each is answered from the stored SEO data, with the elements listed where there are few enough and counted where there are not: - *Which documents have an SEO title but no SEO description?* - *Which products have an Italian SEO title?* - *Which pages have no Open Graph block?* - *Which products are still missing the German title?* None of them needs a filter written by hand. The rest of this page is the filter Genius builds out of such a question, for anyone who has to check it or extend it. - [The two fields](#the-two-fields) - [Find elements without SEO data](#find-elements-without-seo-data) - [Ask in one language](#ask-in-one-language) - [Write a value](#write-a-value) - [The write that is refused](#the-write-that-is-refused) - [The suggestion this bundle brings](#the-suggestion-this-bundle-brings) - [Debug the field pipeline](#debug-the-field-pipeline) ### The two fields | field | type | written | holds | |----------------|-------------|---------|------------------------------------------------------------| | `seoMetaData` | `relations` | yes | what an editor typed in, one item per value | | `seoPrefilled` | `boolean` | no | whether an extractor fills the element in while it renders | An item of `seoMetaData` has four keys. A filter names the same ones a write does. | key | holds | |--------------|------------------------------------------------------------------------| | `integrator` | the SEO block: `title_description`, `open_graph`, `twitter_card`, ... | | `field` | the value inside it: `title`, `description`, `og:image` | | `locale` | the language of the value | | `values` | the text | The integrator names of an installation are listed on the field itself, under `itemOptions`. Only elements SEO is switched on for are considered: pages when documents are enabled, and the configured `data_classes` when objects are, see [Meta Data](10_MetaData.md). The field carries that limit itself, so a question about missing SEO data needs no filter for it. ### Find elements without SEO data A field nobody filled in has no item, so `none` is the whole question. *Which pages have no Open Graph block?* asks it: ```json {"seoMetaData": {"none": {"integrator": "open_graph"}}} ``` *Which documents have an SEO title but no SEO description?* names both sides of the same field: ```json {"seoMetaData": {"any": {"integrator": "title_description", "field": "title"}, "none": {"integrator": "title_description", "field": "description"}}} ``` *Which pages mention "free consultation" in their SEO description?* compares `values` as text: ```json {"seoMetaData": {"any": {"field": "description", "values": {"contains": "free consultation"}}}} ``` A count filtered on `seoMetaData` comes back split by `seoPrefilled` in its `breakdown`. Filtering on both throws one half of that answer away. ### Ask in one language *Which products have an Italian SEO title?* ```json {"seoMetaData": {"any": {"integrator": "title_description", "field": "title", "locale": "it"}}} ``` A product with a German title and none in Italian is not in that answer. Turn it around for *which products are still missing the German title?*: ```json {"seoMetaData": {"none": {"integrator": "title_description", "field": "title", "locale": "de"}}} ``` `locale` answers for both kinds of element. | element | language of a value | |------------|------------------------------------------------------------------------| | an object | the value carries it, one per language | | a document | the page carries it, in its `language` property | A page without that property counts as `general.default_language`. That is the language it renders in, so the filter and the site agree. A value that carries no language of its own, `twitter:card` for one, holds for every language and is found by naming any of them. ### Write a value Only what is named changes. Writing a title leaves the description, the other languages and the other integrators as they are. Genius reads and writes what the backend shows. A page saved without publishing has its own SEO values, and those are the ones a filter finds, a read returns and a write goes into. Publishing the page publishes them with it. On an object every value belongs to a language and the item's `locale` says which. A document is one page in one language, so an item written for it has no `locale`. `schema` and `html_tag` are read and filtered but not written. A `schema` block is named by a generated id and holds a JSON-LD document, which a request has no way to name a value in. Whether an integrator can be written is decided by its [integrator type](MetaData/10_Integrator.md#how-an-integrator-holds-its-data). Where documents have `hide_opendxp_default_seo_panel` set, `seoMetaData` replaces a page's own `title` and `description` fields. ### The write that is refused `open_graph` and `twitter_card` store the languages of a value together and can only let go of all of them at once. Dropping one language while others remain is refused, and nothing is written at all, not even the part that would have gone through. Remove every language, or overwrite the value instead. ### The suggestion this bundle brings Genius offers three example instructions in the chat and in the routine window. `SeoBlockProvider` adds one of its own, for classes that may have `seoMetaData` written and have two text fields to build a title out of. Nothing has to be configured for it. A project that does not want it names it in `content_crafter.yaml`, and one that wants different words keeps the shape and writes its own. ```yaml opendxp_content_crafter: suggestions: exclude: [seo_block] ``` The wording is `seo_bundle.content_crafter.suggestion.seo_block` in this bundle's own catalogue. ### Debug the field pipeline To see what the field pipeline made of an archetype, without a model call: ```bash php workbench/bin/explain.php fields --user=admin --arguments='{"domain":"object","type":"Product"}' ``` `AdvancedSeoExtension::prepend()` loads the integration, and only when the container has the `opendxp_content_crafter` extension. --- ## Changelog(Advanced-seo) ### 1.2.1 - [BUGFIX] A job log names why an SEO value could not be dropped in one language as a plain fact - [CHORE] Require Content Crafter 2.1.1 ### 1.2.0 - [CHORE] Require Content Crafter 2.1 for the Genius support - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [BUGFIX] Genius offers only the integrators a project enables. A disabled integrator broke the schema tools ### 1.1.1 - [BUGFIX] A stored schema block keeps its `localized` flag. A block that is not translated appears in the head and in the backend again ### 1.1.0 - [NEW FEATURE] Genius support: ask about SEO gaps in plain language and let it write [Read more](./docs/30_Genius.md) - [ENHANCEMENT] [MIGRATION] Element meta data is stored as one row per field and language instead of one serialized block [Read more](./docs/MetaData/10_Integrator.md#how-an-integrator-holds-its-data) - [BC BREAK] `ElementMetaData::getData()` and `setData()` no longer work, because there is no serialized block left to hand over. 1. Replace `$metaData->getData()` with `ElementMetaDataManagerInterface::getIntegratorData($metaData)`. It returns the same shape. 2. Replace `$metaData->setData($data)` with `ElementMetaDataManagerInterface::saveElementData()`. It takes the element type, the element id, the integrator name and the data. ### 1.0.5 - [BUGFIX] Always use full scope of allowed locales when rebuilding local value ### 1.0.4 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.3 - [ENHANCEMENT] Drop CoreShop support and add Ecommerce Bundle Support ### 1.0.2 - [CHORE] Remove deprecated migration version reference from Installer ### 1.0.1 - [CHORE] [MIGRATION] Remove old migration files and add cleanup migration to remove them from `migration_versions` - [CHORE] Refactor `ElementMetaData` to use `#[UniqueConstraint]` attribute ### 1.0.0 - [NEW FEATURE] Initial release - [BUGFIX] Fix asset paths [#1](https://github.com/open-dxp/advanced-seo-bundle/pull/1) - [CHORE] Fix tests [#2](https://github.com/open-dxp/advanced-seo-bundle/pull/2) - [CHORE] Adjust Test Setup [#4](https://github.com/open-dxp/advanced-seo-bundle/pull/4) - [CHORE] Enable auto-commit in PHP CS Fixer workflow [#6](https://github.com/open-dxp/advanced-seo-bundle/pull/6) --- ## Google Index Worker Update / Delete data in realtime via google index API. ### Configuration | Name | Default | Description |------|---------|------------| | `push_requests_per_day` | 200 |Set allowed push requests per day. This check is currently not available. | | `push_requests_per_minute` | 600 | Set allowed push requests per minute. This check is currently not available. | | `auth_config` | null | Set path to your auth config (mostly `config/opendxp/google-api-private-key.json`. | --- ## Integrators An integrator is one block of SEO metadata: a title and a description, an Open Graph set, a JSON-LD document. Each one brings its own backend panel and renders its own tags. - [Enable an integrator](#enable-an-integrator) - [Render as fieldset instead of tab](#render-as-fieldset-instead-of-tab) - [Available integrators](#available-integrators) - [How an integrator holds its data](#how-an-integrator-holds-its-data) - [Add an integrator type](#add-an-integrator-type) ### Enable an integrator ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: title_description - integrator_name: open_graph integrator_config: facebook_image_thumbnail: 'socialThumb' - integrator_name: html_tag - integrator_name: schema ``` ### Render as fieldset instead of tab ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: integrator_rendering_type: 'fieldset' ``` ### Available integrators - [Title & Description Integrator](./Integrator/10_TitleDescriptionIntegrator.md) - [Open Graph Integrator](./Integrator/11_OpenGraphIntegrator.md) - [Twitter Card Integrator](./Integrator/12_TwitterCardIntegrator.md) - [Schema Integrator](./Integrator/13_SchemaIntegrator.md) - [HTML Tag Integrator](./Integrator/14_HtmlTagIntegrator.md) ### How an integrator holds its data Every integrator uses its own shape. `title_description` keys its values by name, `open_graph` keeps a list of rows, `html_tag` a plain list of tags. An integrator type is what knows one of those shapes: it takes the block apart into single values and puts it back together. `seo_element_meta_data` holds one entry per element and integrator. The values hang off it in `seo_element_meta_data_value`: | column | holds | |---------------------------------|------------------------------------------------| | `field` | the name inside the block | | `locale` | the language, empty when the value has none | | `value` | the text | | `value_type` | `json` where the value is a structure | Empty values get no row. `NamedFieldsIntegratorType` adds the fields from `listWritableFields()` back when it rebuilds the block, so `title_description` always has both of its fields. An entry can have no values. The panel writes one when an editor clears a draft and saves, so the field shows empty instead of the published text. ### Add an integrator type An integrator another bundle registers falls to `UnwritableIntegratorType`, which passes its data on as one value per top level key and writes nothing. To read it in its own shape, or to write it, implement `IntegratorTypeInterface` and tag the service `seo.meta_data.integrator_type`. | method | answers | |---------------------------|--------------------------------------------------------------------| | `supports()` | which integrator this type is for | | `isWritable()` | whether a request may change it | | `canRemoveSingleLocale()` | whether one language can be taken off while the field keeps others | | `readValues()` | the block as single values | | `buildStoredData()` | those values as the block again | `readValues()` and `buildStoredData()` are the two directions of the same shape. What one takes apart, the other has to build, because there is no other copy of the data. Extend `AbstractIntegratorType` for the locale row handling and the two `false` defaults. `IntegratorTypeRegistry` takes the first type that claims an integrator, so a type for a subclass is tagged with a higher priority than the one for its parent. | type | claims | writable | |-----------------------------|----------------------------------------|------------------| | `NamedFieldsIntegratorType` | `title_description` | yes | | `NamedValuesIntegratorType` | `open_graph`, `twitter_card`, `schema` | all but `schema` | | `PlainListIntegratorType` | `html_tag` | no | | `UnwritableIntegratorType` | whatever no other type claims | no | --- ## Extractors This bundle comes with one pre-installed extractor: the `IntegratorExtractor`. This service will extract all data from your enabled integrators. Every extractor has two methods: #### supports($element) This method passes a various element (document/object). The extractor is able to decide if this element is valid for processing. #### updateMetaData($element, $locale, $seoMetadata) This method allows you to update the `SeoMetaData` object ### SeoMetaData Class | Name | Description | |------------------------------------------|-----------------------------------------------------------------------------------------------------------------| | `setMetaDescription` | Set meta description. | | `setTitle` | Set title. |`` | `setTitle` | Set title. | | `addExtraProperty`, `setExtraProperties` | Add a extra property. | | `addSchema` | Add a schema block ( `application/ld+json`). **Note!** No script tags are allowed here, only encoded json data! | | `addExtraName`, `setExtraNames` | Add a extra name meta field. | | `addExtraHttp`, `setExtraHttp` | Add a extra http meta field. | > **Note:** Extractors are prioritized services. > If another extractor supports your element too it could override your current definition. ### More Information - [Custom Extractor](./Extractor/10_CustomExtractor.md) --- ## SEO MetaData Middleware Sometimes an extractor may need some more tools to create meta data. For example, the [Schema Bundle](https://github.com/open-dxp/schema-bundle) allows you to use the fancy graph builder while creating schema blocks! ### Adding Middleware ```yaml # config/services.yaml services: App\Seo\Middleware\MyCustomAdapter: tags: - { name: seo.meta_data.middleware.adapter, identifier: my_custom_adapter } ``` ```php string = 'Important string!'; } public function getTaskArguments(): array { return [$this->string]; } public function onFinish(SeoMetaDataInterface $seoMetadata): void { // nothing to do by default // in some extended usages you may want to finalize and add some data to the SeoMetaData object after all extractors have been dispatched. } } ``` ### Usage In your extractor you could use it like this: ```php getMiddleware('my_custom_adapter'); $middleware->addTask(static function (SeoMetaDataInterface $seoMetadata, string $string) { $seoMetadata->setTitle($string); // output: "Important string" }); } } ``` --- ## Custom Extractor Integrating a custom extractor is very easy. ```yaml App\MetaData\Extractor\DescriptionExtractor: tags: - {name: seo.meta_data.extractor, identifier: my_object_description } ``` ```php setMetaDescription($element->getDescription()); } } ``` --- ## Third Party Extractors This Bundle comes with some pre configured extractors. ### Complexity These extractors will be enabled on cache build level. If any supported bundle isn't installed, no service will be included - so no overload here! ### Supported Bundles This is an accurate list of supported bundles! *** #### OpenDxp Ecommerce Bundle If the opendxp ecommerce bundle is installed, product/category name/short description and og data extractors will be added automatically. Disable them via `disable_default_extractors: true`. - Bundle: https://github.com/open-dxp/ecommerce-bundle - Object Types: `EcommerceProduct`, `EcommerceCategory` - Extractors: - Title & Description Extractor (`opendxp_ecommerce_title_description`) - OG Type, Title, Description and Image Extractor (`opendxp_ecommerce_og_tags`) ##### Configure Ecommerce Extractor ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: objects: enabled: true data_classes: - EcommerceProduct - EcommerceCategory ``` ##### Disable Default Ecommerce Extractor ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_provider: third_party: opendxp_ecommerce: disable_default_extractors: true ``` *** #### OpenDxp News Bundle > Pro Tip: Hide the "metaTitle" and "metaDescription" fields in "NewsEntry" and "NewsCategory" (category SEO fields are unused fields by default) class since you should use the SEO-Tab only! > If you're going to delete them from your entry class definition (Only on new installations otherwise you'll lose your data!), you need to add these methods to an extended class first, otherwise the news bundle will throw an exception! - Bundle: https://github.com/open-dxp/news-bundle - Object Types: `NewsEntry` - Extractors: - Entry Meta Extractor (`opendxp_news_entry_meta`, still using the `NewsBundle\Generator` Service to generate metadata and keep bc) ##### Configure News Extractor ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: objects: enabled: true data_classes: - NewsEntry ``` ##### Disable Default News Extractor ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_provider: third_party: opendxp_news: disable_default_extractors: true ``` --- ## Title & Description This Integrator allows you to define title and description for a given document/object. It also renders a live preview (Google SERP Snippet). ### Configuration ## Default Configuration This is the most basic configuration you need to enable this integrator. ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: title_description ``` --- ## Open Graph Integrator This Integrator allows you to define Open Graph meta tags. It also renders a live preview (Facebook). ### Notes You may have noticed, that there is no `og:url` in your property selection. This property gets appended automatically. Make sure your [link generators](https://opendxp.io/docs/5.x/Development_Documentation/Objects/Object_Classes/Class_Settings/Link_Generator.html) for objects are up and running! ### Configuration ## Default Configuration This is the most basic configuration you need to enable this integrator. ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: open_graph integrator_config: facebook_image_thumbnail: 'socialThumb' ``` ### Extended Configuration Add some more `types`, `properties` and `presets` with this configuration: ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: open_graph integrator_config: facebook_image_thumbnail: 'socialThumb' types: - ['my_type', 'my_type'] properties: - ['og:test', 'og:test', true] # 3. argument: allow export to xliff translation presets: - label: 'My Preset' icon_class: 'opendxp_icon_user' fields: - property: 'og:type' content: 'article' - property: 'og:description' content: null - property: 'og:title' content: null ``` --- ## Twitter Card Integrator This Integrator allows you to define meta tags for twitter cards. It also renders a live preview. ### Configuration ## Default Configuration This is the most basic configuration you need to enable this integrator. ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: twitter_card integrator_config: twitter_image_thumbnail: 'socialThumb' ``` ### Extended Configuration Add some more `types`, `properties` and with this configuration: ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: twitter_card integrator_config: twitter_image_thumbnail: 'socialThumb' types: - ['my_type', 'my_type'] properties: - ['twitter:definition', 'twitter:definition', true] # 3. argument: allow export to xliff translation ``` --- ## Schema Integrator ![Schema field with a JSON-LD product block and the script tag it adds to the page head](../../img/schema_blocks.png) The Schema Integrator is quite simple. Just add one or more valid JSON-LD blocks. The snippet needs to start with ``. Otherwise, it won't get stored. ### Note! If a dynamic extractor adds JSON-LD data to the given element, the schema integrator is not able to replace the values! That said, you need to take extra care implementing additional schema blocks - this could lead to dangerous duplicate entries otherwise! --- ## HTML Tag Integrator This integrator is not recommend but required, if you're going to integrate this bundle within a existing opendxp installation. It allows you to add raw html tags to your document head. ### Configuration ## Default Configuration This is the most basic configuration you need to enable this integrator. ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: html_tag ``` ### Extended Configuration ```yaml opendxp_advanced_seo: meta_data_configuration: meta_data_integrator: enabled_integrator: - integrator_name: html_tag integrator_config: presets_only_mode: false presets: - label: 'Robots No-Index' value: '' icon_class: 'opendxp_icon_stop' - label: 'Secret Meta-Link' value: '' ``` #### presets If defined, the user is able to add predefined presets. They can only be added and not edited! ![Two presets in the configuration and the tags they add](../../img/html_tag_presets.png) #### presets_only_mode If set to `true`, the user is not able to add custom tags but only presets: ![Setting presets_only_mode to false and true, with the matching buttons](../../img/html_tag_presets_only.png) --- ## Migrating to OpenDXP(Advanced-seo) ### Migrate from `dachcom-digital/seo:3.x` to `open-dxp/advanced-seo-bundle:~1.0.0` - Configuration name changed from `seo` to `opendxp_advanced_seo` - [BC Break]: CoreShop Support dropped. Use OpenDxp Ecommerce Bundle instead. [Read more](MetaData/Extractor/11_ThirdPartyExtractors.md#opendxp-ecommerce-bundle) - [BC Break]: News Support dropped. Use OpenDxp News Bundle instead. [Read more](MetaData/Extractor/11_ThirdPartyExtractors.md#opendxp-news-bundle) --- ## Advanced SEO Bundle The last SEO Bundle for opendxp you'll ever need! - Create title, description and meta tags (OG-Tags, Twitter-Cards) for documents **and** objects! - Shipped with a save and user-friendly editor with multi locale support! - Enjoy live previews of each social channel! - Super smooth and simple PHP-API to update meta information of documents or objects! - Submit content data to search engines like Google, Bing, DuckDuckGo in real time! - Fully backwards compatible if you're going to install this bundle within an existing opendxp instance! ### Documents ![SEO tab of a document with title, description and a Google preview](./docs/img/seo_documents.png) ### Objects ![Open Graph editor of an object with localized values and a Facebook preview](./docs/img/seo_objects.png) ### Objects | Tabbed View ![SEO tab with one tab per integrator and a Twitter card preview](./docs/img/seo_tabs.png) #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `^7.4` | 2025 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/advanced-seo-bundle" : "~1.1.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\AdvancedSeoBundle\OpenDxpAdvancedSeoBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpAdvancedSeoBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\AdvancedSeoBundle'` ### Usage This Bundle needs some preparation. Please check out the [Setup && Overview](docs/00_Setup.md) guide first. ### Further Information - [Setup & Overview](docs/00_Setup.md) - [Metadata](./docs/10_MetaData.md) [Set Title, Description, ...] - [Integrators](./docs/MetaData/10_Integrator.md) - [Title & Description Integrator](./docs/MetaData/Integrator/10_TitleDescriptionIntegrator.md) - [Open Graph Integrator](./docs/MetaData/Integrator/11_OpenGraphIntegrator.md) - [Twitter Card Integrator](./docs/MetaData/Integrator/12_TwitterCardIntegrator.md) - [Schema Integrator](./docs/MetaData/Integrator/13_SchemaIntegrator.md) - [HTML-Tag Integrator](./docs/MetaData/Integrator/14_HtmlTagIntegrator.md) - [Extractors](./docs/MetaData/20_Extractors.md) - [Custom Extractor](./docs/MetaData/Extractor/10_CustomExtractor.md) - [Third Party Extractors](./docs/MetaData/Extractor/11_ThirdPartyExtractors.md) - [Middleware](docs/MetaData/30_Middleware.md) - [Index Notification](docs/20_IndexNotification.md) [Push Data to Google Index] - [Google Worker](docs/IndexNotification/Worker/01_GoogleWorker.md) [Push Data to Google Index] - [Genius](docs/30_Genius.md) [Ask "which pages have a title but no description" and get an answer, optional] ### Supported 3rd Party Bundles - Use [open-dxp/jobs-bundle](https://github.com/open-dxp/jobs-bundle) to push job data via google index! - Use [open-dxp/schema-bundle](https://github.com/open-dxp/schema-bundle) to generate schema blocks via PHP API with ease! ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Changelog(Canto-assets) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [BUGFIX] Update CantoController.php [#4](https://github.com/open-dxp/canto-assets-bundle/pull/4) ### 1.0.1 - [ENHANCEMENT] Add php 8.5 support [#3](https://github.com/open-dxp/canto-assets-bundle/pull/3) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix workflows [#1](https://github.com/open-dxp/canto-assets-bundle/pull/1) - [CHORE] Update helper-function to static replacement [#2](https://github.com/open-dxp/canto-assets-bundle/pull/2) --- ## Canto Assets Bundle This bundle adds an integration to the Canto DAM directly in OpenDXP either as a DataObject data type or as a document editable or areabrick #### Setup - Execute: `$ composer require open-dxp/canto-assets-bundle` - Extend the `config/bundles.php` file: ```php return [ // ... OpenDxp\Bundle\CantoAssetsBundle\OpenDxpCantoAssetsBundle::class => ['all' => true], ]; ``` Create the following configuration: ```yaml # config/packages/opendxp_canto_assets.yaml opendxp_canto_assets: environment: 'canto.de' appId: '' secret: '' sitename: '' ``` ##### Access Token The access token is fetched by a maintenance task (refresh_access_token_task). In order to have a valid token, make sure to run maintenance at least once: `$ bin/console opendxp:maintenance -j refresh_access_token_task` ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Rules Decisions that hold across the whole bundle: which language is used, how things are named to an editor, which user a run acts as, and which permission is checked. Every other page links here rather than restating them. - [Languages](#languages) - [Backend language and content languages](#backend-language-and-content-languages) - [Default language](#default-language) - [An empty language stays empty](#an-empty-language-stays-empty) - [Default translation catalogue](#default-translation-catalogue) - [Name a language in the request](#name-a-language-in-the-request) - [Labels](#labels) - [What the answer leaves out](#what-the-answer-leaves-out) - [Acting user](#acting-user) - [Permission and visibility](#permission-and-visibility) ### Languages #### Backend language and content languages An installation carries two sets of languages. They are separate settings, and neither is worked out from the other. | set | held in | carries | |-----------------------------------|-----------------------------------------------------------------------------------------|---------------------------------------------------------------------| | Backend language, the BE locale | `users.language`, one code per user | The language a user is spoken to in. Genius chats and answers in it | | Content languages, the FE locales | The website languages of the installation, ordered per user in `users.contentLanguages` | The languages content is written in. They hold the localized fields | The first of a user's content languages is their preferred content language. ``` users.language = de users.contentLanguages = en,de,fr,it ``` This user is spoken to in German while their preferred content language is English. Nothing about a language is derived from the other setting. `UserLanguages` answers both. `conversation()` gives the backend language, `listContent()` the content languages in the user's own order, and `preferredContent()` the first of them. The chat and every prompt use *conversation*. A query and a write use *content*. #### Default language | what happens | in which language | |-----------------------------------------------------------|--------------------------------| | Genius answers in the chat | The backend language | | A query reads or filters a localized field | The preferred content language | | A step writes localized values and names no `locales` | The preferred content language | | A step selects its elements and writes no language | The preferred content language | | An item condition on a translated field names no language | The preferred content language | | A tool run at the workbench names no `locale` | The preferred content language | A step selects in the first of the languages it writes. A step that writes none still selects in one, and that one is the preferred content language. Two kinds of step write none: an operation over rows that hold no language is offered no `locales` at all, and a step whose values carry their own languages per entry names none either, see [Writing](20_Writing.md#a-translated-field-inside-an-item). Each of these is a setting of the acting user, so two people running the same routine fill different columns. The language list a query schema and a plan schema offer is the website languages of the installation in the acting user's own order, preferred first. A query that arrives without a language is given the preferred content language in `QueryResultBuilder::build()`, before anything filters, sorts or reads. Nothing below that point sees a query with no language, and nothing reads a localized field in every language at once. A plan writes the language into the summary a person approves, so the choice can be turned down before anything is saved. ``` 1 Changes 11 × Bike [German] ``` Where the rows of a query hold a value in a language other than the one read, the answer says which, see [What the answer leaves out](#what-the-answer-leaves-out). #### An empty language stays empty An installation can name a fallback language per content language, and a website then renders that one where a field is empty. Genius never reads it. A field with nothing in French is empty here, the way the backend shows it, even on a page whose visitors see the German text. Two things follow. *Which products have no French description* answers the question that was asked, rather than finding none because every read came back filled. And a step that reads one language to write another reads what is really in the source language, instead of the fallback language being handed back and written into itself. Where the source language is empty, a `$transform` leaves the element alone and a `$generate` is handed nothing, see [Writing](20_Writing.md#value-forms). #### Default translation catalogue A question about translations that does not say which catalogue reads `messages`, the texts a website renders. The backend catalogue is read only where the request is about the backend. See [Translations](12_Translations.md). #### Name a language in the request Say the language in the request to read or write another one. *Which products have no French description* names French, and the default no longer applies. A plan step takes a list of languages, so one step writes any number of them, see [Writing](20_Writing.md). ### Labels Genius names a class, a field, an object brick and a field collection by its label and never by its technical name. A label is the title on the definition, put through the admin translation in the user's backend language. Where the definition carries no title, or the title has no translation entry, the label falls back to the technical name, and the model then says `MySpecialClass` to an editor. | what is named | its label is | |--------------------------------------|--------------------------------------------------| | A data object class | The class definition title, else the class name | | A field | The field definition title, else the field name | | An object brick, a field collection | The definition title, else its key | | A document, an asset | The type name, translated | ``` Bike title set, entry present -> "Bicycle" MySpecialClass no entry -> "MySpecialClass" ``` Give every class, field, object brick and field collection a title, and give that title an admin translation in each backend language in use. Nothing in the code stands in for a missing title. A class whose label is its own technical name is offered last in the suggestions of the chat and of the routine window, behind every class that has one, so a suggestion says a technical name only when nothing else is left, see [Suggestions](01_Configuration.md#suggestions). ### What the answer leaves out A query reads one language, leaves variants out, and reads a value an element borrows from a parent as if it held it. Each of those can hide a row somebody expected. In these cases the answer adds a hint. | the case | the answer carries | |----------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------| | No rows were found and the same filter matches in another language | How many rows that language holds, and to ask again with it | | Rows were found and a field that was read is blank in the language read | How many of those rows hold the field in another language, and which | | Variants were left out and the same filter matches some | How many, and how to ask for them. On every answer, a count-only and a too-long one included | | A step's filter finds nothing in the language the step writes | How many the same filter matches per other language. This one is a refusal | | Rows were found and some of them show a field only because a parent holds it | How many, and to ask again with `{"inheritance": "own"}` on that field | | Nothing was found, and the same filter would match if a field were read as what the element holds itself | How many, and the same way to ask | | A grouped query found more groups than the limit holds | How many groups there are in all, and to ask again with a higher limit | | A field holds a list of more than 20 rows | The first 20, how many there are in all, and the call that returns the next ones | A filter naming the value of a translated field picks a different set per language, which is why a step's filter is refused rather than reported. A row of a query that named fields carries `inherited` where one of them is borrowed, so a filter, a row and the answer all report inheritance the same way, see [Filters](11_Query_Filters.md#inherited-values). A plan summary says both, each as a line under the step it belongs to. ``` Variants left out, 27 more would be included 11 of these show "Image" only because a parent object holds it. Writing here gives them one of their own. ``` ### Acting user Every read and every write happens on behalf of one OpenDXP user. That user carries the permissions, the workspace rules and the two language settings above. | where it runs | the acting user | |---------------------------|----------------------------------------------------| | The chat | The logged-in user | | A job | The user who started the routine | | An accepted review row | The user who submitted the job, never the reviewer | | The workbench | The user `--user` names, which is required | A reviewer decides what lands without lending their own rights to it, so reviewing a job never needs more rights than running one. A right taken away in the meantime refuses the accept. A job whose user no longer exists is canceled rather than run as somebody else, and the job log says so. ### Permission and visibility A permission decides whether an action can be reached at all. Which elements the answer may contain is decided separately, per element, by the same OpenDXP workspace rules that apply to a person. Only the workspace right `view` decides what an answer may contain. `list` says that an element appears in a tree, and there is no tree here. Every question reads a value off an element, so an element the user may not open is left out of the answer even where the tree would show it. A relation belongs to the element that holds it, the same as in the backend. A target the user may not view stays in the answer with its element type and its id only: ```json {"elementType": "object", "id": 4711, "withheld": true} ``` This holds for relations, dependencies and properties. An image, a video and a link show only the id of their target in any case. A filter counts such a target and matches it by its id. A condition on another field of the target never matches it. When Genius writes the field, such a target stays unless the plan removes it. A `$replace` keeps it when it names its id. Genius never links a target the user may not view. The job stops at that element instead. Writing checks a second right on the same element. A missing right is reported as a refusal, not passed over in silence. Writing a value checks `save`, or `publish` on an asset, because the asset workspace has no `save` column. Publishing, unpublishing, renaming, moving and deleting each check their own columns in addition, see [Writing](20_Writing.md#rename-move-publish-or-delete-an-element). Which workspace row answers for one element, in this order: 1. The workspace closest to the element, meaning the one with the longest matching path. 2. On that path, the user's own row. Only where they carry none do their roles answer, and among the roles a grant beats a denial. 3. No workspace above the element is a no. That is the order `Element\Dao::isAllowed()` reads, so a denial in the tree is a denial in an answer. An administrator is not restricted. > [!TIP] > A count of zero can therefore mean the user sees none of them rather than that none match. Check a > surprising zero against a second user before looking for the bug elsewhere. The permissions themselves are listed in [Configuration](01_Configuration.md#permissions). --- ## Configuration This page lists every key of `content_crafter.yaml`, every permission and what it grants, and the two ways to keep a field away from the model. Which model does the work is not set here. It is assigned in the backend, see [Engines](02_Engines.md). - [`content_crafter.yaml`](#content_crafteryaml) - [Skills](#skills) - [Suggestions](#suggestions) - [Protected fields](#protected-fields) - [HTML sanitizing](#html-sanitizing) - [Chat settings](#chat-settings) - [Streaming](#streaming) - [Permissions](#permissions) ### `content_crafter.yaml` Every key has a default. A working installation needs none of them. ```yaml # config/packages/content_crafter.yaml opendxp_content_crafter: debug: false explorer: inline_display_threshold: 5 limits: max_tool_rounds: 25 max_turn_seconds: 120 max_plan_refusals: 3 skills: [] streaming: event_padding: 65536 suggestions: exclude: [] add: [] field: write_protected: [] read_protected: [] jobs: log_expiration_days: 30 notifications: review_email_path: null persistence: doctrine: entity_manager: 'default' ``` | key | default | what it does | |---------------------------------------|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `debug` | `false` | Adds a `debugTrace` of every model and tool call to each chat response. Request-scoped, never stored. It is also what `--breakdown` writes out at the workbench, see [Debugging](50_Debugging.md). | | `explorer.inline_display_threshold` | `5` | Row count up to which the model sees the rows and the chat shows them. Above it the model gets the count only, and the rows open in Genius Explorer. `0` means it never sees rows. | | `limits.max_tool_rounds` | `25` | Rounds of tool calls one turn may make before it is stopped, in a chat and while a routine works out its plan. | | `limits.max_turn_seconds` | `120` | Seconds one turn may work before it is stopped. Rounds alone allow a turn that stays inside them and still outlasts the person waiting for it. | | `limits.max_plan_refusals` | `3` | How many refusals in a row may go by without the plan getting closer before the turn gives up on it. A refusal that takes one of the standing problems away resets the count, so a turn that keeps making headway is not cut off at three. Nothing is written, and the last refusal is what the person is told. Where it has nothing to say to them, they are asked to word the request differently. | | `skills` | `[]` | Skill files Genius may read, see [Skills](#skills). | | `streaming.event_padding` | `65536` | Bytes of filler in front of every streamed event, see [Streaming](#streaming). | | `suggestions.exclude` | `[]` | Keys of the suggestions this installation does not offer, see [Suggestions](#suggestions). | | `suggestions.add` | `[]` | Suggestions of your own, on top of the shipped ones, see [Suggestions](#suggestions). | | `field.write_protected` | `[]` | Fields nothing may write, see [Protected fields](#protected-fields). | | `field.read_protected` | `[]` | Fields nothing may read, see [Protected fields](#protected-fields). | | `jobs.log_expiration_days` | `30` | How many days a job keeps its log lines. The maintenance task `content_crafter_job_logs` deletes the older ones, see [Jobs](20_Writing.md#jobs) and [Maintenance](60_Maintenance.md#delete-expired-job-log-lines). | | `notifications.review_email_path` | `null` | Path of the email document used for the reviewer mail. There is no stock template: while this is unset, no reviewer mail is sent, see [Review](30_Review.md#notifications) and [Maintenance](60_Maintenance.md#notify-reviewers). | | `persistence.doctrine.entity_manager` | `default` | Entity manager that holds the bundle's own entities. | Every round of a turn resends the whole history and the whole tool catalog, so a model that never reaches an answer costs the same again each round. Rounds and refusals count what a turn does. `max_turn_seconds` bounds how long it takes. `max_turn_seconds` holds inside the call that writes a plan as well. It is read per part as the answer streams in, so a call that runs past the turn's time ends there rather than running to the model's own ceiling. How long the model thinks is a setting of the engine, written as `{"reasoning": {"effort": "high"}}` under **Content Crafter > Crafter-Settings > Engines**, and so is `max_output_tokens`. Neither is set here. `max_turn_seconds` is also how long the connection to the model may stay silent. That limit sits in the HTTP client and is counted from the last part that arrived, so a stream that keeps sending is never touched by it. Left unset it would be PHP's `default_socket_timeout`, so the bundle sets it to `max_turn_seconds` instead. There is no second setting for it. ### Skills A skill is a written procedure in Markdown. Genius reads its name and description every turn and opens the body when the request calls for it, so the order of the steps does not have to be worked out again each turn. ```yaml opendxp_content_crafter: skills: - '%kernel.project_dir%/config/content_crafter/skills/dealer-stock/SKILL.md' ``` The file starts with a `---` front matter block naming the skill, describing when to use it, and listing the tools the body refers to. ```markdown --- name: dealer-stock description: > Answers which dealers stock a bike, and how many dealers a region has. tools: - count_dealers_in_region - query_objects needs: - count_dealers_in_region --- ## Step 1 Ask for the region code if the request does not name one. ``` `description` is required. `name` falls back to the name of the directory the file sits in. | key | means | |---------|-----------------------------------------------------------------------------------------------------------------------------------------------| | `tools` | Every tool the body tells the model to call. Opening the skill opens them, so the model does not load each one before it can follow the steps | | `needs` | The ones the procedure is worthless without. A user who may not call one of these is not offered the skill at all | | `operations` | The plan operations this body explains. A turn that announces one of them is given this skill in the call that writes the plan | Name a tool the body uses in `tools`, and among those the ones it cannot go on without in `needs`. A schema tool opens the query tool of its domain beside itself, so `get_object_query_schema` in `tools` also covers a body that names `query_objects`. `operations` takes effect without anybody opening the skill. Name an operation only where the body says how to write it. Every skill that names it is read in full by the call that writes the plan. A skill holds judgment: which tool to call first, what a request really asks for, and when there is no plan. Facts belong to the tools, the schemas and the plan grammar. Genius reads them when it uses them. A skill that repeats a fact is wrong as soon as the fact changes. > [!NOTE] > Nothing here is fatal. A file that is not there, one without front matter, and one naming a tool > that does not exist are each logged as a warning and skipped. A tool the body names that opening > the skill does not open is logged too, and stays closed. Where two files give the same skill name, > the later one wins. ```bash php workbench/bin/explain.php skills --user=admin ``` It lists every skill that was read, with its `tools`, its `needs`, its `operations`, the `problem` that keeps it out, the `unmetNeeds` this user has no permission for, and whether it is `offered` to them, see [Debugging](50_Debugging.md). ### Suggestions The chat and the routine window both offer three example instructions. They are put together from what this installation holds, without asking a model. A wording with slots in it fits a class as soon as every slot can be filled from that class. The three that are offered are drawn from everything that fits, so the same examples do not come up every time. A user who may not change objects is offered none. Nine wordings ship with the bundle. Each is named after the shape of class it fits, and each fills its own slots. | key | fits a class that | slots | |-----------------------------------|-----------------------------------------------------------------------------------------------------------|-------------------------------------------------------------| | `translated_text_field` | has a translated, writable text field, and there is more than one content language | `{field}`, `{language}` | | `two_text_fields` | has two writable text fields | `{field}`, `{second_field}` | | `long_text_field` | has a writable textarea or WYSIWYG field | `{field}` | | `writable_tags` | may have tags written, and there is a tag to name | `{tag}` | | `writable_properties` | may have properties written, and there is a predefined property of type bool that objects may carry | `{property}` | | `asset_relation` | has a writable relation that takes images, and there is an asset folder to name | `{field}`, `{folder}` | | `container_with_translated_field` | has a fieldcollection with a translated, writable text field, and there is more than one content language | `{container}`, `{field}`, `{language}`, `{second_language}` | | `brick_with_writable_field` | has an objectbrick with a writable text field | `{brick}`, `{field}` | | `container_with_relation` | has a fieldcollection with a relation field | `{container}`, `{field}` | `{class}` is filled for every wording, with the label of the class. A text field is one an editor types prose into, meaning an input, a textarea or a WYSIWYG. A select, a link and a video are held as a string too and are not offered. The wordings themselves are translation keys, so they are offered in the backend language of whoever asks, and every slot is filled with a label rather than a technical name. The nine above are under `content_crafter.suggestions.`. A wording another bundle brings sits under a prefix of that bundle, in a catalogue of its own. ```yaml opendxp_content_crafter: suggestions: exclude: [long_text_field] add: - when: writable_tags text: 'Tag every {class} that has no tag yet as Season 2026.' ``` `exclude` drops a wording by its key. `add` puts wordings of your own beside the ones that ship. `when` names one of the keys above and decides where the wording is offered, `text` is the wording. Use the slots of that key and `{class}`. A placeholder that is not among them stays in the text as you wrote it. A `when` that names no known key stops the container from building, and the message lists the keys this installation does have. Another bundle can bring a wording of its own along with the shape it fits, see [Add a Suggestion](extending/Suggestions.md). Its key then works in `exclude` and `when` like any other. A suggestion names classes by their label, see [Rules](00_Rules.md#labels). ### Protected fields Two keys decide what may be touched at all, whatever the class definition allows. Both are keyed by class and list field names. The class is a DataObject class name, or the full class name of any other archetype a query domain describes. Both keys take the class by its short name or in full. ```yaml opendxp_content_crafter: field: write_protected: Bike: ['onHand', 'onOrder', 'isTracked'] read_protected: Dealer: ['apiToken', 'internalNote'] ``` `write_protected` keeps the read side of a field and removes it from everything that writes: the direct tools, the write plan, and the schema, which stops offering it. Use it for figures another system owns, such as stock levels or prices maintained by an ERP, where a wrong value looks entirely plausible. `read_protected` removes the field from the schema altogether. Nothing reads it, filters on it, sorts by it, or shows it in a grid. Use it for what sits in a content field without being content, such as a token, a key, or a note about a person. Password and encrypted fields are already excluded and need no entry. > [!TIP] > A class definition field marked *not editable* in the class editor is never written either, and > needs no entry here. Use the class editor where the field should be read-only for people too, and > `write_protected` only where a person may still change it by hand. A bundle protects its own fields in code instead, by implementing `WriteProtectionInterface` or `ReadProtectionInterface` and returning the same shape, class name to field names. What a bundle contributes and what is configured here are merged, so neither can undo the other. ```php final class BikeStockWriteProtection implements WriteProtectionInterface { private const array STOCK_FIELDS = ['onHand', 'onOrder', 'isTracked']; public function listUnwritableFields(): array { return array_fill_keys($this->bikeClassNames, self::STOCK_FIELDS); } } ``` Which class holds the bikes is a project decision, so the class names come from a container parameter rather than standing in the code. ### HTML sanitizing The sanitizer that runs when a document saves throws away every element it does not know, together with the text inside it. Two lists decide what survives. ```yaml framework: html_sanitizer: sanitizers: opendxp.wysiwyg_sanitizer: # kept as they are, on top of what OpenDXP already allows allow_elements: pre: 'class' code: 'class' # tag removed, text kept block_elements: - section - article - figure - figcaption - details - summary ``` `allow_elements` merges with the OpenDXP list. `block_elements` is empty in both Symfony and OpenDXP, so that list is yours alone. An element in neither list loses its text. `script` and `style` belong in neither, so their content keeps being thrown away. Genius reads `allow_elements` at runtime and tells the model which tags survive, so the list you configure is the list it writes against. ### Chat settings **Content Crafter > Crafter-Settings > Genius Settings** holds the settings an administrator changes without a deployment. | setting | what it does | |---------------------|---------------------------------------------------------------------------------------------------| | History strategy | *Token window* drops older messages once the budget is reached. *Whole history* sends everything. | | Max. history tokens | Budget for the token window, default 100000. The current message is never dropped. | | Selection actions | Which action appears when an editor selects text in the backend, and which engine answers it. | ### Streaming While a turn is running, the chat says what it is doing: which tool it opened, when it starts writing a plan, when it is waiting. Those notices travel as [server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html) and appear in the thinking bubble. The answer itself follows at the end, in one piece. This works on most servers without setting anything up. Web servers hold a small response back until more of it has accumulated, so every notice is padded until it is big enough to be passed on right away. The padding is a comment line, which every reader of a stream drops. ```yaml opendxp_content_crafter: streaming: event_padding: 65536 ``` Where the thinking bubble stays empty until the answer appears, double the value until it fills: `131072`, then `262144`. Keep the first value that works. Set it to `0` where the server passes events on by itself: nginx with `fastcgi_buffering off`, or Apache with `flushpackets=on` on the PHP-FPM proxy. ### Permissions A fresh installation grants none of these. Assign them under **Settings > Users**. | permission | grants | |----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------| | `opendxp_content_crafter` | The Content Crafter menu. Everything else needs this too. | | `opendxp_content_crafter_genius` | The Genius chat. | | `opendxp_content_crafter_genius_settings` | The Genius settings page. | | `opendxp_content_crafter_genius_selection_actions` | Selection actions on text in the backend. | | `opendxp_content_crafter_jobs` | Every job, the job list, and continuing, cancelling and deleting a job. Without it a user reads only the jobs they started. | | `opendxp_content_crafter_routines` | Seeing routines. | | `opendxp_content_crafter_routines_edit` | Creating and changing routines. | | `opendxp_content_crafter_routines_delete` | Deleting routines. | | `opendxp_content_crafter_routine_from_chat` | Letting Genius build and submit a plan. | | `opendxp_content_crafter_prompts` | Seeing generative prompts. | | `opendxp_content_crafter_prompts_edit` | Creating and changing generative prompts. | | `opendxp_content_crafter_prompts_delete` | Deleting generative prompts. | | `opendxp_content_crafter_execute_update` | Running a job that changes existing elements. | | `opendxp_content_crafter_execute_create` | Running a job that creates elements. | | `opendxp_content_crafter_write_without_review` | Running a job with no workflow while workflows are active, and building a plan a review would not allow, see [Review](30_Review.md). | | `opendxp_content_crafter_critact_publish` | Publishing and unpublishing an element from a plan, see [Writing](20_Writing.md#rename-move-publish-or-delete-an-element). | | `opendxp_content_crafter_critact_rename` | Renaming an element from a plan. | | `opendxp_content_crafter_critact_move` | Moving an element from a plan. | | `opendxp_content_crafter_critact_delete` | Deleting an element from a plan, together with everything below it. | | `opendxp_content_crafter_audit` | Reading the audit log those actions are written to. | | `opendxp_content_crafter_audit_delete` | Deleting entries from the audit log. | | `opendxp_content_crafter_workflow` | The workflow list. | | `opendxp_content_crafter_workflow_review` | My Reviews, and deciding what is waiting. | | `opendxp_content_crafter_settings` | Crafter-Settings. | | `opendxp_content_crafter_settings_engines` | Assigning models to roles. | Every tool checks the permission a human editor would need for that action. Which elements the answer may then contain is a separate decision, see [Rules](00_Rules.md#permission-and-visibility). --- ## Engines An agent is a platform and a model under a name. Each of the seven roles below points at an agent. Both are set under **Content Crafter > Crafter-Settings > Engines**, which needs the permission `opendxp_content_crafter_settings_engines`. Which platforms and models exist comes from `ai.yaml`. Which of them does what is decided here, so swapping a model needs no deployment. - [Roles](#roles) - [Who translates](#who-translates) - [Which models a role offers](#which-models-a-role-offers) - [Build an agent and assign it](#build-an-agent-and-assign-it) - [Choose a model per role](#choose-a-model-per-role) ### Roles | role | does | falls back to | |------------|-------------------------------------------------------------|--------------------------------------| | Assistant | Drives the chat and works plans out. | nothing, and nothing runs without it | | Content | Writes the text a job puts into fields. | Assistant | | Utility | Small side jobs such as naming a conversation. | Assistant | | Vision | Reads images, in a chat and as input for a generated value. | Assistant | | Image | Makes images. | nothing | | Audio | Makes audio. | nothing | | Translator | Carries text from one language into another. | nothing | A role with no agent of its own is answered by its fallback. A role with neither cannot be used, and asking for it fails by name: ``` No agent is set for image. Pick one under Content Crafter > Crafter-Settings > Engines. ``` > [!IMPORTANT] > A plan that asks for a generated image while the Image role is unassigned is refused when the plan > is built, not when the job runs. The same holds for audio and for a translation. Nothing gets halfway through a job and > then stops. Vision reads a file. It is asked for the asset type `image` and for no other, so a generated value whose input is a PDF or a video has no engine to read it and is refused. No model is ever sent the original file. An image goes as its `contentCrafterPreview` thumbnail, which fits it into 1536 by 1536 pixels as WEBP at quality 85 and leaves a smaller image at its own size. The thumbnail is written when the bundle is installed and when an existing installation migrates, and one that is already there is left alone, so its size and format can be changed under **Settings > Thumbnails > Image Thumbnails**. An image whose preview cannot be made is refused rather than read as empty, and the asset log says why. ### Who translates The Translator role says which *model* translates. Which *translator* runs is a second setting on the same page, because a translator need not be a model at all: a bundle can register one that talks to an outside service instead. | translator | is | |------------|------------------------------------------------------------------| | AI model | The one this bundle brings. It asks the Translator role. | A plan may name another one under `with`, and where it names none this setting answers. With only one translator installed there is nothing to pick, `with` is left out of the plan grammar, and the setting is there to be read rather than changed. Nothing set means the model translator. Installing a bundle that registers a second one changes nothing until somebody picks it here: having the choice is not the same as having made it. ### Which models a role offers Each role lists only the models whose platform declares a matching capability. | role | capability | |------------------------------|-----------------------------------------------------| | Assistant | `TOOL_CALLING` | | Content, Utility, Translator | `OUTPUT_TEXT` | | Vision | `INPUT_IMAGE` | | Image | `OUTPUT_IMAGE`, `TEXT_TO_IMAGE` or `IMAGE_TO_IMAGE` | | Audio | `OUTPUT_AUDIO` or `TEXT_TO_SPEECH` | A model missing from a role declares no capability that fits. Platforms word the same ability differently, so a model qualifies through any one of the capabilities listed for its role. ### Build an agent and assign it The settings page has two parts. *Agents you built* is a list of agents, each with a name, a platform, a model and a JSON field of options. *Agent assignment* is one field per role. It offers the agents whose model can do that role's job and nothing else, see [Which models a role offers](#which-models-a-role-offers). Build the agent once and point as many roles at it as you like. A role points at an agent by its name, so renaming an agent leaves the role unassigned rather than pointing at something else. The options are passed to the platform with every call of that agent, for example a temperature, a reasoning effort or a `max_output_tokens`. What is accepted depends on the platform, not on this bundle. The page refuses invalid JSON on save, and so does the agent when something uses it. > [!NOTE] > Each role reads the platform, the model and the options of its agent rather than an assembled > agent. The chat then builds its own around them, with the system messages, the tool box and the > permission filter. A selection action is handed an agent of the platform and the model alone, see > [Add a selection action](extending/Chat.md#add-a-selection-action). ### Choose a model per role The Assistant role drives every turn, and the whole tool catalog goes with each round. The Content role is called once per value a job writes, which is where the volume is. > [!TIP] > Writing one field of forty thousand elements is forty thousand calls on the Content model and none > on the Assistant one. Spend on Assistant for a chat that has to reason, and on Content only where > the written text itself has to be good. --- ## Asking Genius is a chat that sits in the backend and answers questions about your own content. It writes a real query against your classes, follows relations and reads the language you ask about. On this page you will open the chat, ask your first question, narrow it down, and open the answer as a grid. Nothing on this page changes any content, so there is no approval to wait for and nothing to undo. Changing content comes later, in [Writing](20_Writing.md). The examples use a `Bike` class with the fields `name`, `frameSize`, `color`, `weight`, `gears`, `electric`, `description` and `image`, plus a field collection `accessories` where each entry has a `name` and a `price`. Yours will have different fields. The questions work the same way. ### Before you start You need the permission `opendxp_content_crafter_genius` and a model assigned to the Assistant role. If the chat answers that no agent is set, that role is still empty, see [Engines](02_Engines.md). ### Ask your first question Open the chat panel. It opens from anywhere in the backend, and you can dock it into the layout or float it as a window. Type a question the way you would say it out loud: ``` Which bikes have no image? ``` Genius reads your classes, works out that `Bike` is the class you mean and `image` the field, and answers with the bikes that have none. You did not name the class, the field or a filter. Use the labels you see in the backend rather than technical field names, and let Genius find them. > [!TIP] > A question that names no language reads your preferred content language, and the answer comes back > in your backend language. Both are covered in [Rules](00_Rules.md#languages). ### Narrow it down Now add a condition. The next question builds on the same class: ``` Which electric bikes weigh more than 25 kg? ``` Two conditions, one on a checkbox and one on a number. You can keep going in the same sentence: ``` Which electric bikes weigh more than 25 kg and have fewer than 8 gears? ``` Conditions can also be about what is missing, which is usually the more useful question: ``` Which bikes have no description in French? ``` Under all of this, Genius builds a filter tree. You never write it by hand in the chat, but a routine stores one and a plan step selects with one, so it is worth knowing it exists, see [Filters](11_Query_Filters.md). ### Count, group and add up The same chat answers questions a list screen cannot: ``` How many bikes per frame size? How heavy is the average bike per category? How many bikes were added per month this year? ``` Grouping and totals are read in the query, not counted afterwards, so the numbers are right for the whole result and not only for the page you are looking at. A group carries its own count and whatever else you asked to be worked out, so one question answers both at once. A question about a date also picks how wide a group is, per year, quarter, month, week, day or hour, and *per month* therefore gives you twelve groups and not one per moment a bike was added. ### More shapes of question The whole range in one place, including what you just asked: | shape | example | |--------------------------|-----------------------------------------------------------------------| | Several conditions | *Which bikes are electric, weigh under 20 kg and have no image?* | | What is missing | *Which pages have no meta description?* | | Counting and grouping | *How many bikes per frame size?* | | Totals and averages | *What is the average weight per category?* | | Grouped over time | *How many bikes were added per month this year?* | | Values nested in a field | *Which bikes have an accessory over 200?* | | One language | *Which bikes have no German description?* | | Two languages compared | *Which bikes have a description in German but not in French?* | | Across element types | *What did I change last week?* | | Where something is used | *Where is this image used?* | Some of these reach further than any single backend screen. An accessory price sits in a field collection with any number of entries per bike, and no screen adds those up. A question about a tag comes back as pages, images and bikes in one answer, where the backend keeps three separate trees. ### Point at an element Sometimes the question is about one particular thing. Drag it out of the tree into the chat input, and a reference to it is written where the cursor is: ``` Where is [[element:asset:17]] used? ``` You can drag several elements in at once, folders included, out of any of the three trees. Typing a path by hand works as well. Each reference is looked up again on every turn and handed to Genius as one entry: element type, id, subtype, key, path, and the class if it is a data object. The same element dragged in twice counts once. An element that was renamed or moved since you dragged it in is read as it stands now. The reference names the element. The sentence around it decides what part the element plays. A folder dragged in as the place to put something new is a destination, not a set of elements to work on. If a reference points at something that is gone, or that you are not allowed to see, Genius says so and asks what you meant. It never quietly picks something else. > [!NOTE] > You do not always have to point. Genius already knows which object, asset or document is open in > the active tab, and the text you last selected in a backend field. Both travel with your message, > so *change the headline of this page* works with nothing dragged in. An element you name yourself > always wins over the open one. ### See the rows of an answer A question names how many rows it is about. *The most expensive product* is one row, *the five newest forms* are five, and *products over 300 euros* are all that match. Genius shows exactly these rows, in the order the answer was read in. Up to five rows appear in the chat below the answer. Each row shows its name and the fields the question was about. A click on a row opens it. More rows open in a paginated grid, the Genius Explorer. The answer then carries a button: ``` Bikes, 92 rows ``` The columns of the grid are the fields of the query and the field it is sorted by. A click on the folder icon opens a row. The model never reads more rows than the chat shows. It tells you what the rows mean and leaves the rows to the chat and the grid. The setting `explorer.inline_display_threshold` sets the number of rows, see [Configuration](01_Configuration.md). One question can run more than one query, and each of them shows its own rows. ### Where your conversations go Every chat is a conversation and is saved for the user who had it. You will find past conversations under **My Genius > Conversations**, where you can reopen or delete them. ### Everything Genius can reach You have been asking about data objects. The same chat reaches the rest of the backend: | area | what you can ask about | |------------------|-----------------------------------------------------------------------------------------------| | Data objects | Any class, its fields, its relations, its object bricks and field collections | | Documents | Pages, snippets, emails and links, and the content placed on a page | | Assets | Files, their type, their metadata, what an image shows, and the text a PDF or text file holds | | Elements | Objects, documents and assets in one answer | | Tags | The tag tree, and which elements carry which tag | | Properties | Element properties, by key and value | | Dependencies | What uses an element and what an element uses | | Notes and events | Notes on elements, with their type and data | | Scheduled tasks | What is scheduled to publish or unpublish, and when | | Mail | The mail log, its status, and the document or form behind it | | Workflows | The workflow places an element sits in | | Translations | The keys an application asks for, and the text behind each per language | Other bundles add areas of their own, such as stores and prices, or forms and their submissions, see [Extending](40_Extending.md). ### When not to use it Use the backend search when you can find something by its name or id. Genius is for the questions a screen cannot answer, and every question costs a model call. ### Next You can now ask about anything in the backend. The next step is changing content, which is a different flow: Genius writes a plan, you approve it, and a job carries it out. Continue with [Writing](20_Writing.md). Asking the chat for an image or a spoken text is covered there too, under [Images and speech](20_Writing.md#images-and-speech). To make Genius answer about data of your own, see [Extending](40_Extending.md). --- ## Filters A query tool and the schema tool that names its fields are reached together, whichever of the two is asked for. Reading the schema first is what a filter is written from: a filter written without it names fields the installation does not have. Every query narrows its result with a filter tree. A query tool builds one from the question you asked, a routine's Explorer query source holds one, and a step's `target.matching` selects with one. This page is the grammar of that tree, and of the two arguments a query reads over what the tree finds: `groupBy` and `aggregate`. - [Filter structure](#filter-structure) - [Operators](#operators) - [Inherited values](#inherited-values) - [Filter on a path](#filter-on-a-path) - [Fields that hold rows](#fields-that-hold-rows) - [Group the result](#group-the-result) - [Group a date by year, month or week](#group-a-date-by-year-month-or-week) - [Work out a number over the result](#work-out-a-number-over-the-result) - [Fields that cannot be filtered](#fields-that-cannot-be-filtered) ### Filter structure Every key of an object is `and`, `or`, `not`, or the path of a field as the schema lists it. Keys in the same object are AND-ed. Wrap in `and` only to group next to an `or` or a `not`. ```json {"electric": true, "or": [{"weight": {"gte": 10, "lte": 20}}, {"name": {"contains": "City"}}], "not": {"path": {"startsWith": "/bikes/archive/"}}} ``` The condition on one field takes one of four forms. | form | means | |-------------------------------|-------------------------------------------| | `"electric": true` | Equals, and there is no `equals` operator | | `"color": ["black", "red"]` | One of these | | `"image": null` | Is NULL | | `"weight": {"gte": 10}` | An operator object | A filter on a localized field compares one language. The query names it, and a query that names none compares the acting user's preferred content language, see [Rules](00_Rules.md#languages). A field name or an operator one letter off the one this installation has is read as that one, where exactly one of them is that close. A word that sits as near to two of them, or that begins two field names, is refused instead: writing into the wrong field is worse than one more round. ### Operators An operator object holds one or more of these keys. Which of them a field takes follows from its `valueType`, unless the field narrows the list itself. `gte` and `lte` in the same object are read as one range and compiled to `BETWEEN`. | operator | means | on | |--------------------------|---------------------------------------------------------|-----------------------------------------| | `ne` | Not equal. `"ne": null` means is NOT NULL. | any comparable field | | `gt`, `gte`, `lt`, `lte` | Greater or less than, with or without equal. | `string`, `number`, `date`, `structure` | | `contains` | Matches anywhere in the value, ignoring case. | `string`, `strings`, `structure` | | `startsWith`, `endsWith` | Matches at the beginning or at the end only. | `string` | | `in`, `notIn` | Matches any of these values, or none of them. | any comparable field | | `empty` | `true`: NULL or an empty string. `false`: a real value. | any comparable field | | `inTree` | Everything below this tag and not the tag itself. | the `path` field of a tag | `inTree` belongs to a field rather than to a value type, and one field lists it: `path` on a tag, which is a path of tag names and takes nothing but a plain value or `inTree`. A tag carries no path of its own, so its branch is walked through the tree, however deep. For the tags directly under one, filter `parentId` with its id. The path of an element is a stored value and takes `startsWith`, see [Filter on a path](#filter-on-a-path). A `strings` field holds several values in one comma separated column. A comparison on it asks whether one of them is in there, and it takes a value, a list of values, or `empty`, and nothing else. Adding an operator of your own: [Add a filter operator](extending/Filter_Operators.md). ### Inherited values An object can show a value only because a parent object holds it. A condition compares the value as it reads on screen, borrowed or not. `inheritance` picks the other reading, and it is said per condition, so one filter tree can ask both. | written | compares | |----------------------------------------------------|---------------------------------------------------------------------| | `{"image": {"empty": true}}` | What the element shows. This is what an ordinary question means | | `{"image": {"empty": true, "inheritance": "own"}}` | What the element holds itself. A borrowed value counts as empty | `inheritance` sits in the operator object beside the comparison and takes `inherited`, the default, or `own`. On a field that cannot inherit it changes nothing. *Which bikes show an image but hold none of their own* needs both readings in one tree: ```json {"and": [{"image": {"empty": false}}, {"image": {"empty": true, "inheritance": "own"}}]} ``` A value worked out from several rows with `countDistinct`, `avg`, `sum`, `min` or `max` has no reading of its own. `inheritance` is refused there. Say it on the field the rows are read from instead. ### Filter on a path `path` on an element is its full path including its own name. It takes a plain value, a list, `ne`, `in`, `notIn` and `startsWith`, and nothing else. | written | matches | |------------------------------------------|---------------------------------------------------------------| | `{"path": "/en/bikes/road"}` | The one element whose path is exactly that | | `{"path": ["/en/bikes", "/de/bikes"]}` | Either of them | | `{"path": {"startsWith": "/en/bikes/"}}` | Everything below it, however deep, and not the element itself | A prefix is taken as written, so the closing slash decides what it matches. `/en/bikes/` is everything below that element. `/en/bikes` without one also matches the element itself and every name beginning the same way, such as `/en/bikesale`. Everywhere else a trailing slash is dropped, so `{"path": "/en/bikes/"}` asks the same question as `{"path": "/en/bikes"}`. Any element can hold children, not only a folder. For the direct children alone, filter `parentId` with that element's id. A value without a leading slash is refused: `bikes` is a name and not a path. Filter `key` for the name instead and read the path off what comes back. A query that finds nothing and named a path no element of that type has says so in the answer, so an empty folder reads differently from a folder that was never there. ### Fields that hold rows A `relation`, `relations`, `objectbricks` or `fieldcollections` field holds rows of its own, so a condition on one of them says nothing until you say how many have to match. It takes no comparison. | key | means | |---------|--------------------------------------------------------------------------| | `any` | At least one row satisfies the condition | | `every` | Every row does, and an owner with no rows at all counts as satisfying it | | `none` | No row does. This is the form for a "without" question | | `empty` | `true`: no row at all. `false`: at least one | | `count` | How many rows there are, compared like any number | > [!TIP] > A bare id on such a field is read as `any` with that id, so `{"category": 12}` and > `{"category": {"any": {"id": 12}}}` ask the same question. Use `none` for a "without" question: > `any` wrapped in `not` asks something else, because it also matches an owner with no rows at > all. Inside `any`, `every` and `none` the same grammar starts again over the target's own fields, to any depth. A subfield there may also carry `countDistinct`, `avg`, `sum`, `min` or `max` to compare that subfield across the rows. `avg` and `sum` take a `number` field, `min` and `max` a `number` or a `date` one, and `countDistinct` any field that is not itself made of rows. ```json {"category": {"none": {"name": "Cargo"}}, "accessories": {"any": {"price": {"avg": {"gt": 200}}}}} ``` ### Sort by a field of the rows `sortBy` reaches into a field that holds rows with `.`, such as `price.price`. One element can hold several rows, so a descending sort ranks it by its highest value and an ascending sort by its lowest. An `any` filter on the same field narrows the rows that count. The filter sits at the top of `filters` or inside an `and`: ```json {"filters": {"price": {"any": {"store": "Switzerland"}}}, "sortBy": "price.price", "sortDescending": true} ``` This ranks the products by their price in that one store. ### Group the result `groupBy` sits beside `filters` rather than inside it. It names one field, and the answer is one group per distinct value of that field rather than the elements themselves: ```json {"groupBy": "frameSize", "limit": 3} ``` ```json {"groups": [{"group": "M", "count": 41}, {"group": "L", "count": 27}, {"group": "S", "count": 9}]} ``` The biggest group comes first and `limit` caps how many of them are listed. Where it cut the answer off, the result says how many groups there are in all, so raise `limit` to see the rest. One answer holds 50 groups at most. `offset` does not page through groups, and `countOnly` and `sortBy` say nothing here and are ignored. #### Group a date by year, month or week A date grouped as it is stored makes one group per instant, which is almost never the question. `groupGranularity` says how wide one group is, and it takes one of six widths. | `groupGranularity` | one group per | named | |--------------------|------------------|----------------------| | `year` | calendar year | `2026` | | `quarter` | calendar quarter | `2026-Q3` | | `month` | calendar month | `2026-07` | | `week` | ISO week | `2026-W31` | | `day` | day | `2026-07-24` | | `hour` | hour | `2026-07-24 15:00` | A week belongs to the year its Thursday is in. Every name is written largest part first and padded, so the groups sort the way they read. On a field that is not a date `groupGranularity` is refused, because there is nothing for a width to mean. ### Work out a number over the result `aggregate` is an object of result key to field path, and each key is worked out over every row the filter matched. | key | works out | on | |-----------------|------------------------------------------------|-------------------------------------------| | `countDistinct` | How many different values the field holds | any field that does not itself hold rows | | `avg` | The average | `number` | | `sum` | The total | `number` | | `min`, `max` | The smallest and the largest value | `number`, `date` | There is no `count` key. How many rows matched at all is `countOnly`, and a grouped answer carries its count per group anyway. ```json {"filters": {"electric": true}, "aggregate": {"avg": "weight", "countDistinct": "color"}} ``` ```json {"avg": 24.8, "countDistinct": 6} ``` Set `groupBy` and `aggregate` together and every group carries those numbers beside its own count: ```json {"groupBy": "creationDate", "groupGranularity": "month", "aggregate": {"sum": "weight", "countDistinct": "color"}, "limit": 4} ``` ```json {"groups": [{"group": "2026-08", "count": 12, "sum": 214.5, "countDistinct": 4}, {"group": "2026-07", "count": 9, "sum": 168.0, "countDistinct": 3}]} ``` > [!IMPORTANT] > `avg`, `sum`, `min` and `max` come back read the way the field itself reads, so a total over a > price is an amount in the currency unit. `countDistinct` answers in rows and is never read that > way: how many different prices there are is a plain number, and how many different owners a set of > bikes has is a number and not an owner's name. ### Fields that cannot be filtered A field the schema marks `"notComparable": true` has no column behind it. A filter on it is refused, and so are `sortBy` and `groupBy`. It can still be read. `sortBy` and `groupBy` are refused on two further grounds. A field whose value is only ever shown masked cannot be sorted or grouped by, because the order would hand back what the masking keeps out. A field whose processor gives no SQL expression cannot either, however comparable it is. --- ## Translations Genius reads and writes the OpenDXP translation catalogues: the keys an application asks for by name, and the text stored behind each per language. A key appears when the application first asks for it, so a step fills in a text and never adds a key or removes one. - [Catalogues](#catalogues) - [Fields of a row](#fields-of-a-row) - [Find what is not translated yet](#find-what-is-not-translated-yet) - [Compare two languages](#compare-two-languages) - [Write a text](#write-a-text) - [Have the text translated](#have-the-text-translated) - [What is not in a catalogue](#what-is-not-in-a-catalogue) ### Catalogues | catalogue | holds | languages | |------------|-------------------------------|-------------------------------------------| | `messages` | the texts a website renders | the content languages of the installation | | `admin` | the texts the backend renders | the admin languages, a separate list | A call names one under `catalog`, and there is no answer across both. Left out, it is `messages`, see [Rules](00_Rules.md). Only these two are offered. A further domain a project registers under `opendxp.translations.domains` is not in the `catalog` enum, because this bundle carries no description of its columns. Reading and writing both need the OpenDXP permission `translations`, the one the backend translation editor needs. ### Fields of a row A row is one key in one language. A key of four languages is four rows, whether anybody has written into them or not. | field | holds | |-------------|---------------------------------------------------------------------------| | `key` | the name the application asks for, `form.label.firstname` | | `language` | the language of this row | | `text` | what a reader sees, an empty string until somebody writes it | | `type` | how the text is held, `simple` for a plain text | | `languages` | the same key's rows in the other languages | These five are all a query reaches. `get_translation_query_schema` lists the languages the named catalogue is configured for, so a filter never has to guess one. ### Find what is not translated yet Filter `text` for an empty string. ```json {"catalog": "messages", "filters": {"language": "en", "text": ""}} ``` ### Compare two languages `languages` reaches the same key's rows in the other languages. `any` of one language and `none` of another asks for a gap: written in one, still empty in the other. ```json {"catalog": "admin", "filters": {"language": "de", "text": {"ne": ""}, "languages": {"none": {"language": "en", "text": {"ne": ""}}}}} ``` > [!IMPORTANT] > Name the row's own `language` beside it, as here. A filter that reaches only through `languages` > matches every language of every key it finds, and the count comes back as the number of keys times > their languages. For one language alone, compare `language` and `text` on the row itself. Everything else about the filter tree is the ordinary grammar, see [Filters](11_Query_Filters.md). ### Write a text `translation.update` is the only write. There is no `translation.create` and no `translation.delete`. A row carries no id, so a step names the key itself. ```json {"ref": "fill", "op": "translation.update", "selector": "admin", "locales": ["en", "fr"], "target": {"subject": "form.label.firstname"}, "values": {"text": "First name"}} ``` `values` takes `text` and nothing else. `locales` names the languages it goes into. A target matching several keys writes into every one of them, which is why a step that states its text normally names a single key. A key the catalogue does not hold is refused rather than created. `locales` accepts the languages of the catalogue the step writes into: the content languages for `messages`, the admin languages for `admin`. #### Have the text translated `text` also takes a `$translate`, so one step translates a whole catalogue. It is worked out once per language named, and it reads the same key in the language under `sourceLocale`. This is the plan behind *translate every key that is filled in German and still empty in English, from German*. ```json {"ref": "translate", "op": "translation.update", "selector": "admin", "locales": ["en"], "target": {"matching": {"language": "de", "text": {"ne": ""}, "languages": {"none": {"language": "en", "text": {"ne": ""}}}}}, "values": {"text": {"$translate": {"sourceLocale": "de"}}}} ``` There is no instruction to write: the wording that asks for the translation is built by the system, see [Writing](20_Writing.md#value-forms). A `$generate` here writes a **new** text in the language the step writes, and cannot read another one. > [!IMPORTANT] > A key that is still empty in the source language is left as it stands rather than written empty, > so a run over a catalogue only fills in what there was something to translate. A step that writes a language the acting user may not edit is refused, with the languages they may edit. The backend catalogue is not restricted this way. ### What is not in a catalogue A translated field of an object or a document is read on the element itself, with a `locale`, and not here. The language a page renders in is the `language` field of that document, which says nothing about either catalogue. --- ## Writing In [Asking](10_Asking.md) you only read. This page is the other half: you describe a change in words, Genius turns it into a plan, you approve the plan, and a job carries it out. You will start with one bike and one field, read the plan Genius built for it, then grow the same change until it covers every bike in a folder. After that come the parts you reach for once you know the flow: what a step can write, how routines repeat a change, and what to do when a job stops. Nothing is written until you approve it. Everything on this page can be tried and abandoned. The examples use the `Bike` class from [Asking](10_Asking.md): `name`, `frameSize`, `color`, `weight`, `gears`, `electric`, `description`, `image`, `category`, and a field collection `accessories` whose entries have a `name` and a `price`. - [Make your first change](#make-your-first-change) - [Read the plan](#read-the-plan) - [Change many elements at once](#change-many-elements-at-once) - [How a change is written](#how-a-change-is-written) - [Write a good instruction](#write-a-good-instruction) - [When a plan is refused](#when-a-plan-is-refused) - [When no plan comes back at all](#when-no-plan-comes-back-at-all) - [What a step can write](#what-a-step-can-write) - [Add, change or remove the items of a field](#add-change-or-remove-the-items-of-a-field) - [A translated field inside an item](#a-translated-field-inside-an-item) - [Rename, move, publish or delete an element](#rename-move-publish-or-delete-an-element) - [Lay out a page](#lay-out-a-page) - [Targets](#targets) - [Variants](#variants) - [Value forms](#value-forms) - [Which form a value takes](#which-form-a-value-takes) - [Images and speech](#images-and-speech) - [In the chat](#in-the-chat) - [In a plan](#in-a-plan) - [Orientation and size](#orientation-and-size) - [The content of a new asset](#the-content-of-a-new-asset) - [Replace the file of an asset](#replace-the-file-of-an-asset) - [Routines](#routines) - [Placeholders](#placeholders) - [Generative prompts](#generative-prompts) - [Elements](#elements) - [Start a routine](#start-a-routine) - [Jobs](#jobs) - [Units and the job log](#units-and-the-job-log) - [When a job stops](#when-a-job-stops) - [Continue a blocked job](#continue-a-blocked-job) ### Make your first change You need `opendxp_content_crafter_execute_update` to change elements and `opendxp_content_crafter_execute_create` to create them. Deleting needs neither. It has a permission of its own, see [Rename, move, publish or delete an element](#rename-move-publish-or-delete-an-element). Open the chat and say what you want, the way you would say it to a colleague: ``` Set the frame size of City Bike 3 to M. ``` Genius does not change anything yet. It works out which element you mean and which field, and comes back with a plan: ``` 1 Changes 1 × Bike [English] Only those where (Name) is ("City Bike 3") (Frame size) : ("M") ``` Approve it, and a job writes that one value. That is the whole flow, and it is the same flow for a change over forty thousand elements. > [!NOTE] > What runs is the plan, not the sentence that produced it. Once you have approved a plan, the > wording you typed no longer matters. There is no other way to write content with Genius. ### Read the plan The plan you just approved had one step. Before you approve a bigger one, it is worth knowing how to read it. Everything in brackets is drawn as a pill on screen. A pill is a value the job reads or writes while it runs, and the words around it say what happens to it. A pill that opens with a number was made in another step, and the number is that step. A pill without one belongs to the step it stands in. So `(2 · Bike · Name)` is the `Name` of the bike step 2 is standing on, and `(Image)` is the field of the step whose line it is. A pill with a dotted underline holds more than it shows. Hover it, or reach it with the tab key, and what it was worked out from appears: the technical field name behind a label, the whole of a value the line had to cut short, the instruction a model is given, the wording stored under a prompt title, what a row operator does to the rows a field already holds. None of it is needed to decide on the plan. Fields, classes and languages are named the way the backend names them, see [Rules](00_Rules.md#labels). A line that says something about the step rather than something the step does, such as variants left out, is stepped in from the rest. A step that takes something away carries a warning sign on its title. > [!TIP] > The same summary is printed by `explain.php plan`, which costs no model call. Use it while you are > still working out how to word something, see [Debugging](50_Debugging.md). ### Change many elements at once Now the same change over a set. Nothing about the flow changes, only what the summary counts: ``` Set the frame size of every bike under /bikes that has none to M. ``` ``` 1 Changes 11 × Bike [English] Only those where (Frame size) is empty Variants left out, 27 more would be included (Frame size) : ("M") ``` Eleven elements, counted before anything runs, not estimated. The line about variants tells you what the step deliberately left out. One instruction can also come out as several steps that know about each other: ``` Take every bike without an image, generate one for each, put it in a new folder and hang it on the bike. ``` ``` 1 Creates a new Folder Puts it in (Home /) Names it ("generated") 2 For each of 11 × Bike [English] Only those where (Image) is empty Variants left out, 27 more would be included 2.1 Creates a new Image Puts it in (1 · Folder) Names it after (2 · Bike · Name) (The file itself) : (a generated image) from (2 · Bike · Name) 2.2 And on each of them Sets (Image) : (2.1 · Image) ``` The steps under step 2 run once per bike. Step 2.1 puts its image in the folder step 1 made, and 2.2 hangs that image on the bike step 2 is standing on. #### How a change is written You do not have to know this to use Genius, but it explains why a plan sometimes takes a moment. 1. You write the change in words, in the chat or as the instruction of a routine. 2. The model hands over everything the change touches as one plan, through `submit_plan`. That call names the operations the plan will use and opens the call that writes the answer. The grammar of that answer covers only the operations named. The answer is either the plan or one sentence saying why there is none, and that sentence is what a routine shows as its problem. The round working the change out always ends through `submit_plan`, whichever of the two it comes to. 3. The plan is checked as a whole before anything happens: field names, types, the operators a field offers, permissions, whether the filters compile, whether a step pointing at another step resolves, whether a medium can be read, whether a stored wording exists, whether a word a filter names a row by answers exactly one row. Everything wrong comes back at once and nothing is written. The plan is then written again with the problems put right, see [When a plan is refused](#when-a-plan-is-refused). 4. What holds up is summarised step by step and counted: how many elements it touches and how many model calls that comes to. Where jobs are reviewed, every step says whether it runs straight away or waits for a reviewer. 5. You approve that summary. In a chat by approving the plan, for a routine by starting it. 6. The job runs step by step, and each step element by element. Values the plan left open, such as `$generate.text`, are worked out now. A job carrying a review workflow writes none of them and holds every value for a reviewer instead, unless the plan does nothing but lay out pages, see [Review](30_Review.md). 7. Every element is saved the normal way, and a step that deletes runs the same delete the backend runs. Every element the job got to is written to its log, see [Jobs](#jobs). Whether that is live or a draft depends on what the step writes. | what a step writes | what the job leaves behind | |---------------------------------------|-----------------------------------------------------------------------------------------------------| | Page content | A draft version. The page visitors see is untouched, see [Lay out a page](#lay-out-a-page) | | Anything else, with a review workflow | Nothing yet. The value waits for a reviewer, and accepting it writes it, see [Review](30_Review.md) | | Anything else | The value on the element, live at once if the element is published | ### Write a good instruction Write the instruction the way you would say it, and name the fields by the labels you see in the backend. ``` Translate the description of every bike under /bikes into French. Keep brand names as they are. ``` Three things decide whether the plan comes out right. - **Name where a value comes from.** *Take the description and shorten it to 150 characters* is a rule. *Write something nice* is not. - **Say the languages if you mean several.** A step writes the languages it was given, and one that names none writes the preferred content language of the person the plan runs as, see [Rules](00_Rules.md#languages). - **Do not narrow twice.** If the element source already selects the bikes under `/bikes`, the instruction does not need to repeat it. An image is a source like any other field. *Fill the alt text of every image under /bikes from what the picture shows* has the model look at the file itself. The Vision engine reads it, see [Engines](02_Engines.md). ### When a plan is refused Sometimes the plan does not come back. A refusal is one of two things, and which one decides what happens next. | the refusal | what happens next | |----------------------------------------------------------|---------------------------------------------------------------| | Something the plan could say differently and get through | It is handed back to be written again and the turn carries on | | A limit that stands however the plan is worded | Nothing is retried. You are told what stopped it | Six limits stand, whatever the plan says. | the limit | what a plan runs into | |-----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | A field the query schema does not mark `"writable": true` | `id`, `modificationDate`, `versionCount` on any element | | A key that only exists while an element is made | `docType` on a document | | A permission the acting user does not have | The step's own permission, or the element's | | An element the step names that is not there | An id from an earlier turn, or from another tree | | An element whose state does not allow the step | The element is locked, or has a draft that is newer than the published version, see [Rename, move, publish or delete an element](#rename-move-publish-or-delete-an-element) | | A word a step's filter names a row by that answers no row | `{"category": {"any": {"name": "Cargo"}}}` where no category is called Cargo | Whether a field can be written is decided by the field itself, and this page does not repeat that answer, see [Asking](10_Asking.md). A plan that keeps being refused is given up on. Writing stops after three attempts in a row that put no problem right, and as soon as one attempt comes back with exactly the same problems as the one before it. You are told the problems of the last attempt, and nothing is written. The number of attempts is `limits.max_plan_refusals`, see [Configuration](01_Configuration.md). #### When no plan comes back at all A turn can hand back one sentence instead of a plan. Only three things are a reason for that: the installation cannot carry the request out however it is worded, the content already stands that way, or a password, a key or a token was asked for. That sentence goes to whoever asked, so it is checked before it gets there. Each of these sends the turn back to write again. | the answer | why it does not stand | |------------------------------------------------------------|---------------------------------------------------------------------------| | It names none of the three reasons | Something the turn could still look up is not a reason | | Its sentence names a tool or a skill | Both are the turn's own to call, and nobody else can call them | | It announced what it would write and read nothing about it | A claim about your content is worth nothing from a turn that never looked | The last one does not apply to a secret. That one is refused without reading anything. A turn sent back that answers the same way again is not sent back a third time, see the attempt limit above. ### What a step can write You have written one field. Here is the whole range. | what | what a step can do | |----------------------------------------|----------------------------------------------------------------------------| | Fields of an object, document or asset | Set a value, in one language or several | | Object bricks and field collections | Set, add, update, remove or replace entries | | Relations | Set, remove or replace what is related | | Properties | Set or remove a property on an element | | Notes | Add a note to an element | | Tags | Add or remove tags on an element | | The tag tree itself | Create a tag at a path, or rename one | | Page content | Lay out the content of a page | | New elements | Create a folder, object, document or asset with its values | | The element itself | Publish, unpublish, rename, move or delete an object, document or asset | | Translation catalogues | Set the text of a key, see [Translations](12_Translations.md) | A step can carry steps of its own that run once for each element it touches, so *give every bike under /bikes its own spec sheet and link it to the bike* is a single plan. A property keeps the name the request gives it. A name Genius picks itself is English in lowercase snake_case, like `missing_german_name`. A predefined property is always written under its key, also when the request calls it by its name. Fields listed under `field.write_protected` are never written and are not offered, see [Configuration](01_Configuration.md). #### Add, change or remove the items of a field A field the query schema gives an `itemKey` holds items rather than one value: a relation, the tags, the properties, the notes, an object brick, a field collection. A step writes such a field with an instruction about its items instead of a value. | instruction | what the field holds afterwards | |-------------|----------------------------------------------------------------------------------------------------------| | `$set` | The named items, changed at their key and put in where the field holds none. Every other item stays | | `$add` | The named items beside the ones already there. A key the field holds is refused rather than written over | | `$update` | The named items changed where they are. A key the field does not hold is refused rather than added | | `$remove` | Everything but the named items. An item to take out is nothing but its key | | `$replace` | Exactly the named items. Whatever the field holds now and is not named is gone | `$set` and `$replace` are the two to keep apart. `$set` reaches the items it names and leaves the rest of the field alone. `$replace` decides the whole field, so it is right for filling one that holds nothing and wrong for changing one that already holds something. Which of the five a field takes is in its query schema, under `writeOperators`, and it is not the same list for every field. A field collection hands out the `index` of an item itself, so an item has no name until it is in: it takes `$add`, `$update`, `$remove` and `$replace`. A relation names its items by id and an object brick by type, before they exist, so both take `$set`, `$remove` and `$replace` and neither has `$update`. A note gets its id from the field as well, but it stays as it was written, so the notes take `$add` only. `$add` and `$update` state what the field held before the write, which over a filter matching many elements is right for some of them and wrong for the rest. An item names itself with the `itemKey` and puts its own fields under `values`. An item that is nothing but its key, an id or a tag path, carries no `values`. An item of a relation with columns names the values of its columns the same way: `{"id": 12, "values": {"rank": 1}}`. ```json "accessories": {"$update": [{"index": 0, "type": "Accessory", "values": {"name": "Rear rack"}}], "$add": [{"type": "Accessory", "values": {"name": "Bell", "price": 12}}], "$remove": [{"index": 2, "type": "Accessory"}]} ``` `$update` and `$remove` take a `matching` in place of the part of the key the field hands out itself: one field of the item per key, with the value it has to have, and the rest of the key beside it. That is how a step over many elements names an item whose index is a different number in each. A condition compares the way a query filter compares. A value on its own means equal, `null` means the field holds nothing, and an object beside the field takes the same words a filter takes: `empty`, `ne`, `in`, `notIn`, `contains`, `startsWith`, `endsWith`, `gt`, `gte`, `lt` and `lte`, see [Filters](11_Query_Filters.md). A relation is named by the id it points at, so `{"empty": false}` is how a condition says the item points at something. ```json "accessories": {"$update": [{"type": "Accessory", "matching": {"price": {"gt": 50}}, "values": {"price": 49}}], "$remove": [{"type": "Accessory", "matching": {"name": {"startsWith": "old-"}}}]} ``` Which words a field takes is the same list its query schema gives, so a word it is not compared with is refused with the ones it is. To work on every item of a kind, an item says `"matchAll": true` beside its `type` and names no `matching` at all. A condition that narrows nothing is refused rather than read as "all of them", the same way a step's own target tells `matchAll` and an empty filter apart. ```json "accessories": {"$update": [{"type": "Accessory", "matchAll": true, "values": {"price": 0}}]} ``` ##### A translated field inside an item The items of a field collection or an object brick do not exist per language: one set of items carries every language at once. A translated field inside such an item therefore says its languages itself, one entry each, and the step's `locales` does not reach it. ```json "accessories": {"$update": [{"index": 0, "type": "Accessory", "values": {"name": [{"language": "en", "value": "Rear rack"}, {"language": "de", "value": "Gepäckträger"}]}}]} ``` Only the languages named are written, so a language left out keeps what it has, and one named with a `value` of `null` is emptied. A `value` takes whichever forms the step itself takes, so on a step that allows a `$generate` one language can be worded differently from the next, see [Value forms](#value-forms). A condition picking items by such a field names its language the same way, because the items it means are different ones in each language. Named for several languages it means the items holding all of them, and with no language named it is read in the first content language of the acting user, see [Rules](00_Rules.md#default-language). ```json "accessories": {"$update": [{"type": "Accessory", "matching": {"name": [{"language": "de", "value": null}]}, "values": {"name": [{"language": "de", "value": "Gepäckträger"}]}}]} ``` Everywhere else a translated field takes its value plainly and the step's `locales` says which languages to write it into, see [Targets](#targets). #### Rename, move, publish or delete an element These five actions change the element itself rather than the values it holds. A version does not undo any of them. Each action therefore needs a permission of its own, in addition to the right to run the job, and each one is written to the audit log. | action | how a step writes it | permission | workspace rights on the element | |-----------|----------------------------------------------------------------------|-------------------------------------------|---------------------------------| | Publish | `{"published": true}` | `opendxp_content_crafter_critact_publish` | `publish` | | Unpublish | `{"published": false}` | `opendxp_content_crafter_critact_publish` | `unpublish` | | Rename | `{"key": "the-new-name"}` | `opendxp_content_crafter_critact_rename` | `settings`, `rename` | | Move | `{"parentId": 42}` | `opendxp_content_crafter_critact_move` | `settings`, `rename` | | Delete | `object.delete`, `document.delete` or `asset.delete`, with no values | `opendxp_content_crafter_critact_delete` | `delete` | Two things are checked. The permission decides whether this installation lets Content Crafter perform the action at all. The workspace rights decide whether this user may perform it on this element, see [Rules](00_Rules.md#permission-and-visibility). Moving checks the rights of the element that is moved and, like a creation, the rights of the element it is moved under. `key` is a single name and never a path. `parentId` is the numeric id of the element the moved one sits under, or `"$"` pointing at the step that creates it. Anything in a tree can hold what goes under it, a folder, a page and an object alike. A step may set both at once, which renames and moves the element in one go. A name already taken at that place is refused while the plan is checked. A name that has become taken by the time the job gets there is numbered up instead, the way a creation numbers one up, so a step over many elements does not stop at the second one to want the same name. An asset is never published, so an asset step does not take `published`. A renamed file keeps an ending that says what it is. A step that also writes `content` gets the ending of the new file, see [Replace the file of an asset](#replace-the-file-of-an-asset). An element cannot be renamed or moved while it is locked, or while it has a draft that is newer than the published version. Both actions would rewrite the path that draft was taken against. An element also cannot be moved into itself or into anything below it. Moves are read together as well: two of them that are each allowed on their own can leave a parent chain that never ends, and the whole plan is refused for it. A `.delete` step takes no `values` and no `locales`. A step that names either is refused. Deleting an element also deletes everything below it, so the summary states how many elements are deleted with it and how many other elements point at the one that was named. ``` 1 Deletes Bike “City Bike 3” (#123) and the 12 below it 3 elements point at it. ``` Every element below the named one is checked for the delete permission before anything is deleted. A project can forbid a deletion by listening to the `DELETE_INFO` event of that element type. The reason it gives is quoted back word for word. A folder is an ordinary `selector` for documents and assets, so `document.delete` and `asset.delete` can name one directly. Object folders belong to no class, so `object.delete` cannot name one. Delete the objects inside it instead, with `{"matching": {"path": {"startsWith": "/bikes/archive/"}}}`. Deletions and creations are read together as well. A step that deletes an element and a step that creates one at the same path are refused as a pair. Deleting does not free the name. It throws the element away with its id, and every link, field and reference pointing at it goes with it. Change the element that stands there instead. Where what is wanted cannot be written into it, a PDF into an asset that holds an image for example, it belongs beside it under a name of its own. A deletion cannot wait for a reviewer, see [Review](30_Review.md). Each of the five actions is written to the table `content_crafter_audit_log`, on the connection that performed it. One row records the action, the user, the element and the job it ran under. The name of the element is stored as it read at that moment, so a deleted element is still identified by the path it had. #### Lay out a page Laying out a page needs the right to write documents and the right to save the document itself. The step writes a draft version. On a published page, what visitors see stays as it is until somebody opens the page in the editor and publishes it. A page that is not published yet is written directly. A brick is named by the `key` the page was read with. A job about a kind of brick rather than about one brick, such as every heading or every quote, names them with `matchAll` and, where it narrows further, `brickType` or a `matching` of settings. That reaches the bricks at one level. The ones inside another brick are named the same way in that brick's own `children`. A name that finds no brick fails the plan, and what it did find stands beside the step when somebody approves it. A layout step never waits for a reviewer, because the draft it writes holds the change back already. Where jobs are reviewed, a plan therefore either lays out pages or changes content, never both, see [Review](30_Review.md). Whether the page may then be published is not decided here. Set that up on the document itself, for example with an OpenDXP workflow. > [!NOTE] > A draft belongs to the user who made it. The step reads the draft of the user the job runs as, see > [Rules](00_Rules.md#acting-user), and carries on from there rather than from the published > content. ### Targets A step names its elements in `target`. A step that acts on an existing element takes exactly one of four keys. This applies whether the step changes the element or deletes it. | key | acts on | |--------------------|--------------------------------------------------------------------------------------------------| | `"subject"` | One thing, by an id a read tool gave, or `"$"` naming the step in this plan that makes it | | `"matching"` | Every element a filter finds, see [Filters](11_Query_Filters.md) | | `"matchAll": true` | Every element of the step's `selector`, with no condition narrowing it | | `"given": true` | The elements the routine is pointed at when somebody starts it | Each of the four is a branch of its own in the grammar, so a step cannot name two of them. Say `matchAll` where the request names the selector and nothing else, as *set this on all bikes* does. A `matching` with no conditions in it is refused rather than read the same way, so a filter somebody forgot to write cannot quietly change everything. A `matching` on a translated field reads it in the **first language the step writes**, and a step that writes none reads it in the preferred content language, see [Rules](00_Rules.md#default-language). So *the products with no French name* is a step whose `locales` begins with `fr` and whose filter asks for an empty name: the one language is named once, and the filter runs in it. A language is never written inside the filter itself. `"variants"` stands beside `matching` or `matchAll` and says whether object variants take part: `exclude`, which is the default, `include` or `only`. It sits in those two branches and nowhere else, because `subject` and `given` name what they act on already. A step that leaves variants out says how many, in a line of its own. A step that creates elements says `"count"` instead, how many to make, and one that makes a single element may leave the target out altogether. None of the four above fits a step whose elements do not exist yet. Such a step also names a `parentId`, the id of the element the new one goes under, and a `key`, the last part of its path. A key already taken in that place gets a number appended rather than being refused, so one key serves a step that makes many. To name each new element after the one it belongs to, write `"$."`, as in `"$bike.name"`. A `$generate` or a `$transform` is refused there, because a name has to be known before the element is made. A step's own ref names the element it is standing on, so `"$."` is how one field of an element is written from another: in a step whose ref is `bike`, `"$bike.name"` is the name of the bike this round writes. The value is read before the step writes, so it is what stood in the field when the step began. A step that makes its element cannot do this, because there is nothing to read off it yet. The `steps` under a creating step run once for each element it made, pointing back at it with `{"subject": "$"}`. *Make two pictures and describe each of them* is one creating step with a `count` of 2 and one step under it. A required field the step leaves empty does not stop it. A plan writes what the request named, so a field the request said nothing about lands empty and somebody fills it in later. #### Variants A class that allows variants offers `variantOf` instead of `parentId`: the id of the object or the variant of that same class which the new one varies, or `"$"` naming the step that makes it. A variant has no place of its own in the tree, so the key that says where it goes is the same key that says it is a variant. Name one of the two, never both. ```json {"ref": "small", "op": "object.create", "selector": "Bike", "values": {"variantOf": 123, "key": "city-bike-3-s", "frameSize": "S"}} ``` A class that allows no variants does not offer the key at all. A plan that names it anyway is refused and cannot be corrected. Somebody has to switch variants on for the class first. ### Value forms A value in a plan is usually the value itself. Three other forms exist, and which of them a step may write is part of the grammar it is read against, see [The plan grammar](extending/Plan_Grammar.md). | the step | its values may be | |-------------------------------------------|---------------------------------------------------------------| | `.update` on an object, document or asset | The value, a `$transform`, a `$translate` or a `$generate` | | `.create` on an object, document or asset | The value or a `$generate` | | A layout step, a tag step | The value | Each form reads in exactly one way, and that is what tells them apart. | form | reads | writes | |--------------|------------------------------------------------|-----------------------------------| | `$transform` | a field, in any language named | what it read, with pieces swapped | | `$translate` | a field, in the language named | the same text in another language | | `$generate` | the fields of `input`, in the language written | something new | #### Which form a value takes Two questions decide it, in this order. **1. Are the elements named one by one, or found by a filter?** | the step's target | what follows | |---------------------------------------------|----------------------------------------------------------------------------------------------| | `subject`, `count`, or one step per element | The plan knows each element while it is written, so it writes the values out. No model call. | | `matching`, `matchAll`, `given` | There is no one value, there are as many as the filter finds. Go to question 2. | **2. Does the value depend on the element it goes into?** | the value | write | model calls | |---------------------------------------------|------------------------------------|-------------| | The same for every element | The value itself | none | | Worked out from what the element holds | `$transform` | none | | The same text in another language | `$translate` | one each | | Different per element, from nothing | `$generate` with an empty `input` | one each | | Different per element, from the element | `$generate` with `input` | one each | Three rules fall out of this and hold everywhere. **A value that has to be known before the element exists cannot be generated.** `key` and `parentId` are read while the element is made, so a `$generate` in either is refused. Ten new pages with ten invented names are ten steps with ten names written out, not ten generations: a generated name would leave every page at the key the step gave it. **A value describing something the plan does not hold is never written out.** An alt text, a caption, what a picture shows or what a document says: whoever wrote the plan has not seen the file, so a sentence written there is guessed from the file name. It is a `$generate` reading the asset's `content`, whatever the value would have said. **`input` is the whole of what the model sees.** It reads nothing else about the element. A generation with an empty `input` therefore writes the same kind of value into every element without knowing which one it is in, and that is what makes it the right form for "give each of them one of its own" and the wrong one for "describe each of them". `$transform` works the new value out of what the element already holds. It carries a `prefix`, a `suffix`, a `replace` of `search` and `with`, or a `from` naming another field to copy. An element with nothing in the field it reads is left alone. `$translate` carries what a field holds in one language into the language the step writes. It names that language under `sourceLocale` and nothing else is needed: the wording that asks for a translation is built here rather than written into the plan, so it reads the same every time and can say things a plan could not, such as keeping markup where the text carries it. `from` reads another field instead of the one being written. An element with nothing in the source language is left alone rather than emptied. Where the installation has more than one translator, `with` names one; left out, the one the installation is set to does it, see [Engines](02_Engines.md). `$generate` has a model write the value per element, from an `instruction` and the `input` it may read. Its `as` says which media type. Image and audio go into the `content` of an asset step, see [Images and speech](#images-and-speech). A model works out words and files, so both forms are refused on a field that holds anything else. A relation, a number, a boolean and a date each take the value written out, an id a read tool gave, or `"$"` naming the step that makes it. The refusal comes while the plan is checked, so no model call is made first. ```json {"$generate": {"instruction": "one sentence on what this picture shows", "input": [{"from": "image", "take": "content"}], "as": "text"}} ``` Both name what they read with the same three keys. `from` is the field, `item` names one row of it the way that field's `itemKey` names its rows, and `take` the part of that row to read. An entry of `input` is either a field name on its own or an object of the three, and reads every row where it names no `item`. A `$transform` also takes a `sourceLocale`, which copies one language into another without changing a word. Reading one language to write another *as a translation* is `$translate`, and a `$generate` has no way to read a language other than the one it writes. An entry of `input` can hand a value over instead of naming a field. `value` is what to hand over and `name` what the model is told to call it, as in `{"value": "$bike.name", "name": "bike"}`. That is how a step reads a field of the element another step stands on. > [!IMPORTANT] > `$generate` and `$translate` each cost one call per element and per language. A step that writes > one field of forty thousand elements is forty thousand calls. `$transform` costs none. What a > translation costs is counted in the unit its translator works in, which is not always tokens. Every asset except a folder has a `content` field: the text of a text file, the extracted text of a PDF, and for everything else the file itself. A file goes to the model as a file, so the generation runs on the engine that reads that asset type rather than the Content one, see [Engines](02_Engines.md). Images are the only type read, and a generation given a file no role reads is refused when the plan is built, not when it runs. ### Images and speech A file is made in one of two places. | where | how | what comes out | |-------|-----------------------------------------------------------------------------------------|---------------------------------------------------------| | Chat | Genius calls `generate_image`, `edit_image` or `generate_speech` | One file, shown or played in the chat. No asset is made | | Plan | A `$generate` with `"as": "image"` or `"as": "audio"` in the `content` of an asset step | One asset per element the step touches | The three tools need a conversation, so the routine window does not offer them at all and a `$generate` is the only way to a file there. A chat has both ways, and a request that covers a set of elements is a `$generate` in the chat too. A plan never calls a tool. #### In the chat *Make me a picture of a red city bike.* It is shown at once and no asset is made. Ask for another attempt, ask for one thing about it to be changed, or say where to keep it. Keeping it is a plan with an `asset.create` step whose `content` names the `mediaRef` that came back. Putting it over a file that is there is an `asset.update`, see [Replace the file of an asset](#replace-the-file-of-an-asset). Under the picture stands how big it is and what it is, such as `1024 × 1536, PNG`. Clicking it opens it at its own size. A sound file has no measurements, so its line names the format alone. A `mediaRef` is not an element id. It reaches only what was generated in the same conversation. #### In a plan *Give every bike without an image its own photo.* The step that makes the file sits inside the step that picks the bikes, so it runs once per bike while the job runs. ```json {"ref": "file", "op": "asset.create", "selector": "image", "values": {"parentId": "$folder", "key": "$bike.name", "content": {"$generate": {"instruction": "a bike photo on a white background", "input": [{"value": "$bike.name", "name": "bike"}], "as": "image"}}}} ``` Image needs the Image role assigned and audio the Audio role. A step asking for a media type this installation has no engine for is refused when the plan is built, see [Engines](02_Engines.md). #### Orientation and size Asking for an image takes an `orientation` of `square`, `portrait` or `landscape`, both in the chat and in a `$generate` with `"as": "image"`. It is optional. Left out, the provider reads the prompt and picks. `edit_image` has none, because a change keeps the shape of the image it changes. A resolution cannot be asked for. A picture a model makes is at most 1536 pixels on its longest side, whichever provider makes it. #### The content of a new asset An asset cannot be made empty and filled later, so every `asset.create` step except a folder needs a `content`. It takes one of three forms. | form | means | |-------------------------------------|-------------------------------------------------------------------| | `{"$generate": {…, "as": "image"}}` | Make the file while the job runs. `"as": "text"` is refused here | | `{"mediaRef": "media-7"}` | Keep a file generated in this conversation | | An asset id, or `"$"` | Copy the file of an asset that exists or that another step makes | #### Replace the file of an asset `content` is a field on an `asset.update` as well. Writing it puts a new file into an asset that is already there, in the same three forms. A `$generate` makes one file per element the step touches, the way it makes one sentence per element for a text field. The new file has to be the same kind of asset as the one it goes into, or the step is refused. OpenDXP would otherwise read the new media type after the write and quietly turn the asset into another kind. This is an ordinary field write. It needs the permission to run an update and the right to save that asset, and a review workflow holds it back like any other value. OpenDXP writes a version before it, so the file that was there can be put back as long as the installation keeps enough versions. The summary states the measurements the file had and the ones it gets, so a picture put over a larger one is on screen before anybody approves the plan. It is said where both are known, which is a step naming one element and a file that already exists. ### Routines So far every change was a one-off in the chat. A change you run again is a routine. | way | use it for | |---------|--------------------------------------------------------------------------------------| | Chat | One change, now. Describe it to Genius and approve the plan it builds. | | Routine | A change you run again. Saved with its instruction, its element source and its plan. | A plan built in a chat is kept as a routine too, marked as coming from a chat. Routines live under **Content Crafter > Routines**. A routine holds a name, an instruction, an element source and, optionally, a review workflow. The element source says where the elements come from. | source | means | |------------------|-----------------------------------------------------------------------| | Tree node | Everything below one node, optionally including children and variants | | Selection | The elements handed to it when it is started | | Explorer query | The elements a query finds | | Creates elements | The routine makes elements and is given none | The window suggests instructions. **Show suggestions** puts three examples together out of the classes this installation holds and the fields on them, and clicking one puts it in the instruction field. No model is asked, so they come back at once and say the same thing every time. The element source is not read: a suggestion is always a whole instruction that names the elements it works on. Which wordings there are, and how to add your own, is in [Configuration](01_Configuration.md#suggestions). Saving builds the plan and checks it against the system as it stands. A routine is *Ready* when the plan holds up, and *Blocked* when something in it no longer exists or is not allowed. The problems name the step. Opening a routine later checks it again, so a class that changed since is caught before the routine runs. #### Placeholders A placeholder is written in double brackets and names its type before the colon. There are three. | written | stands for | what becomes of it | |------------------------------|------------------------------|----------------------------------------------------------------------------------------------------------| | `[[gprompt:SeoDescription]]` | A stored wording | Replaced by the wording when the plan is built, see [Generative prompts](#generative-prompts) | | `[[given:locale]]` | The language the step writes | Replaced while the job runs, once per language | | `[[element:object:12]]` | An element of the tree | Stays as it is. The element is looked up and described when the plan is built, see [Elements](#elements) | #### Generative prompts A generative prompt is a stored wording under **Content Crafter > Generative prompts**. An instruction refers to it by its title, and the text is inserted when the plan is built. A title starts with a letter and holds letters, digits and underscores, with no spaces. ``` Write the meta description with [[gprompt:SeoDescription]]. ``` Typing `##` in the instruction field lists the stored prompts and puts the reference in. The chat input has the same list, and without `opendxp_content_crafter_prompts` it stays empty. The wording lands in the one generation the instruction asks it for. Every other generation in the same plan writes an instruction of its own, so a plan that makes a picture and then writes its alt text does not describe the picture with the wording meant for the alt text. `[[given:locale]]` inside a generative prompt is replaced with the language the step writes, so one prompt serves every language. A step that writes no language at all is refused when the wording it uses asks for `[[given:locale]]`. An element reference is refused when the prompt is saved. The wording is put in after the plan is built, later than references are looked up, so a `[[element:object:12]]` typed in here would reach the plan as text. Name the element in the instruction that uses the prompt. #### Elements Drag an element out of the tree into the instruction field and a reference to it is written where the cursor is. Several can be dragged in at once, folders included, out of any of the three trees. ``` Describe every bike under [[element:object:5]] in the tone of [[element:document:12]]. ``` Each one is looked up when the plan is built and handed over as one entry: element type, id, subtype, key, path, and the class of a data object. The same element written twice is one entry. A path typed out by hand works as well. A reference names an element. The instruction around it decides what part the element plays. A folder named as the place for something new becomes the `parentId` of the step that creates it, never the elements a step acts on, see [Targets](#targets). A reference is how a person points at an element while writing, and it never appears in the plan itself. The plan names the id. > [!NOTE] > An element you are not allowed to see counts as gone. A routine whose instruction points at a > deleted element is *Blocked*, the same as one naming a stored wording that is gone. Elements are not in the `##` list, and the field for generative prompts takes no drops. A reference comes out of the tree and nowhere else. #### Start a routine Start a routine from **Content Crafter > Crafter-Interface**. It counts what it would touch first: how many elements are affected and how many model calls that comes to. Both are counted, not estimated. ### Jobs Approving a plan queues a job, and from here on you are watching rather than deciding. A started routine becomes a job on the `content_crafter` transport, and the consumer works through it. ```bash bin/console messenger:consume content_crafter ``` **Content Crafter > Jobs** lists them. A job detail shows the plan, the affected elements, the log, how many elements it got through and how many it left out, and the tokens it spent. #### Units and the job log A job works in units. One unit is one step on one element, in a transaction of its own, together with the steps that step carries. So an element is written whole or not at all, and what was written before it stays written. The log holds a line for every unit, not only for the ones that failed. Each line records the step, the element and what became of it, which is what a job picks up again from. A step that carries steps of its own is one line for the element it stands on, not one line per step underneath. | line | means | |------------------------|---------------------------------------------------------| | Created | The element was made | | Changed | Its values were changed | | Deleted | It was deleted | | Renamed or moved | Its name or its place changed | | Waiting for a reviewer | Its values are held for a reviewer | | Skipped | It failed and somebody chose to carry on without it | | Stopped here | It failed and the job stopped at it | | Cancelled | The job was cancelled, so the rest of the plan was left | Log lines expire, see [Maintenance](60_Maintenance.md#delete-expired-job-log-lines). Those of a blocked job do not, because it continues off them. The job itself stays, with its plan and its affected elements, until somebody deletes it. #### When a job stops Everything a plan can be held to is checked before anybody approves it. A failure while it runs is therefore a defect rather than an expected bad row, and the next element usually fails the same way. The job stops at the element it could not write. Nothing is rolled back. | status | means | |----------------------|--------------------------------------------------------------------------------| | `new` | Queued, not picked up yet | | `processing` | Running | | `complete` | Every element written | | `blocked` | Stopped at an element it could not write, and can be continued | | `partly_errored` | Finished, and somebody chose to carry on without the elements that failed | | `errored` | The plan itself could not be resolved, so nothing ran | | `waiting_for_review` | Nothing written, values are waiting for a decision, see [Review](30_Review.md) | | `canceled` | Cancelled by a person, or submitted by a user who no longer exists | A job is never retried on its own. The transport is configured with `max_retries: 0`, and a blocked job is not picked up again by a second delivery. It continues only when a person says so. Cancelling a job is read when the message reaches the consumer, and again while the job runs. A queued job never starts. A running one stops at the next element rather than in the middle of one, so the element under way is written and the rest of the plan is left. The log says where it stopped. Values it was holding for a reviewer are rejected, and what it wrote stays. #### Continue a blocked job Clear whatever stopped the job, the reason is on the line that says *Stopped here*, and open the job. Three buttons say what should happen to the element it stopped on. The log says what the job already did, so none of that runs a second time, and no model is asked. | choice | what happens | |---------------------------------------|-------------------------------------------------------------------------------| | I fixed it, carry on | That element is tried again, and the next failure stops the job again | | Leave that one out, carry on | That element is written off, and the next failure stops the job again | | Carry on and leave out whatever fails | Nothing stops the job again, and every element it cannot write is written off | > [!CAUTION] > The third choice is behind a confirmation. Nothing asks again after it, so every element the job > cannot write is left out of it. The log says which. A job that left anything out finishes as `partly_errored` rather than `complete`. If nothing about it can be saved, cancel it, word the request so the elements that cannot be written are left out, and start again. > [!IMPORTANT] > A step that names a filter looks that filter up again every time it runs, a continuation included. > It does not carry a list of ids from the moment you approved it. So an element that came to match > while the job stood blocked is written too, and the job can end on more elements than the summary > counted. Nothing it already wrote is written twice: those are in the log and are passed over. > > This matters because a blocked job waits as long as it takes somebody to clear the cause. Where the > set has to be the one you approved, cancel the job and start it again rather than continuing it. ### Next Everything on this page wrote straight away once you approved it. In an installation where content is reviewed, a job writes nothing and holds every value for a reviewer instead, one field at a time. Continue with [Review](30_Review.md). --- ## Review In [Writing](20_Writing.md) every approved plan wrote straight away. With reviews switched on it does not. The job runs, works every value out, and then holds each one until a person decides on it. Nothing reaches an element before that. You will switch reviews on, run a job against your bikes, find its values waiting in **My Reviews**, and decide them one at a time. ### Switch reviews on 1. Under **Content Crafter > Crafter-Settings > Global Settings**, switch on *Enable Workflows*. 2. Create a workflow under **Content Crafter > Workflows**. A workflow is a name, a list of reviewers and a *Notifications* switch that decides whether those reviewers are mailed, see [Maintenance](60_Maintenance.md#notify-reviewers). 3. Assign that workflow in the routine window. *Enable Workflows* is the main switch. While it is off, no job waits for a review, whatever workflow its routine was given. With it on, a job carrying a workflow holds its values, and a job without one writes straight away. Starting a job without a workflow then needs the permission `opendxp_content_crafter_write_without_review`. Without it, a routine without a workflow is refused and Genius does not offer to write at all. > [!NOTE] > Not everything can be held back. Laying out a page writes a draft, which is already a hold, and a > deletion cannot be undone by a reviewer at all. Both are covered in > [What is held back and what is not](#what-is-held-back-and-what-is-not). ### Run a job and see what waits Run something over your bikes, the way [Writing](20_Writing.md) did: ``` Write a short description for every bike under /bikes that has none. ``` Approve the plan. The job runs to the end, calls the model once per bike, and writes nothing. Every description it worked out is now waiting. Open **Content Crafter > My Reviews**. It lists one row per field of whatever a step writes, and one per language where a step writes several. So eleven bikes in two languages are twenty-two rows. You see the workflows you are a reviewer of. An administrator sees all of them. ### Decide a row Select rows to accept or reject them together. Open a row to decide it on its own. A row holds the value as it will be written. The `$generate` and `$transform` ran while the job did, so accepting costs no model call and nothing is worked out at that moment. | button | what it does | |-----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------| | Accept and write | Writes the value now, and a published element shows it at once. The value is editable first, and a rewritten value is recorded as rewritten. | | Accept everything on this element | Writes every field of that element the same job still holds. The element gets one new version, not one per field. | | Reject | Writes nothing. There is nothing to undo. | An accepted value is written as the user who submitted the job, never as the reviewer, see [Rules](00_Rules.md#acting-user). A new element is created unpublished, so publishing it stays a separate decision. A generated image waits as the file itself. Accepting it makes the asset, and the row that links the image to a bike is written afterwards, with the id the asset then has. That ordering is general: rows are written in the order their elements need, so a value that goes on an element another row creates is written after that element exists. Where two rows wait on each other there is no order that writes them, and the accept is refused rather than half done. A row about a tag, a form, an output workflow or a delivery channel is not about an element. It names the row and what it is instead of an element path, and there is nothing to open. > [!NOTE] > Deciding a row takes a lock. If somebody else decided the same row while you had it open, the > accept is refused and asks you to reload, rather than writing over their decision. A job stays at `waiting_for_review` until nothing of it is waiting, however each row was decided. ### What is held back and what is not Steps on objects, documents, assets, tags, forms, output workflows and their delivery channels are held, whether they change something or make it. **Laying out a page is not held.** What it writes lands as a draft, which is a hold of its own, so it runs straight away. Keeping somebody from publishing what was laid out is set up on the document, not here, see [Writing](20_Writing.md#lay-out-a-page). That has a consequence for how a plan may be put together. While workflows are active and you do not hold `opendxp_content_crafter_write_without_review`, a plan either lays out a page or changes content, never both. A plan holding a layout step may then do two things and nothing else: - lay out pages, each writing a draft of its own page - create the very documents those steps lay out, which are left unpublished Anything else in the same plan is refused when the plan is built, naming the step and the way out: run it as a job of its own, let a reviewer approve it, and lay the page out afterwards. Creating a document that no layout step then lays out counts as anything else, so the exception cannot be used to write a document past the review. **A deletion cannot be held back.** Once it has run there is nothing left for a reviewer to approve. So while workflows are active, a plan containing an `object.delete`, `document.delete` or `asset.delete` step is refused when the plan is built, unless you hold `opendxp_content_crafter_write_without_review`. And a job carrying a review workflow refuses such a step, whoever started it. Publishing, unpublishing, renaming and moving are ordinary values that a step writes. They wait for a reviewer like anything else, see [Writing](20_Writing.md#rename-move-publish-or-delete-an-element). ### Notifications A reviewer of a workflow with *Notifications* switched on gets one mail a day while something of theirs is waiting. There is no stock template, and nothing is sent until `notifications.review_email_path` names one, see [Maintenance](60_Maintenance.md#notify-reviewers). ### What is kept Decided proposals stay on the job that made them, with who decided, when, and whether the value was rewritten. You will find them at the bottom of the job detail. Deleting the job removes them. Nothing expires on its own. Files a job generated are held with the job until the job is decided and nothing of it is waiting. A maintenance task clears the held copies out then, and an accepted file lives on as an asset, see [Maintenance](60_Maintenance.md#delete-the-media-a-job-generated). ### Next Reviews leave things behind: decided proposals, held files, job log lines. Three scheduled tasks clear those out and mail the reviewers. Continue with [Maintenance](60_Maintenance.md). --- ## Extending Everything so far worked on data OpenDXP already knows about. This page is where you make your own data available to Genius, for reading and for writing. You will write one tool, watch it register itself, and call it from the workbench without spending a model call. After that comes the list of everything else you can add, grouped by what it changes. Every extension point is an interface. Implement it, and autoconfiguration tags the service for you. Nothing has to be registered by hand. ### Before you start Three things hold for everything on this page and every page under it. - **Your code goes wherever your services already live**, a bundle of your own or the project's `App` namespace. Nothing has to sit in a particular directory. - **Nothing is registered by hand.** `registerForAutoconfiguration()` in `src/OpenDxpContentCrafterBundle.php` lists every interface that is tagged for you. Implement one, and the service is picked up when the container is built. - **You test without a model.** The workbench runs a tool, a field pipeline or a whole plan from the command line, under the permissions of a user you name, see [Debugging](50_Debugging.md). ### The running example Every page under this one extends the same installation, a bike shop, and each adds to what the page before it built. Two things are there already. `Bike` is a data object class carrying the fields a rider asks about. `Dealer` is a Doctrine entity in a table of its own, `bike_dealers`, which OpenDXP does not know about, so nothing in Genius can reach it yet. ### Add your first tool A tool is one invokable service the model can call, and you can test it without calling a model. Three things describe it. `#[AsTool]` defines the name the model uses to call the tool and a description that tells the model when to use it. `#[ContentCrafterTool]` carries the one line the model reads before it has loaded the tool. `getRequiredPermission()` returns the permission a person would need to perform the same action. ```php namespace App\ContentCrafter\Tool; use App\Repository\DealerRepository; use OpenDxp\Bundle\ContentCrafterBundle\Security\Dto\RequiredPermission; use OpenDxp\Bundle\ContentCrafterBundle\Tool\Attribute\ContentCrafterTool; use OpenDxp\Bundle\ContentCrafterBundle\Tool\ToolInterface; use OpenDxp\Bundle\ContentCrafterBundle\Vocabulary\Enum\ContentCrafterPermission; use Symfony\AI\Agent\Toolbox\Attribute\AsTool; use Symfony\AI\Platform\Contract\JsonSchema\Attribute\Schema; #[AsTool( 'count_dealers_in_region', 'Counts the dealers of one region. It does not say which dealers they are, and it does not ' . 'say what they have in stock.', )] #[ContentCrafterTool(summary: 'Counts the dealers of one region.')] final class CountDealersInRegionTool implements ToolInterface { public function __construct(private readonly DealerRepository $dealers) { } public function getRequiredPermission(): RequiredPermission { return RequiredPermission::of(ContentCrafterPermission::Genius->value); } public function __invoke( #[Schema(description: 'the region code, for example "CH-SG"')] string $region, ): array { return ['count' => $this->dealers->countInRegion($region)]; } } ``` You do not have to tag the service. `ToolInterface` is autoconfigured, so any service of this class becomes a tool as soon as the container is built. Check that it arrived: ```bash bin/console debug:container --tag content_crafter.tool ``` #### Call it without a model `workbench/bin/tool.php` only offers the tools listed in `workbench/manifest.json`. Add your own to `manifest.local.json` next to it, which is not tracked by Git. Each entry describes a tool the way MCP does. ```json { "tools": [ { "name": "count_dealers_in_region", "description": "Counts the dealers of one region.", "inputSchema": { "type": "object", "properties": {"region": {"type": "string", "description": "the region code"}}, "required": ["region"] } } ] } ``` ```bash php workbench/bin/tool.php count_dealers_in_region --user=admin --arguments='{"region":"CH-SG"}' ``` The workbench runs under the permissions and the languages of the user you pass to `--user`. A rejection here is the same rejection the model would receive, see [Debugging](50_Debugging.md). That is a working tool. [Add a tool](extending/Tools.md) covers the rest: the two descriptions and when each of them is read, the five arguments of `#[ContentCrafterTool]`, the skill that opens the tool for the model, and what the tools of a query domain have in common. ### What you can add The pages below are grouped by what they change. Each covers one interface, or a set of interfaces that only makes sense together. `registerForAutoconfiguration()` in `src/OpenDxpContentCrafterBundle.php` lists every interface that is tagged for you. To make your data available to queries: - [Add a Query Domain](extending/Query_Domains.md) adds a new domain that can be queried, such as dealers or orders, with its own table and its own permission. - [Add a field to an existing archetype](extending/Fields.md) adds a value that is not in the class definition. It can be read, filtered and written like any other field. - [Support a class definition field type](extending/Field_Types.md) teaches the core a field type it does not recognise, so that field is no longer dropped from the schema. - [Add a filter operator](extending/Filter_Operators.md) adds a word a filter may use, either on one value type or on one field. To make your data writable: - [Add an operation](extending/Operations.md) adds a write that a routine can be built from. You also decide there whether a reviewer can hold the step back, and whether it may delete. - [Add an editable type to page content](extending/Editable_Types.md) adds a type Genius may place when it lays out a page. - [Add a plan check](extending/Plan_Checks.md) refuses a plan whose steps add up to something your data does not allow, while the model can still write it differently. - [Add a translator](extending/Translators.md) puts an outside service behind a `$translate`, instead of the model the bundle ships with. To change what the model and the backend are told: - [Add a tool](extending/Tools.md) adds something the model can call, with the permission a person would need for the same action. - [Change what the model is told about an archetype](extending/Schema.md) changes its name, the guidance on its schema, and how one of your values reaches the model. - [Add a selection action or a context resolver](extending/Chat.md) adds an action the backend offers on selected text, or tells Genius what the open tab means for a request. - [Add a suggestion](extending/Suggestions.md) adds an example instruction the chat and the routine window offer, for the classes your own field is on. - [Keep a field away from the model](01_Configuration.md#protected-fields) removes one of your fields from everything that writes, or from the schema altogether. > [!TIP] > Whatever you are adding, `workbench/bin/explain.php` shows you the result without calling a model. > Run `fields` first when a field you declared does not appear, see [Debugging](50_Debugging.md). #### Where to start The grouping above is for looking something up. Coming to this the first time, read four of them in this order instead. Each one is a walkthrough, and together they take the dealers from unreachable to writable: 1. [Add a Query Domain](extending/Query_Domains.md), so your own table can be asked about at all. 2. [Add a field to an existing archetype](extending/Fields.md), for a value that belongs on a class OpenDXP already has. 3. [Change what the model is told about an archetype](extending/Schema.md), once something is readable and the model keeps misunderstanding it. 4. [Add an operation](extending/Operations.md), when reading is not enough and a routine has to write your data too. The rest are for when you hit them. None of them assumes you read the others. ### Bundles that extend Content Crafter Five bundles do this already. Read them when you want to see an extension point used in anger. | bundle | adds | read | |---------------------------|------------------------------------------------------------------------|-----------------------------------------| | `ecommerce-bundle` | Stores, prices as queryable fields, and its own schema guidance | `src/Bundle/CoreBundle/ContentCrafter/` | | `formbuilder-bundle` | Forms and their submissions as query domains | `src/ContentCrafter/` | | `advanced-seo-bundle` | SEO metadata as fields on every element, and a suggestion about them | `src/ContentCrafter/` | | `toolbox-bundle` | Its own editable types for page content | `src/ContentCrafter/EditableType/` | | `deepl-translator-bundle` | A translator, so a `$translate` runs through DeepL rather than a model | `src/ContentCrafter/` | Each of them names Content Crafter without depending on it: the services live in a file of their own that the bundle loads only where `opendxp_content_crafter` is registered, so the bundle still installs on its own. ### Next Your tool answers one question about dealers, and only that question. To let somebody ask *which dealers stock the City Bike 3 in Sankt Gallen*, the dealers have to become something Genius can query, filter and count for itself. Continue with [Add a Query Domain](extending/Query_Domains.md). --- ## Debugging Almost everything Content Crafter does can be run from the command line, under a user you name, and most of it without spending a model call. That is the workbench: it calls a tool, explains what this installation makes of a plan or a class, puts a prompt to the model, holds a conversation with the chat, and starts a stored routine. It sits in `workbench/` in the repository and is left out of the released package, so no server carries it. This page is what each entry point answers. - [Entry points](#entry-points) - [Run a tool](#run-a-tool) - [Find out why a field is missing](#find-out-why-a-field-is-missing) - [Check a plan](#check-a-plan) - [Have the model build a plan](#have-the-model-build-a-plan) - [Run a chat turn](#run-a-chat-turn) - [Start a routine and decide its held values](#start-a-routine-and-decide-its-held-values) - [Run a plan in a test](#run-a-plan-in-a-test) ### Entry points ```bash php workbench/bin/tool.php --user= [--arguments=] php workbench/bin/explain.php --user= [--arguments=] php workbench/bin/ask.php "" --user= [--arguments=] php workbench/bin/chat.php "" --user= [--conversation=] [--arguments=] php workbench/bin/routine.php --user= [--routine=] [--value=] [--rewritten=] php workbench/bin/runs.php [--cases] ``` > [!WARNING] > `--user` is required, and everything runs under that user's permissions and that user's languages, > see [Rules](00_Rules.md). Each prints one JSON object with `status` first. `--arguments` is the JSON the call takes, one object, named the way the tool or the question names its arguments. `tool.php` and `explain.php` put what they answered under `result`. | entry point | answers | |---------------|---------------------------------------------------------------------------------------------------------------------------------------------------| | `tool.php` | What a tool answers, through the same toolbox and the same permission check the model goes through | | `explain.php` | The seven questions no tool answers: the field pipeline, a page layout, a plan, the two plan schemas, the skills and the parameters of every tool | | `ask.php` | The plan a model works out from a prompt, as the routine window asks for it | | `chat.php` | One turn of the chat, in the conversation it belongs to | | `routine.php` | A stored routine started the way the backend starts it, and the values it holds decided the way a reviewer decides them | | `runs.php` | The runs already recorded against a file of expectations, without a kernel and without a user | `tool.php` offers the tools listed in `workbench/manifest.json`, plus whatever the untracked `manifest.local.json` beside it adds, and refuses everything else. A tool of another bundle goes into the local file, and a tool that costs money stays out of both. The bench itself is described in [workbench/README.md](../workbench/README.md). ### Run a tool ```bash php workbench/bin/tool.php get_object_query_schema --user=admin --arguments='{"className":"Bike"}' php workbench/bin/tool.php query_objects --user=admin \ --arguments='{"className":"Bike","filters":{"weight":{"lte":12}},"countOnly":true}' php workbench/bin/tool.php get_asset --user=admin \ --arguments='{"assetId":170,"fields":["content","pageCount"]}' ``` A query tool takes `filters`, `countOnly`, `sortBy`, `sortDescending`, `groupBy`, `groupGranularity`, `aggregate`, `limit`, `offset` and `fields`, plus whatever its own domain needs. The schema tool of that domain lists the field paths a filter may name. What `groupBy`, `groupGranularity` and `aggregate` do is in [Filters](11_Query_Filters.md#group-the-result). The answer is the one the model would receive, so a value that is only ever shown masked is masked here too. The unmasked reading is the Genius Explorer grid in the backend. ### Find out why a field is missing `fields` maps the field pipeline. Run it first when a field you declared does not show up. ```bash php workbench/bin/explain.php fields --user=admin --arguments='{"domain":"object","type":"Bike"}' php workbench/bin/explain.php fields --user=admin \ --arguments='{"domain":"asset","type":"image","itemType":"AssetMetadataArchetype"}' ``` | what it lists | means | |------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `kept` | The fields the model sees, each with the recognizer and describer behind it, or the provider that declared it, its value type, and whether it can be filtered, sorted, written or nested into | | `takenOverByAProvider` | A reflected member a provider superseded through `Field::$replaces` | | `hidden` | Deliberately kept out, with the reason it was kept out for | | `dropped` | A member no describer claimed, grouped by the recognizer that offered it | `domain` is the name a query domain registered under, so a domain of your own answers here as soon as it is tagged, see [Add a Query Domain](extending/Query_Domains.md). > [!TIP] > `itemType` describes the archetype behind one of the fields instead of the archetype itself, named > by its definition key for a brick or a fieldcollection, or by its class name. The archetypes that > declare themselves in code have no definition key and are reachable no other way. ### Check a plan ```bash php workbench/bin/explain.php plan-schema --user=admin php workbench/bin/explain.php plan --user=admin \ --arguments='{"plan":[{"ref":"s1","op":"object.update","selector":"Bike", "target":{"subject":56},"values":{"color":"black"}}]}' ``` `plan-schema` is the grammar the steps of a plan are written against. `plan-answer` is the whole answer of the writing call. It holds the grammar under `plan`. Without a plan, it holds a reason and a sentence under `say`. A routine can give one reason more than a chat. `{"routine": true}` shows the answer of a routine. `submit_plan` itself writes nothing. It names the operations the plan will use, and the grammar above is cut to those, see [How a change is written](20_Writing.md#how-a-change-is-written). `plan` checks a plan against the system as it stands and writes nothing. It answers `resolved`, the `summary` a person would approve, the `steps` behind that summary and the `impact` the plan would have. A plan that does not hold up comes back as `"resolved": false` with every problem listed, which is what the routine window shows as *Blocked*. > [!NOTE] > An administrator holds every permission, `opendxp_content_crafter_write_without_review` among them. > A plan that a review would refuse therefore holds up under `--user=admin`. Name a user without that > permission to see the refusal, see [Review](30_Review.md). ### Have the model build a plan ```bash php workbench/bin/ask.php "set the navigation title of document 56 to Demo Home" --user=admin ``` The prompt goes to the model the way a routine puts it, and nothing is saved. `outcome` is the first thing the answer says: `plan`, `question`, `refusal` or `fault`. A file of prompts, each with what it was supposed to come to, is run with `--expectations=`. Both are described in [workbench/README.md](../workbench/README.md). > [!CAUTION] > This costs a model call, one per prompt. ### Run a chat turn ```bash php workbench/bin/chat.php "how many bikes are in stock?" --user=admin php workbench/bin/chat.php "and how many of those in red?" --user=admin --conversation=41 php workbench/bin/chat.php "give this page a shorter navigation title" --user=admin \ --arguments='{"type":"document","id":56}' ``` `ask.php` asks the way the routine window asks, `chat.php` asks the way the chat panel asks. A routine has no conversation, a chat has no `scope` and no `entryPointType`. Four things belong to the chat alone: the conversation, what the editor pointed at, generated media and a confirmation somebody answers, see [Asking](10_Asking.md). `--arguments` is what the editor pointed at, `type` and `id`, not the arguments of a call. It goes into the message as a `[[context::]]` token, the way the chat panel writes it. Without `--conversation` every call is a first turn. | field | holds | |----------------|--------------------------------------------------------------| | `conversation` | The id the next call carries on with under `--conversation` | | `answered` | What the chat said | | `type` | `text`, `image`, `audio`, `video`, `chart` or `confirmation` | | `media` | The mime type, where the turn came back with a file | | `awaits` | The message id a confirmation is waiting on | | `affected` | The elements the turn changed | | `calls` | The model calls and the tool calls of the turn, in order | `calls` is written only with `--breakdown`, and only where [`debug`](01_Configuration.md) is on: without it nothing is recorded to write. A turn that comes back as `confirmation` waits, and the bench answers it the way an editor does. ```bash php workbench/bin/chat.php --decide=812 --answer=confirm --user=admin ``` `--decide` is the `awaits` of that turn. `--answer` is `confirm` or `cancel`. Where the confirmation offered a choice or an input, it is one of the offered values, or the words the editor would type instead, which the chat revises from. > [!CAUTION] > A turn costs a model call, and it writes. A confirmed turn runs the tool for real against the > content of this installation, and every turn is saved as a conversation of `--user`. ### Start a routine and decide its held values ```bash php workbench/bin/routine.php preflight --user=admin --routine=7 php workbench/bin/routine.php start --user=admin --routine=7 php workbench/bin/routine.php waiting --user=reviewer php workbench/bin/routine.php accept --user=reviewer --value=312 --rewritten='"A shorter title"' php workbench/bin/routine.php reject --user=reviewer --value=313 ``` | what | it does | |-------------|-------------------------------------------------------------------------------------------------------------------------------------------------------| | `preflight` | Whether the routine may run, how many elements it reaches, whether it would ask for a confirmation, and whether it carries a workflow. Writes nothing | | `start` | Queues the job and answers its `jobId` | | `waiting` | What is waiting in this reviewer's queue: the id to decide with, the element, the field, the language and the state | | `accept` | Writes one held value. `--rewritten` writes what the reviewer put in its place instead, as JSON | | `reject` | Refuses one held value. The element stays as it was | A started job sits on the `content_crafter` transport like any other and is worked off by the consumer, see [Jobs](20_Writing.md#jobs). ```bash bin/console messenger:consume content_crafter ``` The whole run, one command at a time: 1. `start` queues the job. 2. `messenger:consume` runs it. The job reaches `waiting_for_review` and nothing is written. 3. `waiting` names the held value and the id to decide it with. 4. `accept` writes it, and the job is `complete` once nothing of it waits. Only a routine carries a review workflow. A plan built in the chat never does, so a routine is the only way to reach the review side, and `routine.php` is the only way to start one outside the backend. Reviews have to be switched on for anything to wait at all, see [Review](30_Review.md). `waiting`, `accept` and `reject` answer for the reviewer `--user` names, see [Review](30_Review.md#decide-a-row). > [!CAUTION] > This writes. The routine runs against the content of this installation, and every step it holds > back is written the moment somebody accepts it. ### Run a plan in a test `tool.php`, `explain.php` and `ask.php` write nothing. `routine.php` writes. A plan is run against fixture content in the test suite, where `tests/Helpers/content-crafter.php` offers four ways in. | helper | runs | |----------------------------|-----------------------------------------------------------------------| | `runTheJob()` | The job a started routine becomes, with its workflow | | `resumeTheJob()` | A blocked job, with the choice an editor would make in the panel | | `acceptTheHeldValue()` | One value a review is holding back, see [Review](30_Review.md) | | `haveAScriptedAssistant()` | A whole build from prompt to plan, on answers written down in advance | `grabJobLog()` gives the type of every log line in the order the units ran, which is how a test says what a job did, see [Jobs](20_Writing.md#units-and-the-job-log). `haveAScriptedAssistant()` points the Assistant role at a platform that hands back the results it was given, one per call, so a build runs with nothing going over the network. It returns the script, which records the messages and the options of every call. ```php $script = haveAScriptedAssistant([ new ToolCallResult([new ToolCall('looked-up', 'list_object_classes', [])]), new TextResult('{"answer": {"plan": [{"ref": "one", "op": "object.update"}], "say": null}}'), ]); ``` The call that writes the plan carries its tools and its response schema at once, so a scripted answer is either a tool call it makes on the way or the finished answer under `answer`. --- ## Maintenance Once jobs have been running for a while they leave things behind: log lines, the files a job generated, and reviewers who have not been told that something is waiting for them. The bundle registers three maintenance tasks for that, and they run with the OpenDXP maintenance run. Nothing else of the bundle expires on its own. On this page you will see what each task does, which of them needs a setting before it does anything, and what none of them touches. | task | does | to set | |-----------------------------------|--------------------------------------------------|-----------------------------------| | `content_crafter_notification` | Mails reviewers that values are waiting for them | `notifications.review_email_path` | | `content_crafter_generated_files` | Removes the media a decided job generated | nothing | | `content_crafter_job_logs` | Deletes job log lines past their age | `jobs.log_expiration_days` | Both keys live in `content_crafter.yaml`, see [Configuration](01_Configuration.md). A task that fails writes the failure to **Tools > Application Logger** under the component `content_crafter` and lets the maintenance run carry on. What a task removed is written there too, so that log is where you look when you want to know whether anything happened. ### Run one task on its own You do not have to wait for the maintenance run to see a task work: ```bash bin/console opendxp:maintenance --job=content_crafter_job_logs ``` The command puts the task on the `opendxp_maintenance` transport, so a consumer has to be running for it to happen. Without `--job` every registered task of the installation is queued. ### Notify reviewers `content_crafter_notification` mails a reviewer once a day, however much is waiting. A reviewer is mailed when a workflow they are on has *Notifications* switched on and holds at least one value that is still waiting. Reviewers of a workflow without the switch are never mailed, see [Review](30_Review.md#switch-reviews-on). The task records the moment it sent something and does nothing while that is less than a day old. A run that reached nobody is not recorded, so the next one tries again instead of waiting another day. > [!IMPORTANT] > There is no stock template. `notifications.review_email_path` has no default, and while it is > unset the task logs an error and sends nothing at all. The path names an email document. It is rendered with one parameter, `user`, the reviewer as a `User` object. The mail says nothing about what is waiting unless the template works it out itself. A reviewer without an email address is skipped and logged. ### Delete the media a job generated `content_crafter_generated_files` removes the media a job generated while it ran. Nothing about it can be set. A file is removed once both hold: - the job is decided, meaning `complete`, `canceled`, `errored` or `partly_errored`. A `blocked` job is not decided: its files are held until it is continued or cancelled - no value of that job is still waiting for a review The file is held in the database row, so deleting the row is what frees the space. An accepted image lives on as an asset of its own and is not affected, see [Review](30_Review.md#what-is-kept). ### Media generated in the chat This one is not a task, and that is the point. `generate_image`, `edit_image` and `generate_speech` attach their file to the conversation, not to a job. No maintenance task touches it. It belongs to the transcript and stays as long as the conversation does. Deleting a conversation deletes its messages, its generated media and its grids with it. That is the way to get the space back. A conversation is deleted from **My Genius > Conversations** by the user who had it, see [Asking](10_Asking.md#where-your-conversations-go). Nobody else can delete it, an administrator included. ### Delete expired job log lines `content_crafter_job_logs` deletes log lines older than `jobs.log_expiration_days`, 30 days by default. It touches nothing else of the job, see [Jobs](20_Writing.md#jobs). The lines of a `blocked` job never expire. They are what it continues from, and a job can stand blocked for as long as it takes somebody to clear the cause. ### Next That is Content Crafter as a product, from asking a question to clearing up after a job. Everything you needed was in the backend. What follows is for developers. [Extending](40_Extending.md) is where you make Genius answer and write about data it knows nothing about yet, and from there on you are writing PHP rather than clicking. If that is not your job, you are done here. --- ## Testing A bundle or a project that extends Content Crafter can test what the assistant does with its data. The test API calls a tool and runs a plan the way the assistant does, but without a model. It lives under `OpenDxp\Bundle\ContentCrafterBundle\Test`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Setup To use the expectations, register them once in your `tests/Pest.php`: ```php OpenDxp\Bundle\ContentCrafterBundle\Test\Expectation\Jobs::register(); ``` ### Testing your tools and plans Every call runs as the user that [`Admin::actingAs()`](https://github.com/open-dxp/test-foundation#the-logged-in-user) names. A test of the permissions therefore only picks another user. ```php use OpenDxp\Bundle\ContentCrafterBundle\Test\Plans; use OpenDxp\Bundle\ContentCrafterBundle\Test\Tools; use OpenDxp\Bundle\ContentCrafterBundle\Tool\Object\GetObjectTool; use OpenDxp\Test\Factory\UserFactory; use OpenDxp\TestFoundation\Admin; beforeEach(function () { Admin::actingAs( UserFactory::new() ->admin() ->create(), ); }); it('reads the name of a bike', function () { $bike = BikeFactory::createOne(['name' => 'Trail 29']); $read = Tools::call(GetObjectTool::class, [ 'objectId' => $bike->getId(), 'fields' => ['name'], ]); expect($read['name'])->toBe('Trail 29'); }); it('writes the new name of a bike', function () { $bike = BikeFactory::createOne(['name' => 'Trail 29']); $job = Plans::run([ [ 'ref' => 'bike', 'op' => 'object.update', 'selector' => 'Bike', 'target' => ['subject' => $bike->getId()], 'values' => ['name' => 'Trail 29 Pro'], ], ]); expect($job)->toHaveRunClean(); }); ``` `BikeFactory` is a factory of your project. A plan is the list of steps that the assistant writes. [Writing](20_Writing.md) describes plans. A test writes the same steps by hand. ### Test API | Class | What it gives you | |-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Test\Tools` | `call()` calls a tool with the arguments the model would send and returns what the tool returns. `answer()` returns the text the model reads back, after the normalizers and under the permission of the tool. | | `Test\Plans` | `check()` resolves a plan and throws the refusal the assistant would get. `refusal()` returns that message, and `problems()` returns each problem on its own. `run()` runs the plan at once, without the queue, and returns the job. `runUnderReview()` does the same under a workflow, so the values wait for its reviewers. | | `Test\Expectation\Jobs` | The Pest expectations `toHaveRunClean`, which says that the job logged no problem, and `toHaveLogged`, which compares the types of the log entries in their order. | For example, a test checks `expect($job)->toHaveLogged('modified', 'modified')`. ### The suite of this bundle - `tests/Unit` tests the parts that need no installation. - `tests/Feature` holds a folder for each part of the bundle, like `Explorer`, `Plan` or `Review`. - `tests/Story` builds the shared data: `Workshop` with its products, categories, a page and an image, and `WorkshopTree`, which adds folders and nested pages. - `tests/Application` holds the classes of the test installation. No test calls a model. A test that needs an answer scripts it with the test engine of the bundle. --- ## Changelog(Content-crafter) ### 2.1.3 - [BUGFIX] Genius reads a class whose field has a tooltip longer than 190 characters - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 2.1.2 - [BUGFIX] The migrations of other bundles run while the tables of 1.x are still there - [BUGFIX] An installation of 1.x counts as installed, so a deploy runs the migrations to 2.x - [DEPRECATION] `RetiredTableFilter` is deprecated. 3.0 removes it ### 2.1.1 - [BUGFIX] Genius asks what should happen to attached elements when the message leaves it open - [BUGFIX] A new Genius conversation starts with the context of the open tab - [BUGFIX] Genius shows the approval of a plan in the language of the backend - [NEW FEATURE] The job view analyses a stopped job on request: the cause, and the fix where one is known, in the language of the backend - [ENHANCEMENT] [FOLLOW-UP] [MIGRATION] A job log names what gets a person out of a halt, where the cause has a known way out 1. Run `bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\ContentCrafterBundle\Migrations'`. - [BUGFIX] A job whose plan cannot be read says so and names what helps - [BUGFIX] Genius refuses a plan that writes the same as a job of the conversation that is not through yet - [BUGFIX] Genius sees the jobs of its conversation as they stand now, not as "running" forever - [BUGFIX] A job log says why a job stopped as plain facts for a person, without instructions meant for the model - [ENHANCEMENT] Genius reads a job with `get_job` - [ENHANCEMENT] The job views offer exactly the actions the server allows for a job - [BUGFIX] [MIGRATION] The job view pages through the log of a job instead of loading every line at once - [BUGFIX] The job list pages through its jobs - [BUGFIX] A running job cannot be deleted - [BUGFIX] Genius sends a turn back that announced a write and stopped before it read the schema of what it writes - [BUGFIX] A plan writes an item that names its own language once and in that language, such as an asset or SEO metadata item - [ENHANCEMENT] `LocalizedStageableOperationInterface` lets an operation split the values a reviewer gets into one pass per language. See [Operations](docs/extending/Operations.md#review-support) - [BUGFIX] A user without the jobs right reads the jobs they started, in the job view and in Genius. The job list and continuing, cancelling or deleting a job still need the jobs right - [ENHANCEMENT] Genius answers how a started job stands and why it stopped with the new skill `check-jobs` - [ENHANCEMENT] An open job view is the context of a Genius message, like an open element - [ENHANCEMENT] A context resolver implements `WritableContextInterface` when a plan can change what it describes. Only then Genius asks what should happen to it. See [Add a context resolver](docs/extending/Chat.md#add-a-context-resolver) - [BUGFIX] Genius keeps a context per outer tab, so a tab brings its context back when it is shown again. `setActiveContext()` and `clearActiveContext()` take the panel the context belongs to - [ENHANCEMENT] Genius warns in the log about a tool that no skill opens. See [Name the tool in a skill](docs/extending/Tools.md#name-the-tool-in-a-skill) - [BUGFIX] Genius reaches `get_plan_schema` in a conversation through the skill `write-content` - [CHORE] Conflict with `open-dxp/formbuilder-bundle` <1.3.1 ### 2.1.0 - [BUGFIX] Genius asks for the approval of a plan that it writes on its second try - [BUGFIX] A plan creates folders in the object tree - [BUGFIX] Genius builds a plan for a request to move or mark elements instead of stopping after the lookup - [NEW FEATURE] A plan adds notes to elements. See [Writing](docs/20_Writing.md#what-a-step-can-write) - [ENHANCEMENT] A plan writes a predefined property under its key, and checks its value against the type of the property - [ENHANCEMENT] Genius names a new property in English lowercase snake_case, unless the request gives the name - [BUGFIX] A plan writes the language and the navigation of a document as its settings and not as free properties - [BUGFIX] An object or an asset shows a property named like a document setting, such as `language`, among its properties - [ENHANCEMENT] `ItemIdentity` marks rows that are added but never changed or removed. See [Fields](docs/extending/Fields.md) - [BUGFIX] Genius gets consistent instructions that match the installation. See [Skills](docs/01_Configuration.md#skills) - [ENHANCEMENT] A routine hands an open decision back to the author of its prompt - [BUGFIX] A plan adds a brick only where the area allows its type and has room for it - [BUGFIX] A plan writes a video only of a type the field allows - [BUGFIX] A tag rename takes a name, not a path - [BUGFIX] Navigation anchors and parameters keep their "#" and "?" - [BUGFIX] Genius counts tagged elements per tag - [BUGFIX] Genius finds top-level tags, asset metadata and elements in one of several workflow places - [BUGFIX] Genius lists the options of select fields in object bricks and field collections - [BUGFIX] Genius translates catalogue keys with the translator - [BUGFIX] Genius always tells an editor without a right that an administrator grants it - [BUGFIX] Genius answers in the language of the person after a plan is confirmed - [BUGFIX] Genius reads a placeholder in the addresses of an email document. Every address stays masked - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [CHORE] [FOLLOW-UP] Require `symfony/ai-bundle` and `symfony/ai-agent` ^0.15 1. Only if your project requires a platform bridge itself, for example `symfony/ai-open-ai-platform`: raise it to ^0.15. - [BUGFIX] Genius keeps the related elements the user may not view when it writes a relation - [ENHANCEMENT] A relation shows a target the user may not view by its type and id. Filters count such a target. See [Permission and visibility](docs/00_Rules.md#permission-and-visibility) - [BUGFIX] A filter on a reverse relation finds the elements that point back - [BUGFIX] A filter on a relation inside localized fields reads the language of the query - [BUGFIX] Genius reads and writes the columns of a relation with columns - [BUGFIX] Genius reads the rows of a block field - [BUGFIX] The `workflow` field shows the place of the element in each workflow - [ENHANCEMENT] A field with a list of rows, such as a relation, shows its first 20 rows and their total. The new tool `list_relation_items` returns the next rows - [ENHANCEMENT] `list_field_options` and the options in the query schema use the same form - [ENHANCEMENT] A describer can mark a field as a code. The model then sees only its last four characters. See [Fields](docs/extending/Fields.md) - [ENHANCEMENT] Genius shows up to five rows of an answer in the chat. More rows open in Genius Explorer. See [Asking](docs/10_Asking.md#see-the-rows-of-an-answer) - [BUGFIX] [FOLLOW-UP] [MIGRATION] Genius Explorer shows the rows, the fields and the order the query asked for 1. Run `bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\ContentCrafterBundle\Migrations'`. - [BUGFIX] A sort by a field of related rows ranks an element by its highest or its lowest value. See [Filters](docs/11_Query_Filters.md#sort-by-a-field-of-the-rows) - [ENHANCEMENT] A bundle names and opens the rows of its domain and renders the value of a field. See [Query Domains](docs/extending/Query_Domains.md#name-and-open-a-row) - [DEPRECATION] `AbstractQueryTool::clampLimit()` and `AbstractQueryTool::MAX_LIMIT` are deprecated. 3.0 removes them ### 2.0.0 - [BC BREAK] [MIGRATION] The AI layer runs on symfony/ai, and routines replace the presets. Nothing from 1.x converts automatically, see [Upgrading to 2.0](docs/Upgrading_to_2.0.md) 1. Assign the new permissions under **Settings > Users**. The migration creates them but does not hand them out. 2. Install a vendor platform bridge, for example `symfony/ai-open-ai-platform`. 3. Configure your platforms in the `ai.yaml` of symfony/ai. 4. Only if `config/bundles.php` registers `symfony/ai-bundle`: remove it there. This bundle registers it. 5. Open **Content Crafter > Crafter-Settings > Engines** and assign at least the `assistant` role. Nothing runs without it. 6. Only if `content_crafter.yaml` sets `opendxp_content_crafter.enabled`: remove the key. 7. Write your jobs again as routines. - [NEW FEATURE] Routines: a prompt in plain language, compiled once into a plan, saved and started when needed, see [Routines](docs/20_Writing.md) - [NEW FEATURE] Genius: a conversational assistant in the backend that reads, searches and writes content through the same plan a routine uses, see [Genius](docs/01_Configuration.md) - [ENHANCEMENT] Before a job runs, it shows how many elements and how many model calls it needs. Afterwards it shows the tokens it spent ### 1.1.3 - [ENHANCEMENT] Add php 8.5 support [#8](https://github.com/open-dxp/content-crafter-bundle/pull/8) - [CHORE] Remove Quill editor support and related assets [#9](https://github.com/open-dxp/content-crafter-bundle/pull/9) ### 1.1.2 - [BUGFIX] Update `classId` parameter to ensure correct handling of string based class definitions [#7](https://github.com/open-dxp/content-crafter-bundle/pull/7) ### 1.1.1 - [NEW FEATURE] Add `headless_bundle` support and JSON text extraction in DocumentPagePlaceholder [#6](https://github.com/open-dxp/content-crafter-bundle/pull/6) ### 1.1.0 - [NEW FEATURE] Add CSV and Input-based Selections for Element Import [#3](https://github.com/open-dxp/content-crafter-bundle/pull/3) - [CHORE] Update template namespace and switch to ArrayCollection for query parameters [#4](https://github.com/open-dxp/content-crafter-bundle/pull/4) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Change namings [#1](https://github.com/open-dxp/content-crafter-bundle/pull/1) --- ## Content Crafter Bundle Content Crafter reads and changes content in OpenDXP through a language model. Editors ask questions about their data in a chat, and describe changes that the bundle turns into a plan, runs as a job, and optionally holds for review. | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **2.x** | `1.x` | `7.4` | -- | Feature Branch | 2.x | | **1.x** | `1.x` | `7.4` | -- | No | 1.x | ### Requirements - OpenDXP 1.x with the Admin bundle - A `symfony/ai` platform bridge for your model vendor, for example `symfony/ai-open-ai-platform` - A Messenger consumer for background jobs `symfony/ai-bundle` ships with this bundle and registers itself. Do not add it to `bundles.php`. ### Installation ```bash composer require open-dxp/content-crafter-bundle ``` Add the bundle to `config/bundles.php`: ```php return [ OpenDxp\Bundle\ContentCrafterBundle\OpenDxpContentCrafterBundle::class => ['all' => true], ]; ``` Create the tables and register the permissions: ```bash bin/console opendxp:bundle:install OpenDxpContentCrafterBundle ``` The installer refuses to run when any of the bundle's tables already exist. Upgrading from 1.x uses migrations instead: ```bash bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\ContentCrafterBundle\Migrations' ``` Read the [changelog](CHANGELOG.md) and [Upgrading to 2.0](docs/Upgrading_to_2.0.md) before upgrading. Almost nothing from 1.x survives unchanged. Install the backend assets: ```bash bin/console assets:install public --relative --symlink ``` ### First run Declare a platform and a model in `config/packages/ai.yaml`: ```yaml ai: platform: openai: api_key: '%env(OPEN_AI_API_KEY)%' agent: content_crafter_chat: platform: 'ai.platform.openai' model: 'gpt-5-mini' ``` Open **Content Crafter > Crafter-Settings > Engines** and assign a model to the *Assistant* role. Nothing runs without it, see [Engines](docs/02_Engines.md). Grant the permissions your users need under **Settings > Users**. A fresh installation grants none, see [Configuration](docs/01_Configuration.md). Run the consumer that carries out jobs: ```bash bin/console messenger:consume content_crafter ``` ### Documentation Everything is documented under [docs](docs/README.md), which names the order to read it in. Four places to start: - [Asking](docs/10_Asking.md) is the first guide. Open the chat, ask a question, read the answer. Nothing it does changes any content. - [Writing](docs/20_Writing.md) follows it: how a sentence becomes a plan, a routine and a job. - [Configuration](docs/01_Configuration.md) lists every configuration key and every permission. - [Extending](docs/40_Extending.md) is where a developer makes their own data readable and writable. ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. This bundle is licensed under the GNU General Public License version 3 (GPLv3), see [LICENSE.md](LICENSE.md). --- ## Upgrading to 2.0 Two things happened at once. The AI layer moved onto [symfony/ai](https://symfony.com/doc/current/ai/index.html), and the preset was replaced by the routine. Almost nothing from 1.x survives unchanged. **Read all of it before upgrading a production instance.** There is no automatic conversion from presets to routines. A preset described one field of one element type, a routine describes a whole job, and no rule turns the first into the second. #### Getting back to a working setup 1. `bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\ContentCrafterBundle\Migrations'` 2. Assign the new permissions under **Settings > Users**. The migration creates them, it does not hand them out. Until an administrator does, an editor who worked with the bundle in 1.x sees nothing of routines, Genius or the review 3. Install a vendor platform bridge, e.g. `symfony/ai-open-ai-platform` 4. Configure your platforms in symfony/ai's own `ai.yaml`. `symfony/ai-bundle` itself is registered by this bundle, so take it out of `config/bundles.php` if you put it there 5. Open **Content Crafter > Crafter-Settings > Engines** and assign at least the `assistant` role. Nothing runs without it 6. Write your jobs again as routines A fresh installation does not use the migrations at all. It runs `bin/console opendxp:bundle:install OpenDxpContentCrafterBundle`, which builds the schema from the Doctrine mappings and registers the permissions. The installer refuses to run once any of the bundle's tables exist, so an upgrade stays on `doctrine:migrations:migrate`. ### Removed Concepts / Modules #### Presets, contract nodes, prompts, conversations The whole per-field generation stack is removed: `Preset`, `ContractNode`, `Conversation`, `Prompt`, `PromptMetadata` and their tables, plus the preset tree panel, and the `create`/`update` split in the dispatcher. **Instead:** a routine. A prompt in plain language, compiled once into a plan, saved, started when needed. It is not bound to a field or an element type. One routine can write several fields, create elements and change a whole set in one run. See [Routines](20_Writing.md). #### The `ai_engine` configuration tree `opendxp_content_crafter.ai_engine` is gone, with its `pricing`, `option_providers` and engine types. So are `config/quickstart/*.yaml`. **Instead:** platforms and models come from `ai.yaml`, and which of them answers for which role is assigned in the backend under **Crafter-Settings > Engines**. Six roles: assistant, content, utility, vision, image, audio. Only `assistant` has to be set. See [Engines](02_Engines.md). It moved out of YAML because swapping a model is an operating decision, and the person who makes it is not the person who deploys. #### The hand-rolled AI client `openai-php/client`, `src/OpenAI/`, `GptChatProvider` and friends, the OpenAI Assistants/Threads support, the "System" settings tab with its API key fields, `yethee/tiktoken`. **Instead:** symfony/ai. #### Data type nodes and placeholders `DataTypeNode`, the node builders, `##` placeholders in prompts, `PresetOptionProviderInterface`, `docs/10_CustomDataNode.md`, `docs/20_CustomPlaceholder.md`. **Instead:** the plan addresses fields by their real names, resolved from the class definition and checked before anything is written. There is nothing to register per field type. #### Estimated costs The cost estimate shown during preflight is gone, along with `Preset::$estimatedResponseLength` and the `pricing` blocks. **Instead:** two counted numbers before a job runs, how many elements and how many model calls, and the tokens it actually spent afterwards, on the job. #### `operationType` on a contract Told update jobs from create ones. A preset did one or the other, a plan does both at once, so the column held the same value on every row. Nothing replaces it. #### `opendxp_content_crafter.enabled` The flag was meant to hide the bundle's menu, and never did. The backend sent it nested under `settings`, the JavaScript read it one level above that, so the check never matched and the menu always appeared. Remove the key from `content_crafter.yaml` if you set it. To keep the bundle out of a backend, take the permission `opendxp_content_crafter` away from the users instead. ### New #### Genius A conversational assistant in the backend. It reads and searches content, and writes through the same plan a routine uses, so a sentence typed in a chat and a saved routine end up as the same job. A plan approved in a chat is kept as a routine too, always marked as a one-off. See [Genius](01_Configuration.md). #### New permissions | | | |---------------------------------------------------------------------|----------------------------------------------------------------| | `..._routines`, `..._routines_edit`, `..._routines_delete` | the routine list, writing one, deleting one | | `..._prompts`, `..._prompts_edit`, `..._prompts_delete` | the generative prompts | | `..._routine_from_chat` | letting Genius build and submit a plan | | `..._execute_update`, `..._execute_create` | running a job that changes, or that creates | | `..._write_without_review` | running a job with no review workflow, where jobs are reviewed | | `..._genius`, `..._genius_settings`, `..._genius_selection_actions` | the chat and its settings | | `..._settings_engines` | the engine assignment | **Removed:** `..._preset_configuration`, `..._settings_system`, `..._trainer`, `..._dispatcher`. #### Two settings moved into the backend **Crafter-Settings > Engines** for the role assignment, and **Crafter-Settings > Global Settings** for whether jobs are reviewed and from how many elements one has to be confirmed before it starts. The default is 50. ContentCrafter 1.x Upgrade Notes: https://github.com/open-dxp/content-crafter-bundle/blob/1.x/UPGRADE.md --- ## Add a Selection Action or a Context Resolver The dealers can be queried and written by now, and the chat still treats them like anything else. An editor with a dealer open on screen has to say which one, and selecting a line of its description offers them nothing. Two small interfaces close that gap, and they are independent of each other. A **context resolver** says what the open tab means, so *change the headline of this page* works with nothing dragged in. A **selection action** is what the backend offers on text an editor has selected. Take whichever you need. - [Add a context resolver](#add-a-context-resolver) - [Add a selection action](#add-a-selection-action) ### Add a context resolver `ContextResolverInterface` turns *the editor pointed at something of this type* into a sentence the model can act on. Without one the context says a type and a number, and the model has to look the thing up before it can answer anything about it. The chat panel writes what the editor points at into the message, as a `[[context::]]` token. `describe()` is given that type and that id and nothing else. Read anything narrower, a variant or a class or a file type, off the element itself. A resolver also implements `WritableContextInterface` when a plan can change the thing it describes. ```php final readonly class DealerContextResolver implements ContextResolverInterface, WritableContextInterface { public const string TYPE = 'bike_dealer'; public function supports(string $type): bool { return $type === self::TYPE; } public function describe(string $type, string|int|null $id): string { $dealer = $id === null ? null : $this->entityManager->getRepository(Dealer::class)->find((int) $id); if (!$dealer instanceof Dealer) { return 'the dealer list, with no specific dealer open'; } return sprintf( 'the bike dealer "%s" (id %d) open in the editor. Query it with the dealer tools, not ' . 'the document or object tools', $dealer->getName(), $dealer->getId(), ); } } ``` > [!TIP] > The sentence is put into the turn as it stands, so write it as the end of *the editor pointed at > …*. Ending it with which tools to use is what stops the model reaching for the document tools on > something that is not a document. The resolver is half of it. The chat panel writes the token for objects, documents and assets by itself, and for nothing else. Your own type needs the panel told about it, from your bundle's own JavaScript: ```javascript var genius = opendxp.globalmanager.get('content_crafter_genius'); if (genius) { genius.setActiveContext({type: 'bike_dealer', id: dealerId}, this.panel); } ``` The second argument is any panel inside your tab. Genius keeps one context per outer tab and shows it whenever that tab is active. `clearActiveContext(this.panel)` removes it while the tab stays open, and closing the tab removes it by itself. `type` is the same string `supports()` answers to. Check for the manager: it is not there when Content Crafter is not installed. Without this call the resolver is never asked. ### Add a selection action A selection action appears when an editor selects text in a field. The bundle ships one, `RewriteTextAction`, which rewrites the selection. Your own does whatever your project needs: here, one that puts a dealer description into the house wording. Which actions are offered, and which engine answers each, is set under **Content Crafter > Crafter-Settings > Genius Settings**, see [Configuration](../01_Configuration.md). ```php final readonly class DealerToneAction implements SelectionActionInterface { public function __construct(private ResultTextReader $textReader) { } public function getName(): string { return 'dealer_tone'; } public function getLabelKey(): string { return 'bike_dealer.action.house_tone'; } public function getEngineRole(): EngineRole { return EngineRole::Content; } public function getResultBehavior(): SelectionActionResultBehavior { return SelectionActionResultBehavior::ReplaceSelection; } public function getDefaultPromptTemplate(): string { return "Rewrite this dealer description in our house wording. Always name the shop as " . "\"Cycle Works\", keep it under 40 words, return only the text:\n\n{{selection}}"; } public function generate(ChatMessage $message, AgentInterface $engine, string $effectivePrompt): ChatResponse { $prompt = str_replace('{{selection}}', $message->getSelection() ?? '', $effectivePrompt); return ChatResponse::text($this->textReader->read($engine->call(new MessageBag(Message::ofUser($prompt))))); } } ``` | method | answers | |------------------------------|-----------------------------------------------------------------------------------------------------| | `getName()` | The name the setting and the frontend use | | `getLabelKey()` | The translation key of what the editor reads on the chip | | `getEngineRole()` | Which role of work this is, so the settings offer models that can do it | | `getResultBehavior()` | `ReplaceSelection` puts the answer in place of the selected text, `ChatMessage` puts it in the chat | | `getDefaultPromptTemplate()` | The wording used until an administrator changes it | | `generate()` | The call itself, given the message, the engine and the effective prompt | `{{selection}}` is the selected text and `{{input}}` what the editor typed in the chat. An administrator rewrites the template without a deployment, so read it from `$effectivePrompt` rather than from your own method. `getEngineRole()` decides what the settings page offers for this action: the agents this installation has built whose model declares a capability of that role, see [Engines](../02_Engines.md). `generate()` is handed the engine already resolved from the setting, so an action never picks a model itself. `getResultBehavior()` also decides where the action is offered. A `ReplaceSelection` action appears only on a selection that can take the answer back, which is a field the editor may write in, and never on a grid cell or a label. While it runs, that field shows it rather than the chat. ### Next The chat now knows what an editor is looking at. The last thing it can learn from you is what to suggest before they have typed anything. Continue with [Add a suggestion](Suggestions.md). --- ## Add an Editable Type to Page Content Genius lays out a page by writing editables, see [Writing](../20_Writing.md#lay-out-a-page). It can only write the ones it understands, and an editable whose type nothing speaks for is left exactly as it was. Your project's own brick is invisible to it. An editable type is what teaches it one. It says how one editable is read, and how a written value becomes the data the editable stores. You will write one for the shop's bike teaser, so Genius can place it on a page and fill it in. - [Write the editable type](#write-the-editable-type) - [Declare the shape it takes](#declare-the-shape-it-takes) - [Refuse a value](#refuse-a-value) - [Read the value back](#read-the-value-back) - [Extend a type the core already has](#extend-a-type-the-core-already-has) - [See what a page offers](#see-what-a-page-offers) ### Write the editable type Three methods carry the work, and the page takes them one at a time: the shape a value may have, whether this instance accepts it, and what a read hands back. ```php final class BikeTeaserEditableType implements EditableTypeInterface { private const array PARTS = ['bikeId', 'headline', 'showPrice']; public function supports(string $type): bool { return $type === 'biketeaser'; } public function describeWriteShape(): array { return [ 'type' => 'object', 'additionalProperties' => false, 'required' => self::PARTS, 'properties' => [ 'bikeId' => ['type' => 'integer'], 'headline' => ['type' => ['string', 'null']], 'showPrice' => ['type' => ['boolean', 'null']], ], ]; } public function describe(array $config): string { return 'the bike to show off in this spot: {"bikeId": 42, "headline": "Built for gravel", ' . '"showPrice": true}. "bikeId" is the id of a Bike object, "headline" is one short ' . 'line above it, and "showPrice" decides whether the price is printed'; } public function read(Editable $editable): mixed { $data = $editable->getData(); return is_array($data) ? array_intersect_key($data, array_flip(self::PARTS)) : null; } public function resolve(mixed $value, ?Editable $current, array $config): ResolvedSetting { if (!is_array($value) || !isset($value['bikeId'])) { return ResolvedSetting::rejected('takes a bike to show, e.g. {"bikeId": 42, "headline": "Built for gravel"}.'); } $unknown = array_diff(array_keys($value), self::PARTS); if ($unknown !== []) { return ResolvedSetting::rejected(sprintf('was given "%s". It takes "%s".', implode('", "', $unknown), implode('", "', self::PARTS))); } return ResolvedSetting::of([ 'bikeId' => (int) $value['bikeId'], 'headline' => (string) ($value['headline'] ?? ''), 'showPrice' => (bool) ($value['showPrice'] ?? false), ]); } } ``` | method | answers | |------------------------|---------------------------------------------------------------------------| | `supports()` | The editable type name, as the template writes it | | `describeWriteShape()` | The JSON schema of one value of this type | | `describe()` | What this spot takes, in the words the model reads. `null` to say nothing | | `read()` | What the page holds here right now | | `resolve()` | What a written value becomes, or why it is refused | The two descriptions divide the work. `describeWriteShape()` says what is well formed, once for the type. `describe()` says what is allowed at this spot. It is given the editable's own config as the template set it, so it can name the choices this one instance offers. ### Declare the shape it takes The layout grammar holds a scalar, a list of values, and every shape the registered types declare. Nothing else. A type cannot decline to declare one: `describeWriteShape()` has no default on the interface, so a type that does not answer it does not load. A shape the grammar does not carry is a shape nothing tells the model about. What it writes instead is refused, or arrives at `resolve()` as `null`, which looks the same as an editor clearing the field. See [The plan grammar](Plan_Grammar.md). | the type holds | it declares | |--------------------------------------|----------------------------------------------------------| | One line of text | `['type' => ['string', 'null']]` | | An id, or an object naming that id | The two under one `anyOf` | | A list of them | `['type' => 'array', 'items' => [...]]` | `EditableTypeResolver::listWriteShapes()` collects them, unfolds an `anyOf` into its branches and drops duplicates, so a type whose value looks like one the core already declared costs the grammar nothing. > [!IMPORTANT] > Every property of an object shape stands in `required` on the way out and the object is closed, so > the model writes every key and fills the ones that do not apply with `null`. `resolve()` has to > tell a `null` from a key that is not there. A `required` naming a property the shape does not > declare is discarded. The strict pass rewrites `required` to the properties that are there, so the > key you meant to add stays unwritable and nothing says so. > [!NOTE] > `InputEditableType` is the shortest one, `ImageEditableType` the shortest with a choice of shapes. > Both are in `src/Authoring/Layout/EditableType/`. ### Refuse a value `ResolvedSetting::rejected('…')` carries the reason back to the model, which corrects itself before anything is written. `ResolvedSetting::of($data)` carries the data. `null` is a value that can be stored, so a refusal cannot be signalled by returning nothing. That is why the two are separate methods. Write the refusal as the end of a sentence starting with the field's name: *takes a bike to show, e.g. …*. ### Read the value back `read()` has to hand back a value `resolve()` would accept. It is what the model is shown when it reads the page, and a page is corrected by copying that value back into the plan with one thing changed. A read that names a key differently from the write, `type` where the write takes `elementType`, turns every correction of that field into a refusal. The three methods fit together. `describeWriteShape()` is the widest a value may be, `resolve()` decides whether this instance takes it, and `read()` hands back something both would accept again. A class definition field type declares its shape the same way, see [Field Types](Field_Types.md#declare-the-shape-of-a-value-that-is-not-a-scalar). ### Extend a type the core already has Where your type is the core's plus a setting, extend the core's editable type rather than starting over. Two things carry the new key: the keys the type accepts, and the sentence the model reads. Everything else is inherited. ```php final class BikeVideoEditableType extends VideoEditableType { public function supports(string $type): bool { return $type === 'bikevideo'; } protected function describeKeys(): array { return [...parent::describeKeys(), 'showAsLightbox' => ['type' => ['boolean', 'null']]]; } public function describe(array $config): string { return parent::describe($config) . ', and "showAsLightbox": true opens it over the page'; } } ``` `VideoEditableType` keeps its keys in one place, `describeKeys()`, and builds both the shape and the check on the way in from it. Adding an entry there is enough: the model is offered the key and `resolve()` stops calling it unknown. ### See what a page offers `list_area_bricks` lists every area of the page, the brick types allowed in each, and the settings each brick takes, your `describe()` among them. The workbench offers it, so it can be called without a model, see [Debugging](../50_Debugging.md). ```bash php workbench/bin/tool.php list_area_bricks --user=admin --arguments='{"documentId":19}' ``` For a page type the plan will create rather than one that exists, ask `list_planned_area_bricks` with the document type instead of an id. ### Next Your brick can be placed and filled. The two pages left are about the chat itself: what it offers on selected text, and the example instructions it suggests. Continue with [Add a selection action or a context resolver](Chat.md). --- ## Support a Class Definition Field Type [Fields](Fields.md) added a field the class definition does not carry. This page is the opposite case: the field *is* in the class definition, and it is missing from the schema anyway. That happens when the class uses a field type the project wrote itself. The `Bike` class carries a `gearing` field of such a type, and Genius cannot see it, because nothing knows what the value is worth or how it is written. You will fix that with one small class, and then see what the longer way in is for. First, though, the reason a field goes missing at all. - [Field pipeline](#field-pipeline) - [Describer priority](#describer-priority) - [Map a class definition field type](#map-a-class-definition-field-type) - [Declare the shape of a value that is not a scalar](#declare-the-shape-of-a-value-that-is-not-a-scalar) - [Describe a field the core already found](#describe-a-field-the-core-already-found) - [Change the value a field hands back](#change-the-value-a-field-hands-back) - [Find a dropped field](#find-a-dropped-field) ### Field pipeline Reflection walks a model class and offers every public method as a candidate field. Four services then decide what becomes of it, and a candidate none of them claims is dropped without a word. Your `gearing` is being dropped at the third step. | step | who | decides | |-------------------------------------|-----------------------------------------|-------------------------------------------------------------| | Is this method a field? | `FieldRecognizerInterface` | The name it goes by and the processor that builds it | | Build it out of the reflected member| `ReflectedFieldBuilderInterface` | The `Field`, or `null` for a member not worth listing | | Is it worth listing, and as what? | `FieldDescriberInterface` | `supports()` claims it, `describe()` gives it value type, label, description | | What does a read hand back? | `FieldValueTransformerInterface` | The display value, and what a written value is stored as | The four are separate services and each is tagged by autoconfiguration. #### Describer priority Recognisers and describers are asked in turn, and the order is the tag priority declared with `#[AsTaggedItem(priority: N)]`. **A higher number is asked earlier.** A service without the attribute has priority 0. The first recogniser that says yes to a member wins, and the first describer that claims a field wins. `FieldDescriberInterface` carries the four priorities the core uses. Declare yours with `PRIORITY_PROJECT`. | constant | value | who is asked there | |--------------------|-------|-------------------------------------------------------------------------------------------| | `PRIORITY_SPECIFIC`| 20 | The five core describers that each speak for one archetype, such as tags or the mail log | | `PRIORITY_PROJECT` | 10 | Nothing in the core. This is where a describer of your own goes | | `PRIORITY_GENERAL` | 0 | The seven core describers that speak for a whole family, such as asset or document fields | | `PRIORITY_FALLBACK`| -500 | `ClassDefinitionFieldDescriber`, which claims every class definition field nobody else took | Recognisers use plain numbers. | priority | who is asked there | |----------|-----------------------------------------------------------------------------------------------| | 100 | `PlainColumnRecognizer`, which recognises a member by a table column of that name | | 60 | `PageFieldRecognizer` and `EmailFieldRecognizer`, for document types with fields of their own | | 51, 50 | The two class definition recognisers, relations first, then everything else | | 0 | `GetterOnlyRecognizer`, which takes any remaining member by its method name and is never certain | > [!TIP] > If your describer never runs, look at who is above it rather than at your `supports()`. Any > priority above `PRIORITY_FALLBACK` beats the catch-all, and there is no reason to go above > `PRIORITY_SPECIFIC` unless you mean to take a field away from a core describer. `isLocked()` and `getLocked()` both give the field name `locked`, so where two members would give one name, only the first recognised is taken. ### Map a class definition field type Now the fix. `ClassDefinitionFieldTypeInterface` is the short way in. It says which OpenDXP field definition it speaks for, what the value is worth, how it is written, and one sentence about it. ```php namespace App\ContentCrafter\Field\FieldType; use App\ContentCrafter\Field\Processor\GearingFieldProcessor; use App\Model\DataObject\ClassDefinition\Data\Gearing; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\WriteCapability; use OpenDxp\Bundle\ContentCrafterBundle\Field\Enum\ValueType; use OpenDxp\Bundle\ContentCrafterBundle\Field\FieldType\ClassDefinitionFieldTypeInterface; use OpenDxp\Model\DataObject\ClassDefinition\Data; final class GearingFieldType implements ClassDefinitionFieldTypeInterface { public function supports(Data $field): bool { return $field instanceof Gearing; } public function getValueType(): ValueType { return ValueType::Number; } public function getWriteCapability(string $setter): WriteCapability { return new WriteCapability(GearingFieldProcessor::class, $setter, ValueType::Number); } public function describeField(Data $field): string { return 'The gearing of a bike, as chainrings by sprockets: {"front": 2, "rear": 11}. ' . 'Compared and sorted as the number of gears the two come to.'; } public function describeWriteShape(): array { return [ 'type' => 'object', 'additionalProperties' => false, 'required' => ['front', 'rear'], 'properties' => [ 'front' => ['type' => 'integer'], 'rear' => ['type' => 'integer'], ], ]; } } ``` `getValueType()` says what a filter, a `sortBy` and a `groupBy` compare the field as. `describeWriteShape()` says what a write may look like. They differ here because a gearing is written as its two halves and compared as one number. Return `null` from `getWriteCapability()` for a type that is read but never written. The processor named there implements `WritableFieldProcessorInterface`, see [Fields](Fields.md). The first field type that supports a definition wins, in the order of the tag priority. A definition that extends a definition of the core, such as `Select`, is supported by the core type as well. A field type of your own declares `#[AsTaggedItem(priority: ClassDefinitionFieldTypeInterface::PRIORITY_PROJECT)]` and is then asked first. #### Declare the shape of a value that is not a scalar `describeWriteShape()` is a branch of the grammar a plan is written against, see [The plan grammar](Plan_Grammar.md). A shape it does not carry is a shape nothing tells the model about, and a model told to write a gearing hands back the nearest thing it can think of, which is refused. So a field type whose value is more than a scalar declares its shape here. One whose value is a scalar, a list of scalars or rows returns `null`. Rows are written with `$set`, `$add`, `$update`, `$remove` and `$replace`, and that grammar is already there. Three things hold about the fragment you return. - Every property says its `type`. Nothing fills that in, and one property without it takes the whole plan grammar down with it. - Every property ends up in `required` on the way out, and one you left out of your own `required` is given a `null` branch instead. So the model writes every key of the shape, most of them as `null`, and the processor reading the value has to tell a `null` from a key that is not there. - A type whose value takes more than one shape returns them under one `anyOf`. `FieldTypeResolver::listWriteShapes()` splits the branches and each stands beside the others in the grammar rather than nested inside it. The shape says what is well formed. `describeField()` says what is allowed on **this** field, and it is given the definition to work that out: the units this one takes, the options it lists, the element types it points at. The shape is shared by every field of the type and can carry none of that. ### Describe a field the core already found The class above covers every field of the type, and it is all `gearing` needs. Reach for a describer when one field of one archetype needs a label or a description of its own, or has to be hidden. A field type speaks for every field of its kind and cannot tell them apart. Implement `FieldDescriberInterface`. `supports()` says whether the field is yours, `describe()` hands it back changed. ```php #[AsTaggedItem(priority: FieldDescriberInterface::PRIORITY_PROJECT)] final class BikeFieldDescriber implements FieldDescriberInterface { public function supports(Field $field, Archetype $archetype): bool { return $archetype->className === Bike::class && $field->name === 'frameNumber'; } public function describe(Field $field, Archetype $archetype): Field { return $field->withDescription('Frame number', 'The number stamped on the frame. No two bikes share one.'); } } ``` Once `supports()` says yes, no other describer is asked. A describer that claims a field of a class takes the place of `ClassDefinitionFieldDescriber`, which writes the label, the tooltip and the text of the field type. What holds for every field of a type belongs in `describeField()` of the field type. A field kept out on purpose is said with `Field::withHiddenBecause("why")`, which keeps the reason readable in the debug output. `Field` is readonly. Change it with the methods it carries rather than building a new one: `withValueType()`, `withDescription()`, `withName()`, `withRead()`, `withSensitivity()`, `withoutWrite()` and `withHiddenBecause()`. `withValueType()` changes the type that the schema shows and that a filter compares. The write capability keeps its own type. ### Change the value a field hands back A value transformer sits between the stored column and everything that shows or writes a value: a read, an average, a group label and a filter alike. | method | answers | |--------------------|----------------------------------------------------------------------------------------------| | `supports()` | Whether this transformer speaks for the field | | `toDisplayValue()` | What comes out of the column, as a person reads it | | `toStoredValue()` | What a written value becomes in the column | | `toStoredRange()` | What a value covers when it names less than the column holds, `null` when it names one point | `toStoredRange()` is what makes a day named without a time cover the whole day, so a filter on `2026-03-01` still matches a column that carries a time of day. It hands back a `ValueRange`, which holds a `from` and a `to`. A transformer is applied after the field cache, because a cached service would come back as a detached copy. `DateValueTransformer` in this bundle is the worked example. ### Find a dropped field A recognised member that no describer claimed is dropped. Where the recogniser was certain about it, because it found a table column or a class definition field rather than reading a method name, and no provider speaks for it either, the build refuses outright: ``` Bike: nothing declares "serviceIntervalKm", so it would vanish from the schema without a word. Declare each in a provider, or say it is kept out on purpose with Field::withHiddenBecause("why"). ``` > [!IMPORTANT] > That refusal only fires for a member a recogniser was *certain* about, meaning it found a table > column or a class definition field rather than reading a method name. A candidate that was only > guessed at is dropped in silence, and that is what a missing field usually turns out to be. A > field a describer claimed and then returned `null` for is let through as well, because somebody > decided it. To see what was dropped, and who offered it: ```bash php workbench/bin/explain.php fields --user=admin --arguments='{"domain":"object","type":"Bike"}' ``` See [Debugging](../50_Debugging.md). ### Next Your `gearing` is readable, comparable and writable. What a filter may *say* about it is a separate list: `gte`, `contains` and the rest follow from its `valueType`, and a word that is not among them has to be added. Continue with [Add a filter operator](Filter_Operators.md). --- ## Add a Field to an Existing Archetype [Query Domains](Query_Domains.md) made a whole new kind of data reachable. This page is the smaller move: a single value on a class OpenDXP already has, which the class definition does not carry. Genius reads, filters and writes such a field like any other. Two services make that work. A **virtual field provider** declares the field and what may be done with it. A **field processor** does the doing. You will build both for one field. The `Bike` class stores its price in cents, the way a shop system does, and nobody asks a question in cents. So you will put a `price` field beside it that reads, filters and writes in the currency unit, and have it take the stored field's place. - [Declare the field](#declare-the-field) - [Field arguments](#field-arguments) - [Replace a reflected field](#replace-a-reflected-field) - [Read the class definition](#read-the-class-definition) - [Write the processor](#write-the-processor) - [Build the SQL a filter runs](#build-the-sql-a-filter-runs) - [Shipped processors](#shipped-processors) - [Make the field writable](#make-the-field-writable) - [Register the services](#register-the-services) - [Check that it arrived](#check-that-it-arrived) ### Declare the field `VirtualFieldProviderInterface` has two methods. `supports()` says which archetypes the provider speaks for, `listFields()` returns the fields it adds to them. ```php namespace App\ContentCrafter\Field\Provider; use App\ContentCrafter\Field\Processor\PriceProcessor; use OpenDxp\Bundle\ContentCrafterBundle\Archetype\Dto\Archetype; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\Field; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\ReadCapability; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\SqlCapability; use OpenDxp\Bundle\ContentCrafterBundle\Field\Enum\ValueType; use OpenDxp\Bundle\ContentCrafterBundle\Field\Provider\VirtualFieldProviderInterface; final class PriceProvider implements VirtualFieldProviderInterface { public function supports(Archetype $archetype): bool { return method_exists($archetype->className, 'getPriceCents'); } /** * @return list */ public function listFields(Archetype $archetype): array { return [new Field( name: 'price', read: new ReadCapability(PriceProcessor::class, 'getPriceCents'), valueType: ValueType::Number, sql: new SqlCapability(PriceProcessor::class, 'price_cents'), label: 'Price', description: 'What the bike costs, in the shop currency. It is the stored price in ' . 'cents divided by 100, and it is the only price field. Do not ask in cents.', replaces: ['priceCents'], )]; } } ``` > [!WARNING] > `supports()` decides on the class, and the cheapest reliable test is whether the getter is on it. > `TableRegistry::hasColumn()` answers about the archetype's **own** table, which for a data object > is `objects` and holds only what every element has. It says `false` for `price_cents`, and a > provider guarded that way is never asked. A field carries three capabilities, and each names its processor by service id rather than the service itself. A field list is cached, and a live object does not survive that. | capability | the field can | the second argument | |-------------------|---------------------------------------------|-----------------------------------------| | `ReadCapability` | be read off an element | the getter, where it reads through one | | `SqlCapability` | be filtered, sorted, grouped and aggregated | the column, where the value sits in one | | `WriteCapability` | be written | the setter, where it writes through one | `read` is the only one that is required, so every field is readable. A field without a `SqlCapability` is listed as `"notComparable": true` and refuses a filter, a `sortBy` and a `groupBy`. A field without a `WriteCapability` is listed without `"writable"`. Sorting, grouping and aggregating are not declared. They follow from whether the processor named in `SqlCapability` implements `ExpressibleFieldProcessorInterface`. > [!TIP] > Declare the field with a `ReadCapability` alone first, and add the other two once it shows up in > the schema. A field that is only readable is a working field, and it takes one method instead of > three. #### Field arguments A processor reads these off the `Field` rather than looking them up again while it works. | argument | holds | |-------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------| | `valueType` | Which filter operators the field answers to, see [Filters](../11_Query_Filters.md) | | `label` | What a person sees, see [Rules](../00_Rules.md#labels). The model accepts a label where a name is expected | | `description` | What the model reads before it uses the field. Say what it is not for, which stops wrong calls | | `enum` | The values the field takes, where they are a fixed list | | `connectsTo` | The archetypes a relation reaches | | `targetAssetTypes`, `targetDocumentTypes` | Which asset and document types may go in. `null` means none at all, `[]` means any | | `localized` | The value sits in the per language table, so reading, filtering and writing it name a language, see [Rules](../00_Rules.md#languages) | | `mandatory` | The field cannot be emptied, and a processor refuses a write that would | | `replaces` | The fields this one takes the place of | | `sensitivity` | The value is masked or withheld on its way to the model, and `sortBy` and `groupBy` are refused | | `renderer` | The renderer that shows the value in the chat and in Genius Explorer. `null` leaves it to `valueType` | `Sensitivity` decides what the model sees of the value. Genius Explorer always shows the whole value. - `Code` keeps the last four characters of a code with at least eight characters. - `EmailAddress` keeps the first letter and the domain. - `Withheld` keeps nothing. A `renderer` is a function of the backend that turns the value into HTML. Add it under the same name once OpenDXP is ready: ```javascript document.addEventListener(opendxp.events.opendxpReady, function () { ContentCrafter.Module.Genius.ValueRenderer.addRenderer('bike_frame_size', function (value) { return Ext.util.Format.htmlEncode(value + ' cm'); }); }); ``` `RelationTargets::fromField()` puts `connectsTo`, `targetAssetTypes` and `targetDocumentTypes` together. Its `acceptsAssetType()` and `acceptsDocumentType()` say whether an element of a type may go in. > [!TIP] > Spend the effort on `description`. The most useful sentence is the one saying what the field is > *not* for. On a bike, `weight` and `weightWithRack` are both plausible answers to "how heavy is > it", and saying on each which question it answers is what stops the model picking either. #### Replace a reflected field Reflection declares a field for every column and every class definition field it recognises. Where your field stands for the same thing, name the reflected one in `Field::$replaces` and it drops out, whoever declared it. That is the `replaces: ['priceCents']` in the field above, and it is the reason the model is never offered two ways to ask one question. Without it, `price` and `priceCents` both stand in the schema, and half the answers come back a hundred times too large. Use it wherever the stored field and the useful field are the same thing said differently: a price in cents, a weight in grams, a duration in seconds. Two providers declaring the same name without one replacing the other is an error. Nothing picks a default between them. #### Read the class definition `DefinitionResolver::findFieldDefinition($archetype, $field->name)` hands back the OpenDXP field definition. Use it for what the field deliberately does not carry: the options of a select, the units of a quantity value. Those lists run into the hundreds and stay out of the cached field. > [!CAUTION] > A field list is cached per class definition, and no service survives that cache. That is why a > capability names its processor as a service id instead of holding the processor. Everything you put > on a `Field` has to be data that comes back out of a cache unchanged. ### Write the processor The field above names `PriceProcessor` three times and it does not exist yet. That is the other half. `FieldProcessorInterface` is empty. It marks a class as a processor so the container can find it by service id. A processor says what it can do by implementing one or more of the twelve capability contracts next to it in `Field\Processor\`. | interface | the processor can | reached through | |----------------------------------------------|------------------------------------------------------------------|-------------------------------| | `ReadableFieldProcessorInterface` | read the value off an element | `read` | | `GrowingListFieldProcessorInterface` | count the rows of a field and read only the ones an answer shows | `read` | | `FilterableFieldProcessorInterface` | turn a comparison into SQL | `sql` | | `ExpressibleFieldProcessorInterface` | give the expression a sort, a grouping or an aggregate reads | `sql` | | `TraversableFieldProcessorInterface` | filter in the rows behind the field and sort by `field.subfield` | `sql`, else `read` | | `RelatedFieldProcessorInterface` | say where the rows behind the field sit | `sql` | | `InheritableRelatedFieldProcessorInterface` | say where those rows sit for each `inheritance` reading | `sql` | | `WritableFieldProcessorInterface` | validate and write a value | `write` | | `ItemFieldProcessorInterface` | the same for a field that holds rows | `write` | | `ReferencingFieldProcessorInterface` | say which element a written value points at | `write` | | `ReviewableFieldProcessorInterface` | describe a proposed change for a reviewer | `write` | | `ReflectedFieldBuilderInterface` | build a field out of one reflected member | only `ReflectedFieldProvider` | An answer shows the first 20 rows of a field with a list of rows. A field with rows that a person keeps by hand is read whole and then cut. A field whose rows grow with the data, such as the elements that point back at one, implements `GrowingListFieldProcessorInterface`. Its rows are counted and loaded 20 at a time. Every method takes the `Field` it works on. Whether it also takes the capability follows one rule. > [!NOTE] > **A method is handed the capability exactly when that capability is nullable on the `Field`.** The > caller has already checked it for null, so the method never has to. `read` is never null, so > `read()` gets the field alone and pulls the getter out of `$field->read` itself. The ten methods > reached through `sql` or `write` take both. Five methods look like exceptions to that rule. `buildRelatedTableExpression()`, `buildScopedRelatedTableExpression()` and `resolveTargetSelectors()` are only ever reached through `sql`, so the capability is already implied. `traverse()` and `buildSubfieldExpression()` are looked up through `sql` where there is one and through `read` otherwise, so which capability it would be is not settled at the call. `buildField()` runs before there is a field at all. > [!WARNING] > A field that holds rows needs a `SqlCapability` even when nothing ever filters on it. > `FieldExecutor::findRelatedProcessor()` returns `null` for a field whose `sql` is missing, before > it asks whether the processor is a `RelatedFieldProcessorInterface` at all. The field is listed, it > reads fine, and it has no relation. Nothing is thrown and nothing is logged. ```php namespace App\ContentCrafter\Field\Processor; use OpenDxp\Bundle\ContentCrafterBundle\Archetype\Dto\Archetype; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\Field; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\SqlCapability; use OpenDxp\Bundle\ContentCrafterBundle\Field\Dto\SqlExpression; use OpenDxp\Bundle\ContentCrafterBundle\Field\Filter\ColumnConditionBuilder; use OpenDxp\Bundle\ContentCrafterBundle\Field\Filter\Enum\SqlComparison; use OpenDxp\Bundle\ContentCrafterBundle\Field\Processor\ExpressibleFieldProcessorInterface; use OpenDxp\Bundle\ContentCrafterBundle\Field\Processor\FilterableFieldProcessorInterface; use OpenDxp\Bundle\ContentCrafterBundle\Field\Processor\ReadableFieldProcessorInterface; use OpenDxp\Bundle\ContentCrafterBundle\Sql\Dto\SqlCondition; use OpenDxp\Bundle\ContentCrafterBundle\Sql\Dto\TableExpression; final class PriceProcessor implements ReadableFieldProcessorInterface, FilterableFieldProcessorInterface, ExpressibleFieldProcessorInterface { public function __construct(private readonly ColumnConditionBuilder $columnConditionBuilder) { } public function read(Field $field, object $element, ?string $locale): mixed { return round(((int) $element->{$field->read->requireGetter()}()) / 100, 2); } public function filter(Field $field, SqlCapability $capability, SqlComparison $operator, string|int|float|bool|array|null $value, Archetype $archetype, TableExpression $from): SqlCondition { return $this->columnConditionBuilder->build( $capability->requireColumn(), $this->buildPriceExpression($capability, $from), $field->valueType, $operator, $value, ); } public function buildExpression(Field $field, SqlCapability $capability, Archetype $archetype, TableExpression $from): SqlExpression { return new SqlExpression($this->buildPriceExpression($capability, $from)); } private function buildPriceExpression(SqlCapability $capability, TableExpression $from): string { return sprintf('ROUND(COALESCE(%s, 0) / 100, 2)', $from->buildColumnReference($capability->requireColumn())); } } ``` A provider may be its own processor where the two are about one field. `PathProvider` in this bundle does that, and is the shortest complete example of the pair. #### Build the SQL a filter runs `TableExpression` is the table the query reads from, with its joins, its condition and its per language companion. Never write a table or a column name yourself. | call | gives | |----------------------------------------------|------------------------------------------------------------| | `$from->buildColumnReference('price')` | The quoted column on this expression's own alias | | `$from->resolveLocalized($field->localized)` | The per language table for a localized field, else `$from` | | `$from->buildNestedAlias()` | An alias for one level deeper, so a subquery cannot shadow | `SqlCondition::raw()` takes an expression with `?` placeholders and the values in that order, and names the placeholders, so the same condition can be repeated and combined in any order. `SqlCondition::and()`, `or()`, `negate()` and `exists()` build the rest. ```php SqlCondition::raw(sprintf('%s LIKE ?', $from->buildColumnReference('path')), ['/bikes/%']); ``` `ColumnConditionBuilder::build()` turns any `SqlComparison` into a condition over one expression. It carries `isNull`, `isEmpty`, `in`, `between`, the comma separated `strings` columns, and the case folding and escaping the `contains`, `startsWith` and `endsWith` patterns need. A processor that filters over a column, or over an expression built from columns, calls it instead of writing the comparison out. A `sortBy` or a `groupBy` is refused on three grounds, checked in this order. The message says which one it was, and the processor is not fetched until the first two have passed. | the field has | the message says | |--------------------------------------------------------------|----------------------------------------------------------------------------| | no `SqlCapability` | it is not comparable, so read it instead | | a `sensitivity` | it is only ever shown masked, so it cannot be sorted, grouped or folded by | | a processor that is not `ExpressibleFieldProcessorInterface` | it has no sortable or groupable value | #### Shipped processors Where the value is already reachable, name one of these and write no processor at all. | processor | use it for | |----------------------------|---------------------------------------------------------------------------------| | `PlainColumnProcessor` | A value that is one column, read through a getter | | `VirtualRelationProcessor` | Rows that hang off the element by an id, tied by `targetIdField`/`ownerIdField` | | `GetterOnlyProcessor` | A scalar getter with no column behind it, read only | Three traits carry the parts that repeat. | trait | gives | |-----------------------|--------------------------------------------------------------------------------------------------------------------| | `QueriesRelated` | `read()`, `traverse()`, `buildSubfieldExpression()` and `resolveTargetSelectors()` for a field that holds elements | | `ReadsThroughGetter` | `readThroughGetter()`, which passes the locale to a localized getter | | `WritesThroughSetter` | `writeThroughSetter()`, which passes the locale to a localized setter | > [!TIP] > `QueriesRelated` pulls its own dependencies in with `#[Required]` setters rather than through the > constructor. Use the trait and your processor keeps its own constructor, with only the services it > needs in it. #### Make the field writable So far `price` can be read, filtered and sorted. Writing it takes a `WriteCapability` on the field and `WritableFieldProcessorInterface` on the processor. `validate()` returns the sentence a person reads when the value is wrong, or `null`. `write()` puts the value on the element, which the caller saves. The conversion runs the other way here: a person writes a price in the currency unit, and the element stores cents. ```php public function validate(Field $field, WriteCapability $capability, mixed $value, Archetype $archetype): ?string { if ($value === null || is_numeric($value)) { return null; } return sprintf('takes a price in the shop currency, like 1299.00, got %s.', var_export($value, true)); } public function write(Field $field, WriteCapability $capability, mixed $value, object $element, ?string $locale): void { $cents = $value === null ? null : (int) round(((float) $value) * 100); $this->writeThroughSetter($element, $capability->requireSetter(), $cents, $locale); } ``` `WriteCapability` takes three flags beyond the setter. `usesLocale` where the processor handles the language itself and there is no translatable field to be found by. `writesOwnRows` where the value goes into rows keyed by element id, so the write runs after the save. `multiValue` where one write carries several values. A field that holds rows of its own implements `ItemFieldProcessorInterface` instead. It returns an `ItemIdentity` naming the keys one row is addressed by and the write operators the field takes. On a bike, a field holding one price per dealer is named by the dealer, so writing one dealer's price leaves the others as they were. A row can be named by several keys at once. A row that never changes once it is in, like a note on an element, says `appendOnly: true`. The field then takes `$add` only. ### Register the services You now have both halves. Neither does anything until the container knows about them. A provider and a processor are ordinary services. Autoconfiguration tags them, so a glob over your own namespace is enough. Exclude the DTOs and the archetype marker classes, which are reflected and never services. ```yaml services: _defaults: autowire: true autoconfigure: true public: false App\ContentCrafter\: resource: '../src/ContentCrafter' exclude: - '../src/ContentCrafter/Archetype' - '../src/ContentCrafter/Field/Dto' ``` > [!IMPORTANT] > A bundle loads this file only when Content Crafter is installed, or an installation without it > fails to boot on a missing interface. Keep those services in a file of their own and load it from > your extension's `load()` behind a check of the kernel's bundle list, which carries this bundle > under `OpenDxpContentCrafterBundle`. ### Check that it arrived Four build errors can stop a field before it reaches the schema. All four are raised while `FieldBuilder` builds the field list, three of them through `ProcessorCheck`, and each names the field it means. | the message says | you did | |-------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------| | names X to read/sql/write it, which is not Y | Named a processor that does not implement the contract that capability needs | | reads it through getX(), which C does not have | Named a getter or setter that is not a method on the class | | A and B both declare "x" | Two providers claim one name and neither names the other in `replaces` | | nothing declares "x", so it would vanish from the schema without a word | A recognised column no provider speaks for. Declare it, or hide it with `Field::withHiddenBecause()` | To see what came out, run the field pipeline without a model: ```bash php workbench/bin/explain.php fields --user=admin --arguments='{"domain":"object","type":"Bike"}' ``` It lists every field that was kept, with the provider behind it and what it can do, and every one that was dropped, with the reason. See [Debugging](../50_Debugging.md). > [!TIP] > Run `fields` before and after adding your provider and compare. A field in neither list was never > recognised. A field that moved into `dropped` was recognised and then claimed by nobody. Once `price` is listed, check each capability on its own rather than in the chat. The filter first, then the sort: ```bash php workbench/bin/tool.php query_objects --user=admin \ --arguments='{"className":"Bike","filters":{"price":{"gte":1000}},"countOnly":true}' php workbench/bin/tool.php query_objects --user=admin \ --arguments='{"className":"Bike","sortBy":"price","sortDescending":true,"limit":2, "fields":["name","price"]}' ``` If `priceCents` still turns up in either answer, the `replaces` did not take. ### Next A field the core does not recognise at all is a different problem: it is dropped before any provider is asked, because nothing knows what shape its value has. Continue with [Support a class definition field type](Field_Types.md). --- ## Add a Filter Operator A filter operator is a word a filter object may use, such as `gte` or `contains`. It belongs either to a value type, and then every field of that type answers to it, or to one field alone. Most fields need nothing from this page. The `price` field you built in [Fields](Fields.md) is a number, so it answers to every word a number answers to, and you wrote no operator for it. You come here for one of two reasons: a field takes a word no value type has, or it takes fewer words than its type would give it. The grammar both extend is in [Filters](../11_Query_Filters.md). - [Add the operator](#add-the-operator) - [Narrow the operators of one field](#narrow-the-operators-of-one-field) ### Add the operator Two enums carry an operator. `FilterKeyword` is the word the model writes and reads about. `SqlComparison` is what a processor is handed once the word has been parsed. 1. Add the case to `FilterKeyword`. | method | says | |----------------------|---------------------------------------------------------------------------------------------------------------------------| | `appliesTo()` | Which value types answer to it. `false` for every type when the operator belongs to one field rather than to a value type | | `describe()` | The sentence the model reads about it | | `buildValueSchema()` | The JSON schema of its value | 2. Add the matching case to `SqlComparison` and pair the two in `ComparisonParser::resolveKeyword()`. That method is a `match` over every case, so a new one that is not paired does not compile. 3. Build its SQL. An operator that compares one value against one column needs a line in `OperatorSqlMapper::resolveComparison()`. Anything else is built in the processor of the field that offers it, in `FilterableFieldProcessorInterface::filter()`, see [Build the SQL a filter runs](Fields.md#build-the-sql-a-filter-runs). Four comparisons are reached without naming an operator. | case | written as | |-----------|------------------------------------| | `Equals` | A bare value | | `In` | A bare list | | `IsNull` | A bare `null` | | `Between` | `gte` and `lte` in the same object | `Equals`, `In` and `IsNull` reach `filter()` whatever a field lists in `filterOperators`, so a processor handles them even where it narrowed its list to something else. `Between` reaches it only where the field takes both `gte` and `lte`. ### Narrow the operators of one field A field names the operators it takes in the `filterOperators` of its `SqlCapability`. The list replaces the list of the value type rather than adding to it, so it names everything that field takes. ```php new SqlCapability( self::class, 'path', filterOperators: [FilterKeyword::StartsWith, FilterKeyword::In, FilterKeyword::NotIn, FilterKeyword::Ne], ); ``` The constructor of `Field` refuses two mistakes. | the message says | you did | |-------------------------------------------------------|---------------------------------------------------------------------------------------| | offers X on a Y field, which is not compared that way | Listed an operator that belongs to a value type, on a type that does not answer to it | | spells out every word a Y field already answers to | Wrote the type's full list out. Leave `filterOperators` empty instead | > [!IMPORTANT] > An operator whose `appliesTo()` returns `false` for every value type is exempt from the first > check. That is how a field adds a word no value type has. `inTree` is the only one this bundle > ships, built for the tag tree alone, and a field that does not list it never takes it. A field that narrowed its list carries `filterOperators` in the schema. A field that did not carries nothing, and answers to whatever its value type answers to: ```bash php workbench/bin/tool.php get_object_query_schema --user=admin --arguments='{"className":"Bike"}' ``` ### Next The model now knows which words your field answers to. What it knows about the field itself, its name and the sentence that tells it when to use it, is set somewhere else. Continue with [Change what the model is told about an archetype](Schema.md). --- ## Add an Operation Everything so far was reading. The shop's dealers can be asked about, filtered and counted, and there is no way to change one. An operation is what one step of a plan does, and every change Genius makes goes through a plan. A write with no operation cannot be made at all, by anybody. On this page you give the dealers one, and then decide four things about it in turn: whether a step may name a whole set, whether a reviewer can hold it back, whether it may delete, and what a step of it may carry. See [Writing](../20_Writing.md) for what a plan is, if you skipped it. - [Write the operation](#write-the-operation) - [Act on a set](#act-on-a-set) - [Languages of a step](#languages-of-a-step) - [Review support](#review-support) - [Let a step delete](#let-a-step-delete) - [Critical actions](#critical-actions) - [Value schema](#value-schema) - [Check what came out](#check-what-came-out) ### Write the operation `OperationInterface` is one class per thing that can be written. The table below is long, and most of it you answer in one line: extend `AbstractTableOperation` for a row of your own table, or `AbstractElementOperation` for an object, a document or an asset, and it settles most of these for you. ```php namespace App\ContentCrafter\Operation; use App\ContentCrafter\QueryDomain\DealerQueryDomain; use App\Repository\DealerRepository; use OpenDxp\Bundle\ContentCrafterBundle\Plan\Operation\AbstractTableOperation; final readonly class DealerOperation extends AbstractTableOperation { public function __construct( private DealerQueryDomain $domain, private DealerRepository $dealers, ) { } public function getName(): string { return 'dealer'; } protected function getQueryDomain(): DealerQueryDomain { return $this->domain; } } ``` Your constructor holds only what your own operation needs. The base class takes its services through `#[Required]` setters instead, so there is no `parent::__construct()` to call, and a new service on the base class does not break every operation that extends it. `AbstractElementOperation` is the one exception: it is handed the query domain it writes through as its single constructor argument, so an operation extending that one names that argument and passes it on with `parent::__construct($domain)`. The name the operation returns is the name a plan step uses. The interface is asked for every write mode the operation offers: `create`, `update` and `delete`. A step names the operation and the mode together, so an operation called `dealer` that offers all three is used as `dealer.create`, `dealer.update` and `dealer.delete`. | method | answers | |---------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `getName()` | The name a plan step uses | | `getRequiredPermission()` | The `RequiredPermission` a person would need for the same write | | `getElementType()` | The `ElementType` the backend should refresh, and whether a review row is about an element at all. `null` where the operation writes a row of its own table | | `namesSelector()` | Whether a step of this names a selector at all. A tag step does not: there is one thing to write and no kind to choose | | `listAvailableSelectors()` | The selectors a step of this mode may name, empty where the operation names one but has none to offer. Asked per mode, so a set can be named across kinds with `_all` where a new element cannot | | `resolveArchetype()` | The archetype behind a selector, usually the query domain's own | | `findSubject()` | The object one id stands for | | `listWriteModes()` | Which of `create`, `update` and `delete` this operation offers at all | | `buildValueSchema()` | What a step of this may carry, per mode | | `actsOnASet()` | Whether one step of this can name a whole set. Answering `false` leaves `matching` and `matchAll` out of its target, so a step of it can only ever name one element | | `resolveLocaleMode()` | Whether a step of this is offered `locales`, and what naming none there means | | `writesDraftOnly()` | Whether everything it writes lands unpublished, so it is already held back | | `validate()` | Everything wrong with a step, before anything runs | | `create()`, `update()` | The write itself. Deleting is defined on a separate interface, see [Let a step delete](#let-a-step-delete) | | `countMatching()`, `enumerateMatchingIds()` | A `MatchCount` saying how many elements a filter reaches and what it left out, and their ids in batches. A `null` filter is every element of the selector, which is what a target of `"matchAll": true` becomes. Both are handed the step's `VariantScope`, which an operation over rows that have no variants ignores | > [!TIP] > Leave a mode out of `listWriteModes()` and the operation is not registered for it. An > operation that only changes what already exists returns `[WriteMode::Update]`, and `create` and > `delete` are then unreachable with no error to word. Never express the refusal through > `buildValueSchema()`: it is asked with the selector the step names, and a schema that is empty for > one selector would take the mode away from all of them. `AbstractTableOperation` answers `countMatching()` and `enumerateMatchingIds()` through the query domain that `getQueryDomain()` returns. A query and a step then never disagree about how many rows a filter reaches. ### Act on a set The first of the four decisions. `actsOnASet()` decides what a step of your operation may be aimed at. Answer `true` and the target offers `subject`, `given`, `matching` and `matchAll`. Answer `false` and only `subject` and `given` are left, so no step of it can ever reach more than one element. Answer `false` where a step is written against what was read from one element and means nothing on the next one. The layout operation answers `false`, because its bricks are named by keys that belong to one page. ### Languages of a step Every operation answers `resolveLocaleMode()`. That one answer decides whether a step of this operation is offered `locales` at all, and what an empty list there means. | `LocaleMode` | offered `locales` | naming none means | |--------------|-------------------|------------------------------------------------------------------------| | `None` | No | Nothing this operation writes holds a language | | `Preferred` | Yes | The preferred content language, see [Rules](../00_Rules.md#languages) | | `Every` | Yes | Every content language, because what is written applies to all at once | `AbstractElementOperation` answers `Preferred` and `AbstractTableOperation` answers `None`, so an operation extending either has this settled. An operation on `Preferred` can narrow it one step further by implementing `LocalizedWriteOperationInterface`. Its `writesLocalizedValues()` is asked per step, with that step's selector and its values, and `false` leaves the step with no languages at all. A step that writes only fields holding no language is therefore never given one. Whichever it answers, the step still selects the elements it acts on in one language, see [Rules](../00_Rules.md#default-language). ### Review support The second decision. Values a job would write can wait for a person, see [Review](../30_Review.md), and an operation answers four separate questions about that. | the operation | means | |---------------------------------------------------|--------------------------------------------------------------------| | implements `StageableOperationInterface` | Its values can wait for a reviewer | | implements `LocalizedStageableOperationInterface` | A reviewer gets each value in the languages it is written in | | implements `StageableCreationInterface` | What it creates can wait for a reviewer | | `writesDraftOnly()` returns `true` | Everything it writes lands unpublished, so it is already held back | A draft-only step also binds the plan around it. Where jobs are reviewed, a plan holding one may lay out pages and create the documents it lays out, and nothing else, see [Review](../30_Review.md). > [!IMPORTANT] > An operation that implements neither interface and writes more than a draft cannot run under a > review. Nothing would hold its values back, so the plan refuses it when it is built rather than > writing past the review. `AbstractTableOperation` carries both stageable interfaces for an operation that writes a row of its own table rather than an element, such as a tag, a form or an output workflow. Such a row has no language and no field of an archetype. A reviewer therefore decides the values as they were written, and accepting them runs the same create or update the job would have run. The base class asks the operation for three things: | method | answers | |----------------------|------------------------------------------------------------| | `nameHeldSubject()` | What a reviewer reads instead of an element path | | `describeLabel()` | What this makes, in one word, English | | `readCurrentValue()` | What the row holds now, so a change can be read against it | `AbstractElementOperation` implements both stageable interfaces for objects, documents and assets, together with `CriticalActionInterface` and `DeletingOperationInterface`. The page content operation writes a draft and declares that with `writesDraftOnly()`. ### Let a step delete The third decision, and the one that cannot be taken back. An operation that lists `WriteMode::Delete` has to implement `DeletingOperationInterface`. If it does not, the container build fails and reports which operation is at fault. The interface adds two methods. | method | answers | |---------------------|------------------------------------------------------------------------------------------------------------------| | `delete()` | Performs the deletion, for one selector and one id | | `measureDeletion()` | Returns a `DeletionImpact`: how many elements are deleted along with it, and how many other elements point at it | `measureDeletion()` runs while the plan is built, once for each step that names a single element. Both numbers appear in the summary a person approves. Return `new DeletionImpact()` where neither number means anything for your data. A `.delete` step takes no `values`. A plan whose delete step names values is refused. `buildValueSchema()` is still called for this mode. Return an empty `ValueSchema` from it, so that the plan schema does not contain a branch nothing refers to. A deletion can never wait for a reviewer, no matter which interfaces the operation implements, see [Review](../30_Review.md). ### Critical actions Still part of deleting, and wider than it. A step that writes `published`, `key` or `parentId` performs an action that a version does not undo. An operation whose steps can do that implements `CriticalActionInterface`. An operation that does not implement it has no critical actions. The interface adds four methods. | method | answers | |-------------------------------|---------------------------------------------------------------------------------------------------------------------| | `findCriticalActions()` | The `CriticalAction` cases that follow from this mode and these values. `WriteMode::Delete` always returns `Delete` | | `findCriticalActionRefusal()` | A `Problem` describing what prevents one of them here, or `null` | | `dropIdleCriticalValues()` | The values without those that ask for what the element already has | | `buildAuditSubject()` | The `AuditSubject` written to the log. It is read while the element still exists | Each `CriticalAction` names the bundle permission it needs in `CriticalAction::permission()`, and the workspace rights on the element in `CriticalAction::workspaceRights()`. Return `Problem::stands()` from `findCriticalActionRefusal()` for a missing right, and for a state that cannot be worded around. Return `Problem::correctable()` for something the model could write differently, such as a name that is already taken. If a step returns any actions, the summary marks it, and the plan states that it contains critical actions. [Writing](../20_Writing.md#rename-move-publish-or-delete-an-element) lists the five actions and describes what an editor sees. ### Value schema The last decision, and the one the model sees most of: what a step of your operation may carry. `buildValueSchema()` returns a `ValueSchema` naming the required keys, the optional ones, and the shape of each. The constructor refuses a key it was given no shape for, so a key the model is offered and told nothing about cannot reach it. ```php public function buildValueSchema(WriteMode $mode, ?string $selector = null): ValueSchema { $properties = [ 'name' => ['type' => 'string', 'description' => 'The dealer\'s name as customers see it.'], 'region' => ['type' => 'string', 'description' => 'The region code, for example "CH-SG".'], ]; return $mode === WriteMode::Create ? new ValueSchema(required: ['name', 'region'], properties: $properties) : new ValueSchema(optional: ['name', 'region'], properties: $properties); } ``` Pass `open: true` instead of naming keys, and the step writes any field the archetype's query schema marks writable. Two flags then pick which of the three value forms that open map carries. | the schema says | the form | a value may be | |-----------------------------------|--------------------------|----------------------------------------------------| | Neither flag | `statedValue` | The value, or a list of them, written out | | `generatable`, `generatableKeys` | `statedOrGeneratedValue` | Also a `$generate`, written by a model per element | | `transformable` and `generatable` | `writtenValue` | Also a `$transform`, worked out from the element | The form is named in the grammar the model is held to, so a step does not spend a round writing a value form its operation was never going to take. There is no form for `transformable` without `generatable`, and asking for that pair throws while the plan schema is built. `generatable` opens every key the schema does not name, and `generatableKeys` names them one by one. A key that is neither has to be stated by the step, because no model invents where an element goes or what it is called. Whatever the form, a `$generate` and a `$transform` both work out text, so both are refused on a field that holds anything else, see [Writing](../20_Writing.md#value-forms). `validate()` returns every problem at once, as sentences, rather than throwing on the first. It is given the values, the ids of any that only exist once an earlier step has run, and the languages the step writes. A step that names a key the schema does not know is a problem like any other, and `ValueSchema::findUnknownKeys()` finds them. ### Check what came out Neither of these spends a model call. The first prints the grammar your operation now contributes, the second runs a plan through every check without writing anything: ```bash php workbench/bin/explain.php plan-schema --user=admin php workbench/bin/explain.php plan --user=admin --arguments='{"plan":[{"ref":"s1","op":"dealer.update", ...}]}' ``` See [Debugging](../50_Debugging.md). ### Next Your operation refuses a step that is wrong on its own. It cannot see the plan around it, so two steps that are each fine and impossible together still get through. Continue with [Add a plan check](Plan_Checks.md). --- ## Add a Plan Check The operation you wrote refuses a step that is wrong on its own. It never sees the plan around it, so two steps that are each fine and impossible together go straight through. A plan check is the rule that sees all of them. It answers a question about a whole plan, before anybody approves it, and it is what you reach for when the answer depends on more than a single value: on what another step of the same plan makes, on which element is being written, or on two fields of one step together. - [Where a rule belongs](#where-a-rule-belongs) - [Write the check](#write-the-check) - [What a resolved plan carries](#what-a-resolved-plan-carries) - [Correctable and standing problems](#correctable-and-standing-problems) ### Where a rule belongs Before you write one, check that this is the right place. A rule can live in three, and they know different things. | place | knows | use it for | |---------------------------------------------|----------------------------------------------------------------|-----------------------------------------------| | A field's own processor | one value, its field, the class | whether a value fits its field at all | | A plan check | every step in the order it runs, with its mode, selector and values | whether the steps add up to something allowed | | A save listener on `PRE_ADD`/`PRE_UPDATE` | the finished element | anything only the element itself can answer | A plan check runs while the model can still write the plan differently. A save listener runs after somebody approved it, so what it refuses stops the job rather than correcting the plan, see [Jobs](../20_Writing.md#when-a-job-stops). Prefer a plan check wherever the answer is already knowable. ### Write the check One method, and a plan to walk. This one refuses a dealer put in a region the shop does not serve. ```php namespace App\ContentCrafter; use OpenDxp\Bundle\ContentCrafterBundle\Plan\Check\PlanCheckInterface; use OpenDxp\Bundle\ContentCrafterBundle\Plan\Dto\ResolvedPlan; use OpenDxp\Bundle\ContentCrafterBundle\Vocabulary\Dto\Problem; final readonly class DealerServesItsRegionCheck implements PlanCheckInterface { public function __construct(private RegionRepository $regions) { } public function findProblems(ResolvedPlan $plan): array { $problems = []; foreach ($plan->listEveryStep() as $step) { $region = $step->values['region'] ?? null; if ($step->selector !== 'Dealer' || !is_string($region) || $this->regions->isServed($region)) { continue; } $problems[] = Problem::correctable(sprintf( 'Step "%s" puts the dealer in "%s", which this shop does not serve. The served ' . 'regions are %s.', $step->ref, $region, implode(', ', $this->regions->listServed()), )); } return $problems; } } ``` You do not have to tag the service. `PlanCheckInterface` is autoconfigured, so any service of this class is asked. Return an empty list when you have nothing to say. Every plan goes through the same resolver, so the check answers in the chat, when a routine is saved and at the workbench. Try it out without a model call: ```bash php workbench/bin/explain.php plan --user=admin --arguments='{"plan":[{"ref":"s1", …}]}' ``` ### What a resolved plan carries `ResolvedPlan::listEveryStep()` gives every step, the ones that repeat inside a set included. Each one carries: - `ref`, the name other steps point at with `"$ref"` - `operation`, whose `mode` is `WriteMode::Create`, `Update` or `Delete` - `selector`, the class, document type or asset type the step is about - `values`, as the model wrote them - `target`, where `findLiteralSubject()` gives the element id when the step names one outright Two things are not there. A rule that needs either cannot be answered by a plan check. - **The id of an element another step makes.** It does not exist yet. What you can read is the step that will make it: a `"$ref"` in a value names it, and that step's `selector` says its class. - **A value the model still has to write.** A `{"$generate": …}` is an instruction, not the text. ### Correctable and standing problems `Problem::correctable()` says the model can write the plan differently, and the plan is sent back to be written again. `Problem::stands()` says the limit holds however the plan is worded, and the turn ends with the editor being told what stopped it. Use `stands()` only where nothing about the request could get through, such as a setting that is off or a permission nobody has. A rule the model could satisfy by naming something else is `correctable()`, so that it gets a round to fix the plan itself. > [!TIP] > Say what is wrong and what to write instead, in the same sentence. A `correctable()` problem is > read by the model and by nobody else, and one that only says *no* costs a round without telling it > which way to go. ### Next That is the whole write side for your own data. What is left is the content of a page, which is written through a vocabulary of its own. Continue with [Add an editable type to page content](Editable_Types.md). --- ## The Plan Grammar Content Crafter sends the grammar to the model vendor with the request, as the shape the answer takes. The model is asked to write that shape and is not held to it token by token: a grammar that decides every token also decides them while the model is still working out what the plan should be, and it writes worse under that than it does writing freely. What comes back is read against the grammar instead, and the words a model puts around its answer are cut away rather than taken for part of it. A shape the grammar does not carry is therefore a shape nothing tells the model about. It writes the nearest thing it can think of, and the plan is refused for it. Three rules follow from that: - A field type declares the shape of a value that is not a scalar, see [Field Types](Field_Types.md#declare-the-shape-of-a-value-that-is-not-a-scalar). - The language of a translated row inside an item is an entry that names itself, not a key, see [Writing](../20_Writing.md#a-translated-field-inside-an-item). - Every key of every object is written, most of them as `null`. --- ## Add a Query Domain The tool you wrote in [Extending](../40_Extending.md) answers one question: how many dealers a region has. Ask anything else about a dealer and there is nothing to call. A query domain fixes that for good. It makes a whole kind of data filterable, sortable, groupable and countable, so *which dealers in Sankt Gallen have no phone number* needs no tool of its own. On this page you will turn the shop's dealers into one, in four steps: register the entity, write the domain, say who may reach it, and give it its two tools. You need the `Dealer` entity, mapped with Doctrine. Nothing else from the tool carries over. Rows that no entity maps are covered at the end, in [Rows without an entity](#rows-without-an-entity). ### Register the entity A domain has to know where its rows are. For a Doctrine entity, the mapping knows. Register an `EntityTable` for the class and let `EntityTableFactory` build it: ```yaml services: app.content_crafter.dealer_table: class: OpenDxp\Bundle\ContentCrafterBundle\Archetype\Table\EntityTable factory: ['@OpenDxp\Bundle\ContentCrafterBundle\Field\Entity\EntityTableFactory', 'create'] arguments: [App\Entity\Dealer] ``` That one registration gives the class its fields. Content Crafter reads them off the mapping: | the mapping holds | the model gets | |-----------------------------------------------------------|----------------------------------------------| | a field of a scalar type | a field to read, filter, sort and group by | | a field of type `json`, `array`, `object`, `simple_array` | a field read whole, not filterable | | an association | a `relation` or `relations` field, see below | A field is read through the mapping, not through a getter. An entity whose getter is called `isActive()` for the field `active` is read all the same. A Doctrine type that Content Crafter does not know stops the field list with an error that names the field. Say which value type it is: ```yaml opendxp_content_crafter: field: doctrine_types: money_cents: number settings_blob: structure ``` `structure` is read whole and cannot be filtered on. ### Write the domain Extend `AbstractEntityQueryDomain`. It loads the rows through the mapping and leaves you three methods. | method | answers | |--------------------------------|--------------------------------------------------------| | `getName()` | The name a tool, the schema and `explain.php` use | | `listEntityTypes()` | Which entities the domain holds, and who may read each | | `buildAllowedRowRestriction()` | Which rows this caller may be handed | `listEntityTypes()` returns one `EntityType` per entity: the name a call gives as `type`, the entity class, and the permission a person needs to open the same screen. `titleField` names the field that names a row for a person, see [Name and open a row](#name-and-open-a-row). ```php final class DealerQueryDomain extends AbstractEntityQueryDomain { public function getName(): string { return 'dealer'; } protected function listEntityTypes(): array { return [ new EntityType('dealer', Dealer::class, BikePermission::Dealers->value, titleField: 'name'), ]; } } ``` A domain holds several entities when one area of the backend shows them together, such as the dealers and their regions. A call then names one of them as `type`, the way an asset query names an asset type. A domain with a single entity needs no `type` named. A bundle whose entity classes come from its configuration hands them in through the constructor and returns them from `listEntityTypes()`. `fetch()` hands back the entities, not rows. `EntityNormalizer` turns an entity into what the model reads, every field the archetype has. A bundle that wants a different shape registers a normalizer for its class, which is asked first. ### Say who may reach it, and which rows Each entity names its own permission in `listEntityTypes()`. A person is offered only the types they hold the permission for, and a call that names another type is refused. The domain asks for any one of these permissions with `RequiredPermission::anyOf()`, so a person who may read none of the types does not see its tools at all. `buildAllowedRowRestriction()` is abstract and does not accept `null`. It narrows the rows for the caller in SQL, and it is applied to every count, every aggregate and every fetch alike. > [!CAUTION] > Handing out every row has to be said out loud: `RowRestriction::unrestricted($reason)`. A domain > that does so has to write down what makes that safe. ```php protected function buildAllowedRowRestriction(TableExpression $rows): RowRestriction { return RowRestriction::unrestricted( 'A dealer belongs to the installation rather than to any element, so whoever holds the ' . 'permission above may be handed every row.', ); } ``` Where the rows do belong to somebody, restrict them instead: ```php protected function buildAllowedRowRestriction(TableExpression $rows): RowRestriction { return RowRestriction::restrictedTo(SqlCondition::raw( sprintf('%s = ?', $rows->buildColumnReference('country')), [$this->currentUserCountry()], )); } ``` ### Describe the fields A field from the mapping is named after its property and carries no description. Describe it the way a field of a data object is described, with a `FieldDescriberInterface`: ```php final class DealerFieldDescriber implements FieldDescriberInterface { public function supports(Field $field, Archetype $archetype): bool { return $archetype->className === Dealer::class && in_array($field->name, ['phone', 'internalNotes'], true); } public function describe(Field $field, Archetype $archetype): Field { return $field->name === 'phone' ? $field->withDescription('Phone', 'The number customers call, with the country code.') : $field->withHiddenBecause('The notes are for the sales team only.'); } } ``` A describer can label a field, give it another value type with `withValueType()`, hide it, or return a different field in its place. A field that no describer claims stays as the mapping has it. Only one provider may replace a field. Two providers that both name a field in `Field::$replaces` stop the field list with an error, so a second view of an entity field is written as a describer. ### Follow its relations Every association becomes a field the model filters into, the way it filters into the relations of a data object: ```json {"regions": {"any": {"name": "Ostschweiz"}}} ``` All three ways Doctrine stores an association work: the key on the target row, the key on the owner row, and a join table. A relation is filtered with `any`, `every`, `none`, `empty` or `count`, also when it holds only one row. The target of an association needs an `EntityTable` of its own. It does not need a domain. An association whose target has no table stops the field list with an error that names the field. Register the target, or hide the field with a describer. A translation entity is a relation like any other. The model asks for the language in the filter: ```json {"translations": {"any": {"locale": "de", "label": "Velohändler"}}} ``` In an answer, a row carries the rows of its relations with their fields. The relations of those rows are given as ids only, so two entities that point at each other do not repeat each other. ### Give the domain its two tools The domain is now complete, and nothing can call it. Two tools answer for a domain and both name it. | tool | the model can | |-----------------------------------|------------------------| | extends `AbstractQueryTool` | search the domain | | extends `AbstractQuerySchemaTool` | read its field catalog | Register both. With only the query tool the model has to search without knowing the field names. With only the schema tool it reads the field names and cannot search. List the schema tool under `tools:` in a skill, see [Name the tool in a skill](Tools.md#name-the-tool-in-a-skill). The query tool needs no entry of its own, because a call to the schema tool opens it. A schema tool extends `AbstractQuerySchemaTool` and names its domain. Its permission and its answer come from the domain: ```php #[AsTool('get_dealer_query_schema', 'Returns the queryable fields of the dealers: every field name, its label and its value type.')] #[ContentCrafterTool(summary: 'The queryable fields of the dealers.', cacheableInTurn: true)] final class GetDealerQuerySchemaTool extends AbstractQuerySchemaTool { public function getQueryDomainName(): string { return 'dealer'; } } ``` A domain with several entities takes the `type` in both tools. The schema tool then declares its own `__invoke()` and answers the fields of that type. The parameter is optional, because the base class declares `__invoke()` without one. A call that names no type is refused with the types there are: ```php public function __invoke(?string $type = null): array { return $this->domain->describeSchema($type)->toArray(); } ``` The query tool hands the type on as a `SubtypeSelector`: ```php return $this->buildQueryResult(new QueryRequest( selector: new SubtypeSelector($type), filters: $filters, // ... )); ``` A query tool extends `AbstractQueryTool`, names its domain the same way and declares its own `__invoke()`. Each query tool tells the model in its parameters what this domain is grouped by, so the parameters are written per tool. What a query tool takes beyond `filters`, `countOnly`, `sortBy`, `sortDescending`, `groupBy`, `groupGranularity`, `aggregate`, `limit` and `offset` is its own: an object query requires a class name, an asset query takes a type. See [Tools](Tools.md). ### Try it without a model Once the domain is registered, the workbench runs the field pipeline over it under the name it registered with. This is how a field that does not show up is tracked down: ```bash php workbench/bin/explain.php fields --user=admin --arguments='{"domain":"dealer"}' ``` The query tool itself is offered at the bench only once it is named in `manifest.local.json`, see [Reach the tool at the workbench](Tools.md#reach-the-tool-at-the-workbench). ### Rows without an entity Rows that no entity maps, such as a table another system writes, need the two parts the entity gave for free. The table extends `MappedTable`, which reads the columns off the database: ```php final class DealerTable extends MappedTable { public function getArchetypeClass(): string { return Dealer::class; } public function getTableName(): string { return 'bike_dealers'; } } ``` The domain extends `AbstractTableQueryDomain` and loads its rows in `fetch()`. It names the permission itself in `getRequiredPermission()`, for example `RequiredPermission::of(BikePermission::Dealers->value)`. Asking for none has to be said out loud as well, with `RequiredPermission::none($reason)`. `fetchRows()` runs the whole request, filters, sorting and paging included, and `hydrateReadResults()` reads the fields the request names: ```php public function fetch(QueryRequest $request): array { $dealers = $this->dealers->findByIds(array_column($this->fetchRows($request, 'id'), 'id')); return $this->hydrateReadResults($dealers, $request); } ``` The fields of such a table are declared by a `VirtualFieldProviderInterface`, see [Add a field to an existing archetype](Fields.md). A normalizer for the row class turns a row into what the model reads, see [Schema](Schema.md). ### Name and open a row The chat and Genius Explorer show the rows of a query to a person. A row that is an element, or belongs to one, is named by the key of its element and opens it. Every other row needs its domain: - An entity domain names a row by the `titleField` of its `EntityType`. - Any other domain implements `TitledRowsQueryDomainInterface`. `findRowTitle()` returns the text of a row, or `null`, and the row is then named by its id. A row opens through an opener that your bundle adds in the backend. Add it once OpenDXP is ready: ```javascript document.addEventListener(opendxp.events.opendxpReady, function () { ContentCrafter.Module.Genius.RowOpener.addOpener('dealer', 'dealer', function (row) { bikes.dealer.open(row.id); }); }); ``` The first argument is the name of the domain, the second the `type` of the row. A row of a type without an opener cannot be clicked. ### Interfaces the base class implements Your domain already has these, because `AbstractTableQueryDomain` implements two of them, and `AbstractEntityQueryDomain` extends it and adds the third. `AbstractElementQueryDomain` implements all three. Implement one by hand only on a domain that implements `QueryDomainInterface` directly. | interface | means | you get it from | |------------------------------------|---------------------------------------------------------------------------------------------------------|-----------------------------------------------------------| | `AggregatableQueryDomainInterface` | The domain can be counted, grouped and added up, see [Filters](../11_Query_Filters.md#group-the-result) | `AbstractTableQueryDomain` | | `EnumerableQueryDomainInterface` | A job can walk its rows in batches, picking up after the last id rather than by offset | `AbstractTableQueryDomain` | | `SelectableQueryDomainInterface` | The domain takes a selector, such as an object class or an asset type | `AbstractElementQueryDomain`, `AbstractEntityQueryDomain` | ### Report what the answer left out A working domain can still mislead: a count of zero looks the same whether nothing matches or the filter looked in the wrong language. Three methods say what the answer did not reach, and what they answer becomes an `instruction` on the result. | method | asked when | answers | |------------------------------------------------------------|------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------| | `LeftOutMatchesQueryDomainInterface::findMatchesLeftOut()` | The count came back zero | How many rows the query left out, and what to ask instead | | `LeftOutMatchesQueryDomainInterface::findValuesLeftOut()` | The count came back higher, once on the count alone and again with the rows once they are read | Which read field is blank in the language read and holds a value in another | | `UnknownPathsQueryDomainInterface::findUnknownPaths()` | The count came back zero | Which of the paths the filter named are not in this tree at all | `findValuesLeftOut()` is asked twice because a count-only answer and a too-long one never reach the rows. Anything that holds whatever the rows say, such as a count of what a scope left out, belongs in both calls. Anything read off the rows is returned only where there are rows. The moments they report are listed in [Rules](../00_Rules.md#what-the-answer-leaves-out). Return an empty list on a domain whose rows carry no translated field, the way `ElementQueryDomain` does. > [!TIP] > `findMatchesLeftOut()` is worth answering on any domain whose rows are commonly filtered on a value > people get slightly wrong, such as a name or a status word. Without it the answer says there are > none where rows exist and the filter looked in the wrong place. `UnknownPathsQueryDomainInterface` is answered by `AbstractElementQueryDomain`, so objects, documents and assets have it. A domain of your own that walks a tree implements it itself, and `FilterReader::listPaths()` reads the paths a filter tree names. ### Next The dealers are queryable. The other direction is a value that belongs on a class OpenDXP already has, which needs no domain of its own but does need the field pipeline. Continue with [Add a field to an existing archetype](Fields.md). --- ## Change What the Model Is Told About an Archetype By now the shop's bikes and its dealers can both be queried, and both still come back as the class names `Bike` and `Dealer`. An editor asking about dealers is answered in a word they do not use. Three interfaces change what the model and the editor make of an archetype: what it is called, what is said about it beyond the field list, and how one of your value objects is rendered. This page takes them in that order, and each one stands on its own. - [Name an archetype](#name-an-archetype) - [Add guidance to a schema](#add-guidance-to-a-schema) - [Render one of your values](#render-one-of-your-values) ### Name an archetype `ArchetypeLabelProviderInterface` says what a row of an archetype is called, and which of its own fields label a single row. ```php final class BikeLabelProvider implements ArchetypeLabelProviderInterface { /** @var array}> */ private const array ARCHETYPES = [ Bike::class => ['bike.genius.archetype.bike', ['name', 'key']], Dealer::class => ['bike.genius.archetype.dealer', ['name']], ]; public function supports(Archetype $archetype): bool { return isset(self::ARCHETYPES[$archetype->className]); } public function buildLabel(Archetype $archetype): ArchetypeLabel { [$labelKey, $labelFields] = self::ARCHETYPES[$archetype->className]; return new ArchetypeLabel($this->translator->trans($labelKey), $labelFields); } } ``` `ArchetypeLabel::$labelFields` is a declared order, most telling first. The first of those fields that holds something labels the row, so a bike with no name falls back to its key. > [!NOTE] > An empty list says a row of this archetype has no label of its own, and stops anything scanning > its fields for something that looks like one. ### Add guidance to a schema A schema guide is one or more sentences attached to an archetype's schema, next to its fields. It is for what the field list cannot say: which of two similar fields a person usually means, or what is true only because your bundle is installed. ```php final class BikeSchemaGuide implements SchemaGuideInterface { /** * @param list $bikeClasses */ public function __construct(private readonly array $bikeClasses) { } public function supports(Archetype $archetype): bool { return in_array($archetype->className, $this->bikeClasses, true); } public function describe(Archetype $archetype): array { return ['A bike has two weight-like fields. "weight" is the bike as it is sold. ' . '"weightWithRack" includes the carrier and is always higher. When the user asks how ' . 'heavy a bike is without saying more, they mean "weight".']; } } ``` One note per entry of the returned list, each a sentence to the model. > [!TIP] > Which class holds the bikes is a project decision, so take the class names from a container > parameter instead of naming a class in the code. A guide that names a shipped class stays silent > on the one a project actually uses. Guidance about one field belongs on that field's `description`, see [Fields](Fields.md). A guide is for what is true of the archetype as a whole. ### Render one of your values A query domain's `fetch()` hands back the objects the bundle works with, not rows. What the model reads of one is decided by a `ToolResultNormalizerInterface`, which is an ordinary Symfony normalizer tagged for the private serializer that renders tool results. > [!WARNING] > Register a normalizer with `autoconfigure: false` and tag it by hand. A > `ToolResultNormalizerInterface` implementor is also a Symfony `NormalizerInterface`. Left > autoconfigured, Symfony's FrameworkExtension tags it as well and it lands in the application's > shared serializer, where it changes how unrelated things are rendered. ```yaml App\ContentCrafter\Serializer\Normalizer\: resource: '../src/ContentCrafter/Serializer/Normalizer' autoconfigure: false tags: ['content_crafter.serializer.tool_result_normalizer'] ``` Exclude this directory from the glob that registers the rest of your `ContentCrafter` namespace, or the two registrations claim the same services. ### Next The dealers can be asked about, named and rendered. Everything so far was reading. Letting a routine write your data is the other half. Continue with [Add an operation](Operations.md). --- ## Add a Suggestion The chat and the routine window both greet an editor with three example instructions, put together from what this installation holds and without calling a model. None of them can mention the `price` field you added in [Fields](Fields.md), because the core ships no wording for a field it does not have. A bundle that brings a field brings the wording that uses it. That is this page: a provider decides which classes a wording fits and fills the slots in it, and a translation key carries the words. Nine providers ship with the bundle, see [Configuration](../01_Configuration.md#suggestions). - [Write the provider](#write-the-provider) - [Add the wording](#add-the-wording) - [Exclude or reword a suggestion](#exclude-or-reword-a-suggestion) ### Write the provider Implement `SuggestionProviderInterface`. Autoconfiguration tags the service, so there is nothing to register. | method | answers | |----------------|-----------------------------------------------------------------------------| | `getName()` | The key an installation writes in `exclude` and in the `when` of `add` | | `getTextKey()` | The translation key of the wording | | `findSlots()` | The slots filled for this class, or `null` where the class does not fit it | The shop offers a wording for classes that carry a price, asking for the price to be named in a description. Two things have to be true for that: the class has the field, and it has somewhere to write prose. `SuggestionFields` answers both. ```php namespace App\ContentCrafter\Suggestion; use OpenDxp\Bundle\ContentCrafterBundle\Archetype\Dto\Archetype; use OpenDxp\Bundle\ContentCrafterBundle\Genius\Suggestion\SuggestionFields; use OpenDxp\Bundle\ContentCrafterBundle\Genius\Suggestion\SuggestionProviderInterface; final readonly class PriceProvider implements SuggestionProviderInterface { public function __construct( private SuggestionFields $fields, ) { } public function getName(): string { return 'price'; } public function getTextKey(): string { return 'shop.suggestions.price'; } /** * @return ?array */ public function findSlots(Archetype $archetype): ?array { if ($this->fields->findField($archetype, 'price') === null) { return null; } $field = $this->fields->findTextFields($archetype, longOnly: true)[0] ?? null; return $field === null ? null : ['{field}' => $field->label]; } } ``` `findSlots()` is asked once per data object class. A bundle that brings a query domain of its own rather than fields on an object class has nothing to attach a wording to. The shipped providers read a class with `SuggestionFields`, and it covers most wordings. | method | answers | |-------------------------|------------------------------------------------------------------------------------------------------------------------------------| | `listFields()` | Every field of the class, as `QueryFieldSchema` | | `findField()` | One field by name, or `null` | | `findTextFields()` | The fields an editor types prose into. `localized: true` keeps the translated ones, `longOnly: true` the textarea and WYSIWYG ones | | `listContainerItems()` | One entry per item type a container field of the given value type allows, each the field and the archetype of the item | | `takesImages()` | Whether a relation field takes an image | | `findAssetFolderPath()` | The path of an asset folder in this installation, or `null` | | `reachesObjects()` | Whether a predefined property may sit on an object | > [!IMPORTANT] > The container reads `getName()` while it is still being built, on an instance whose constructor has > not run. Return a literal from it. A name put together from injected values cannot be read there, > and the build stops with a message naming your class. ### Add the wording `getTextKey()` names a key in the `admin` domain. The bundle that brings the provider brings the catalogue that key is in. Put it under a prefix of your own, beside the rest of your backend wordings. ```yaml # translations/admin.en.yaml shop.suggestions.price: 'Mention the price in the {field} of every object of type {class}.' ``` `{class}` is filled with the label of the class. Everything else comes from `findSlots()`. A wording naming a placeholder it does not return is never offered, so change the two together. Fill a slot with the label of a field, never with its technical name. An editor reads the wording, in their own backend language. ### Exclude or reword a suggestion Your name works like any of the core's. An installation that does not want the wording excludes it, and one that wants different words keeps the slots and writes its own, see [Configuration](../01_Configuration.md#suggestions). ```yaml opendxp_content_crafter: suggestions: exclude: [price] add: - when: price text: 'Name the price in the {field} of every object of type {class}, with the currency.' ``` ### Next That is every extension point. The tool you wrote on the first page was the shortest of them, and it has more to it than that page showed: two descriptions read at different moments, five attribute arguments, and what the tools of a query domain share. Continue with [Add a tool](Tools.md). --- ## Add a Tool You wrote a tool on the first page of this chapter, in [Add your first tool](../40_Extending.md#add-your-first-tool), and that page stopped as soon as it worked. This is the rest of it. A tool is an invokable service carrying three things: the name the model calls, the description it reads before deciding to, and the permission a person would need for the same action. You will write a second one, the stock those dealers hold, and then go through what each of the three is for. - [Write the tool](#write-the-tool) - [Name the permission](#name-the-permission) - [Write the description](#write-the-description) - [`#[ContentCrafterTool]` arguments](#contentcraftertool-arguments) - [Name the tool in a skill](#name-the-tool-in-a-skill) - [Query domain tools](#query-domain-tools) - [Reach the tool at the workbench](#reach-the-tool-at-the-workbench) ### Write the tool The same shape as the first one, with a different question behind it. ```php namespace App\ContentCrafter\Tool; use App\Repository\BikeStockRepository; use OpenDxp\Bundle\ContentCrafterBundle\Security\Dto\RequiredPermission; use OpenDxp\Bundle\ContentCrafterBundle\Tool\Attribute\ContentCrafterTool; use OpenDxp\Bundle\ContentCrafterBundle\Tool\ToolInterface; use OpenDxp\Bundle\ContentCrafterBundle\Vocabulary\Enum\ContentCrafterPermission; use Symfony\AI\Agent\Toolbox\Attribute\AsTool; use Symfony\AI\Platform\Contract\JsonSchema\Attribute\Schema; #[AsTool( 'count_bikes_in_stock', 'Counts the bikes one dealer has in stock right now. Says nothing about which bikes they are, ' . 'nothing about bikes on order, and nothing about price.', )] #[ContentCrafterTool(summary: 'Counts the bikes a dealer has in stock.')] final class CountBikesInStockTool implements ToolInterface { public function __construct(private readonly BikeStockRepository $stock) { } public function getRequiredPermission(): RequiredPermission { return RequiredPermission::of(ContentCrafterPermission::Genius->value); } public function __invoke( #[Schema(description: 'id of the dealer', minimum: 1)] int $dealerId, ): array { return ['inStock' => $this->stock->countForDealer($dealerId)]; } } ``` The parameters of `__invoke()` are the tool's arguments. `#[Schema]` on a parameter is what the model reads about it, and the parameter's own type becomes its JSON schema. Refuse a call by throwing a `ToolException`. Its message goes back to the model as the answer to that call, so write it as something to act on. Any other exception ends the turn. > [!IMPORTANT] > A refusal is remembered for the rest of the turn, and the same call with the same arguments is > answered with that message instead of being run again. Throw a `ToolException` only for what the > arguments decide. A failure that could go the other way next time, a network timeout among them, is > a different exception. ### Name the permission The first of the three. `getRequiredPermission()` names the OpenDXP permission a human editor would need for the same action. A user without it never sees the tool, in the catalog or anywhere else. | answer | means | |----------------------------------------|---------------------------------------------------------------------------| | `RequiredPermission::of($name)` | The permission the user has to hold | | `RequiredPermission::anyOf(...$names)` | Any one of these permissions | | `RequiredPermission::none($why)` | No permission of its own, plus a reason saying what already makes it safe | `none()` needs the reason as a sentence and refuses an empty one, so a tool that needs no permission explains why in the class itself. The Genius permission that every chat needs is checked before any tool is reached either way. A tool never filters for visibility itself, see [Rules](../00_Rules.md#permission-and-visibility). ### Write the description The second, and the one that decides whether your tool is ever called for the right question. A tool carries two texts, and they are read at different times. | text | when | how long | |---------------------------------|------------------------------------|---------------------------| | `summary` on `#[ContentCrafterTool]` | Every turn, for every tool | One sentence | | The description on `#[AsTool]` | Once the model has loaded the tool | As long as it needs to be | Genius sends the catalog rather than every tool's full schema, and the model calls `load_tool` by name to make a tool callable. > [!IMPORTANT] > The catalog line is sent on every round of every turn, for every tool a user may call. Keep it to > one sentence. The description behind it is read once the tool has been loaded and can be as long as > it needs to be. > [!TIP] > Write the description in two halves: what the tool finds, and what it does not find. The second > half is what stops it being called for the wrong question. List the fields of the answer in the > schema the tool returns, not in its description. ### `#[ContentCrafterTool]` arguments Name and description stay on Symfony's `#[AsTool]`. Everything this bundle asks of a tool beyond those two is on `#[ContentCrafterTool]`, which takes five named arguments. | argument | default | means | |---------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| | `summary` | required | The catalog line, see [Write the description](#write-the-description) | | `cacheableInTurn` | `false` | The same call with the same arguments runs once per turn. A repeat is not run and the model is pointed at the answer already in the conversation | | `writes` | `false` | The call changes something. Once anything in the turn has written it is refused, and the model is told to put every change still to come into one `submit_plan` | | `needsConversation` | `false` | Offered only inside a conversation | | `needsPlanning` | `false` | Offered only while a plan is being worked out or written | A tool without the attribute declares none of this, and the catalog then carries its whole description instead of a summary. The last two arguments keep a tool out of the catalog where it cannot be used. A model that calls `load_tool` on one of them anyway is told why it is not there, rather than that no such tool exists. ### Name the tool in a skill The model reaches a tool through a skill. A skill lists the tools it opens under `tools:`, and once the skill is open they can be called. `load_tool` is only offered after a skill has been opened, so list your tool in the skill that uses it: ```markdown --- name: dealer-stock description: > Answers which dealers stock a bike, and how many bikes a dealer has. tools: - count_bikes_in_stock --- ``` Genius writes a warning to the `content_crafter` log channel for every tool that no skill lists. How a skill is registered is in [Skills](../01_Configuration.md#skills). ### Query domain tools A tool that answers for a query domain is a case of its own, and it is shorter than the one above. A domain is reached by two tools, and both name the domain the same way. The one that searches it extends `AbstractQueryTool`, the one that says which fields it has extends `AbstractQuerySchemaTool`. Each adds the same single method. ```php public function getQueryDomainName(): string { return 'dealer'; } ``` Neither tool answers what permission it takes. The domain does, and the tool passes `getRequiredPermission()` on, so the permission is answered in one place. `AbstractQueryTool` resolves the domain from that name and takes the permission, the limit ceiling and the result build from it. It pulls the two services it needs in with `#[Required]` setters, so your tool keeps its own constructor and calls no `parent::__construct()`. The tool itself declares its arguments on `__invoke()`: `filters`, `countOnly`, `sortBy`, `sortDescending`, `groupBy`, `groupGranularity`, `aggregate`, `limit`, `offset`, plus whatever its own domain needs. What the grouping ones do is in [Filters](../11_Query_Filters.md#group-the-result), and the domain behind the tool is [a page of its own](Query_Domains.md). ### Reach the tool at the workbench `workbench/bin/tool.php` offers what `workbench/manifest.json` lists and refuses everything else. That file names this bundle's own tools. Write yours into `manifest.local.json` beside it, which is untracked and read as part of the same list. A name that appears in both files is an error naming both places, so a local entry can never shadow a registered tool. The entry is a tool as MCP describes one, with `name`, `description` and `inputSchema`, written out in [workbench/README.md](../../workbench/README.md#the-manifest). ```bash php workbench/bin/tool.php count_bikes_in_stock --user=admin --arguments='{"dealerId":7}' ``` ### Next That is every extension point in this chapter. Whatever you add next, the workbench is how you look at it without spending a model call: what a tool returned, how a field was processed, what a plan resolved to. Continue with [Debugging](../50_Debugging.md). --- ## Add a Translator A `$translate` in a plan carries what a field says in one language into another, see [Writing](../20_Writing.md#value-forms). Who does the carrying is not decided in the plan: the bundle ships one translator that asks a model, and a bundle can register another that asks an outside service instead. `deepl-translator-bundle` does exactly this, and is the shortest thing to read beside this page. - [Write the translator](#write-the-translator) - [Register it](#register-it) - [Which one runs](#which-one-runs) - [What a translator is not](#what-a-translator-is-not) ### Write the translator Implement `TranslatorInterface`. Autoconfiguration tags the service, so there is nothing to register beyond the service itself. | method | answers | |---------------------------|---------------------------------------------------------------------| | `getName()` | What a plan names it by, short and lowercase: `ai`, `deepl` | | `getLabelKey()` | The translation key an editor reads in the settings and in the plan | | `getUnit()` | What it bills in, `tokens` or `characters` | | `findUnavailableReason()` | Why it cannot run at all, or null. A missing key belongs here | | `supports()` | Whether it does that language pair | | `translate()` | The text in the other language, and what the one translation cost | ```php public function translate(TranslationRequest $request): TranslatedText { return new TranslatedText($theTranslation, mb_strlen($request->text)); } ``` A `TranslationRequest` carries the text, the two languages and `containsHtml`, which says whether the text has markup in it. A service that would otherwise strip the tags is told with that; one that leaves them alone ignores it. ### Register it The services go in a file of their own, loaded only where Content Crafter is installed. That way the bundle still installs without it. ```php public function prepend(ContainerBuilder $container): void { if (!$container->hasExtension('opendxp_content_crafter')) { return; } $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../../config')); $loader->load('services/third_party/opendxp_content_crafter.yaml'); } ``` Name Content Crafter under `suggest` in `composer.json`, never under `require`. ### Which one runs A plan that names none runs the one set under **Crafter-Settings > Engines**, in the *Translation* box. Nothing set means the model translator: installing a bundle is having the choice, not having made it, and content is not sent to an outside service because somebody ran `composer require`. A plan may name one under `with`. That key is in the grammar only where more than one translator is installed, so a plan can never name one that is not there. Both answers are read while the plan is checked. A translator that cannot run, or that says no to the pair, refuses the plan there rather than stopping a job on its first element. ### What a translator is not An **engine**. The six engine roles are a platform and a model, and a translator need not be either. The translator this bundle ships asks the *Translator* role; one that talks to a service asks nothing. A **generator**. A `$generate` writes a new text and takes an instruction. A translator carries an existing one across and takes none: the wording that asks for a translation is built by the caller, which is what makes one translation read like the next. --- ## Installation - [Introduction](#introduction) - [Requirements](#requirements) - [Installing the Bundle](#installing-the-bundle) - [Registering the Bundle](#registering-the-bundle) - [Running the Installer](#running-the-installer) - [Configuration](#configuration) - [Preparing the User Class](#preparing-the-user-class) - [Configuring the Search Index](#configuring-the-search-index) - [Configuring OpenID Connect](#configuring-openid-connect) - [Running the Queue Workers](#running-the-queue-workers) - [Configuration Files and Backend Settings](#configuration-files-and-backend-settings) - [Upgrading](#upgrading) - [Rebuilding the Index Mapping](#rebuilding-the-index-mapping) - [Reference](#reference) - [Configuration Reference](#configuration-reference) - [Predefined Properties](#predefined-properties) - [Worker Message Translations](#worker-message-translations) ### Introduction The DAM bundle turns the OpenDXP asset tree into a digital asset management system for a headless frontend. Users sign in through OpenID Connect, search and download assets, upload their own files, and see tags and folders in their own language. This page installs the bundle and prepares the project for it. Every feature has a page of its own, see the [README](../README.md). ### Requirements - PHP 8.3 or later - OpenDXP Core 1.5 or later - OpenDXP Admin Bundle 1.5 or later - OpenDXP Headless Bundle 1.4 or later - OpenDXP Dynamic Search Bundle 1.0 or later - OpenDXP Dynamic Search OpenSearch Index Provider 1.2 or later - OpenDXP Toolbox Bundle 1.0 or later ### Installing the Bundle Install the bundle with Composer: ```bash composer require open-dxp/dam-bundle ``` #### Registering the Bundle Add the bundle and the OAuth2 client bundle to `config/bundles.php`: ```php return [ // ... OpenDxp\Bundle\DamBundle\OpenDxpDamBundle::class => ['all' => true], KnpU\OAuth2ClientBundle\KnpUOAuth2ClientBundle::class => ['all' => true], ]; ``` #### Running the Installer ```bash bin/console opendxp:bundle:install OpenDxpDamBundle ``` The installer creates the database tables, the `UserGroup` class, the [predefined properties](#predefined-properties), the thumbnails, and the admin and frontend translations. A thumbnail or translation that exists already is kept. | Thumbnail | Size | Use | |-------------------|--------------------|---------------------------------------------------------| | `dam_list` | 500 × 500, resized | the media list | | `dam_detail` | 1600 × 1600 | the detail of an asset | | `dam_web_medium` | 1200 × 1200 | a download size for the web | | `dam_web_large` | 2000 × 2000 | a download size for the web | | `dam_ai_analysis` | 512 × 512 | the image every AI feature analyzes | Choose the thumbnails of the list, the detail and the downloads in the DAM settings. Until you choose, the list uses `dam_list` and the detail uses `dam_detail`. The installer also adds these permissions: | Permission | Grants | |------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `opendxp_dam_admin_settings` | the DAM settings, the [Translations](30_Multilingual.md#using-the-translations-panel) panel and the [Tag vocabulary](25_TagSuggestions.md#building-the-vocabulary) | | `opendxp_dam_upload_review` | the [Upload Review](10_Uploads.md#reviewing-uploads) | | `opendxp_dam_tag_review` | the [Tag suggestions](25_TagSuggestions.md#reviewing-suggestions) panel | | `opendxp_dam_ai_analyze` | starting an [analysis run](25_TagSuggestions.md#running-the-analysis) | ### Configuration #### Preparing the User Class The DAM works with your existing `User` data object class. Prepare it in the class editor: 1. Add `OpenDxp\Bundle\DamBundle\Model\ApiDamUser` as its parent class. 2. Add the field `assetWorkspaceDefinition`, the same as in the installed `UserGroup` class. Its columns `permission_view`, `permission_download` and `permission_upload` grant access to folders. 3. Add a field `groups`, a many-to-many relation that allows `UserGroup` objects. 4. Add the checkbox `isDamUser`. Only a user with this checkbox checked may use the DAM. 5. Add the checkbox `isOpenIdAware`. The OpenID sign-in sets it for the users it creates. A token refresh of such a user checks that the user is still valid at the OpenID provider. 6. Keep the field `locale` of the headless `User` class. `DamUserInterface::getLocale()` reads it. Make it mandatory while [multilingual names](30_Multilingual.md) are enabled. > [!IMPORTANT] > The `assetWorkspaceDefinition` field of the group class needs the `permission_upload` column as well. Without it, > no user may [upload](10_Uploads.md). With the Headless Ecommerce Bundle, the user class already extends a class of your project that extends `OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ApiUser`. Make that class a DAM user instead of step 1: ```php namespace App\Model; use OpenDxp\Bundle\DamBundle\Model\DamUserInterface; use OpenDxp\Bundle\DamBundle\Model\DamUserTrait; use OpenDxp\Bundle\DamBundle\Model\OpenIdAwareUserInterface; use OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ApiUser as EcommerceApiUser; abstract class ApiUser extends EcommerceApiUser implements DamUserInterface, OpenIdAwareUserInterface { use DamUserTrait; } ``` By default, the groups are objects of the class `UserGroup`. You may name another class, as long as it implements `DamUserGroupInterface`: ```yaml # config/packages/opendxp_dam.yaml opendxp_dam: user_group: class_name: 'UserGroup' ``` #### Configuring the Search Index The media list is served from an OpenSearch index. Define the index parameters: ```yaml parameters: index_stack_media_list: 'dam_media_%kernel.environment%' os_hosts: - 'http://localhost:9200' os_credentials: [ ] ``` Then register the index for the media list: ```yaml # config/packages/opendxp_dam.yaml opendxp_dam: dynamic_search: index_stack: - search_type: !php/const OpenDxp\Bundle\DamBundle\DynamicSearch\SearchTypes::DAM_MEDIA_LIST index: '%index_stack_media_list%' ``` [Image Search](20_ImageSearch.md#requirements) needs a vector-capable index on top of this. #### Configuring OpenID Connect Users sign in with OpenID Connect, for example through Azure. Put the credentials of the app registration into the environment: ```dotenv DAM_AZURE_TENANT=12345678-1234-1234-1234-123456789012 DAM_AZURE_CLIENT_ID=12345678-1234-1234-1234-123456789012 DAM_AZURE_CLIENT_SECRET=12345678-1234-1234-1234-123456789012 ``` Then configure how users are created and which of them may sign in: ```yaml # config/packages/opendxp_dam.yaml opendxp_dam: security: openid: enable_user_refresh_check: false remote_route_after_handshake: 'azure_token_handover' user_storage_folder_path: '/dam/user' #required_roles: [] required_groups: - '%env(string:default::DAM_GROUP_ID)%' assigned_groups: - 'my_dam_group_identifier' ``` New users receive a language as well, see [OpenID Users](30_Multilingual.md#openid-users). #### Running the Queue Workers Uploads, the AI analysis and the worker jobs of the frontend run in the background on two Doctrine transports: ```bash bin/console messenger:consume opendxp_dam_queue opendxp_dam_queue_fastlane ``` > [!IMPORTANT] > Without a running worker, submitted uploads stay in `processing`, approved uploads are never moved, and no > analysis run finishes. The messages of `opendxp_dam_queue` are stored in the table `messenger_opendxp_dam`, the messages of `opendxp_dam_queue_fastlane` in `messenger_opendxp_dam_fastlane`. #### Configuration Files and Backend Settings A setting lives in one of two places, depending on who decides it: | Place | Contains | Changed By | |-----------------------------------------------|-----------------------------------------------------------------------------|----------------------------| | `config/packages/opendxp_dam.yaml` | which service answers, at which address, with which model | a developer, with a deploy | | the DAM settings under **DAM** in the backend | the upload, the languages, the vocabulary, thresholds, switches and prompts | whoever runs the DAM | A backend setting starts with the value of the configuration, so an untouched installation shows what the configuration says. A text field left empty shows the configured wording as a hint and keeps it. A block whose service is not configured shows no fields and names the missing configuration key instead. ### Upgrading After every update, run the migrations of the bundle: ```bash bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\DamBundle\Migrations' ``` > [!WARNING] > Read the [changelog](../CHANGELOG.md) before you update. Some releases need a change to your classes or a > reindex. ### Rebuilding the Index Mapping If the index mapping no longer matches, rebuild it: ```bash bin/console dynamic-search:os:rebuild-index-mapping -c opendxp_dam_media ``` ### Reference #### Configuration Reference The whole configuration below `opendxp_dam`, with every key and its default. A provider takes the options of the provider you choose. The options of the other providers are shown as comments. ```yaml # config/packages/opendxp_dam.yaml opendxp_dam: user_group: class_name: UserGroup dynamic_search: index_stack: - search_type: !php/const OpenDxp\Bundle\DamBundle\DynamicSearch\SearchTypes::DAM_MEDIA_LIST index: '%index_stack_media_list%' ai: thumbnail: dam_ai_analysis embedding: provider: http # http, jina or a provider of your own. Off while null. automatic: true options: # http endpoint: 'http://dam-ai:8080' # required model: 'google/siglip2-base-patch16-256' # required api_key: null timeout: 30 # jina # api_key: '%env(JINA_API_KEY)%' # required # model: jina-embeddings-v5-omni-small # dimensions: null # at least 32 # endpoint: 'https://api.jina.ai/v1' # timeout: 30 search: vector_lower_bound: 1.09 pipeline: null pagination_depth: 10000 # at most index.max_result_window tagging: min_similarity: null # off while null automatic: false vision: provider: symfony_ai # symfony_ai or a provider of your own. Off while null. automatic: false tags: true max_proposals: 10 description: false options: platform: openai # required, a platform of the "ai" configuration model: gpt-5-mini # required language: en max_tags: 3 max_new_tags: 1 prompt: '...' # see Customizing Prompts tags_prompt: '...' new_tags_prompt: '...' description_prompt: '...' guidance: null model_options: [] vocabulary: max_characters: 7000 translation: provider: deepl # deepl, symfony_ai, http or a provider of your own. Off while null. options: # deepl api_key: '%env(DEEPL_API_KEY)%' # required server_url: null # taken from the key timeout: 30 target_languages: { en: EN-GB, pt: PT-PT } type_contexts: { tag: '...', folder: '...' } request_options: [] # symfony_ai # platform: openai # required # model: gpt-5-mini # required # prompt: '...' # type_prompts: { tag: '...', folder: '...' } # model_options: [] # http # endpoint: 'http://translation:8080' # required # api_key: null # timeout: 60 security: openid: enable_user_refresh_check: false remote_route_after_handshake: null user_storage_folder_path: null locale_claim: locale fallback_locale: null required_groups: [] required_roles: [] assigned_groups: [] ``` Each key is described here: | Key | Described In | |----------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| | `user_group.class_name` | [Preparing the User Class](#preparing-the-user-class) | | `dynamic_search.index_stack` | [Configuring the Search Index](#configuring-the-search-index) | | `ai.thumbnail` | [Covered Assets](20_ImageSearch.md#covered-assets) | | `ai.embedding.*` | [Choosing an Embedding Service](20_ImageSearch.md#choosing-an-embedding-service), [Embedding Automatically](20_ImageSearch.md#embedding-automatically) | | `ai.search.vector_lower_bound` | [Tuning the Vector Lower Bound](20_ImageSearch.md#tuning-the-vector-lower-bound) | | `ai.search.pipeline`, `ai.search.pagination_depth` | the OpenSearch search pipeline of the hybrid query and how deep it may page | | `ai.tagging.*` | [Tag Matching](25_TagSuggestions.md#tag-matching), [Setting the Suggestion Threshold](25_TagSuggestions.md#setting-the-suggestion-threshold) | | `ai.vision.*` | [Vision](25_TagSuggestions.md#vision), [Tag Proposals](25_TagSuggestions.md#tag-proposals), [Writing Descriptions](25_TagSuggestions.md#writing-descriptions) | | `ai.vocabulary.max_characters` | [Vocabulary Limits](25_TagSuggestions.md#vocabulary-limits) | | `translation.*` | [Choosing a Translation Provider](30_Multilingual.md#choosing-a-translation-provider) | | `security.openid.*` | [Configuring OpenID Connect](#configuring-openid-connect), [OpenID Users](30_Multilingual.md#openid-users) | #### Predefined Properties The installer adds three predefined properties for assets: | Key | Type | Description | |---------------------|---------|----------------------------------------------------------| | `dam_asset_poster` | `asset` | A preview image for the asset. | | `dam_is_collection` | `bool` | Promotes a folder to a collection. | | `dam_folder_name` | `text` | The display name of a folder. | None of them is inheritable. The definitions are stored in `var/config/predefined_properties/`, for example: ```yaml # var/config/predefined_properties/dam_folder_name.yaml opendxp: properties: predefined: definitions: dam_folder_name: name: 'DAM: Folder Name' description: 'Use this Property on given Folder to define a nice Name' key: dam_folder_name type: text data: '' config: '' ctype: asset inheritable: false ``` #### Worker Message Translations The installer also adds the translation keys of the messages that background jobs report: | Key | Parameters | DE | EN | |----------------------------------------------------|-------------------------|-----------------------------------------------------------------------------------|------------------------------------------------------------------------| | `opendxp.dam.worker.assets_skipped` | `skipped`, `total` | %skipped% von %total% Assets wurden übersprungen (fehlende Download-Berechtigung) | %skipped% of %total% assets were skipped (missing download permission) | | `opendxp.dam.worker.error.authentication_required` | none | Authentifizierung erforderlich | Authentication required | | `opendxp.dam.error.permission_denied` | `permission`, `assetId` | Berechtigung "%permission%" verweigert für Asset %assetId% | Permission "%permission%" denied for asset %assetId% | | `opendxp.dam.error.asset_not_found` | `assetId` | Asset mit ID "%assetId%" nicht gefunden | Asset with ID "%assetId%" not found | | `opendxp.dam.error.collection_not_found` | `collectionId`, `type` | %type% mit ID "%collectionId%" nicht gefunden | %type% with ID "%collectionId%" not found | | `opendxp.dam.error.worker_processing_failed` | `jobId` | Verarbeitung des Jobs "%jobId%" fehlgeschlagen | Processing of job "%jobId%" failed | | `opendxp.dam.error.no_processor_found` | `payloadClass` | Kein Processor für Payload "%payloadClass%" gefunden | No processor found for payload "%payloadClass%" | | `opendxp.dam.error.invalid_data_object` | none | Ungültiges Datenobjekt | Invalid data object | | `opendxp.dam.error.exception` | `message` | Ein Fehler ist aufgetreten: %message% | An error occurred: %message% | --- ## Uploads - [Introduction](#introduction) - [Configuration](#configuration) - [Upload Settings](#upload-settings) - [Allowing CORS Headers](#allowing-cors-headers) - [Restricting Who May Create Tags and Folders](#restricting-who-may-create-tags-and-folders) - [Uploading Files](#uploading-files) - [Opening a Draft](#opening-a-draft) - [Sending the Files](#sending-the-files) - [Checking the Files](#checking-the-files) - [Describing the Files](#describing-the-files) - [Submitting the Job](#submitting-the-job) - [Following the Job](#following-the-job) - [Reviewing Uploads](#reviewing-uploads) - [Editing Files](#editing-files) - [Review Marks](#review-marks) - [Reviewing New Tags](#reviewing-new-tags) - [Reviewing New Folders](#reviewing-new-folders) - [Translating New Tags and Folders](#translating-new-tags-and-folders) - [Batch Editing](#batch-editing) - [Approving and Rejecting](#approving-and-rejecting) - [Email Notifications](#email-notifications) - [Writing the Templates](#writing-the-templates) - [Cleaning Up Abandoned Drafts](#cleaning-up-abandoned-drafts) - [API Reference](#api-reference) - [Request Headers](#request-headers) - [Endpoints](#endpoints) - [File Fields](#file-fields) - [tus Requests](#tus-requests) - [Protocol Errors](#protocol-errors) - [File Statuses](#file-statuses) - [Job Statuses](#job-statuses) ### Introduction The DAM lets the users of your frontend upload files themselves. A user collects files in an upload job, describes each file, chooses a target folder, and may propose new tags and folders. Once the user submits the job, a reviewer checks it in the OpenDXP backend, and only an approved job moves its files into the DAM. For example, a photographer who has finished a shoot may upload forty pictures into the folder of a campaign, propose the sub folder `Shooting 02` and tag the pictures with a new tag `Skyline` below `Cities`. The reviewer corrects a few titles and approves the job. The bundle then creates the folder and the tag and moves the pictures into place. Files are uploaded with the [tus](https://tus.io) protocol, so a client may resume an interrupted upload. ### Configuration #### Upload Settings The upload is configured in the DAM settings, on the **Data Upload** tab: | Setting | Description | |-------------------------|----------------------------------------------------------------------------------------------| | Upload Root Path | The folder below which the bundle keeps a review folder `upload-{jobId}` for every submitted job. | | Notification Recipients | The backend users who receive an email when a job is submitted for review. | | Allowed Asset Types | The asset types a user may upload. Leave it empty to allow every type. | | Max File Size (MB) | The largest file a user may upload. The default is 1024 MB. | A user may only upload into folders for which a workspace grants the `upload` permission, see [Preparing the User Class](00_Installation.md#preparing-the-user-class). > [!IMPORTANT] > Submitted jobs are processed by the `opendxp_dam_queue` worker, see > [Running the Queue Workers](00_Installation.md#running-the-queue-workers). Without an Upload Root Path, every > submitted job fails. #### Allowing CORS Headers Browser clients send and read tus headers, so allow and expose them in your `config/packages/opendxp_headless.yaml`: ```yaml opendxp_headless: cors: allow_headers: - 'tus-resumable' - 'upload-length' - 'upload-offset' - 'upload-metadata' expose_headers: - 'location' - 'tus-resumable' - 'tus-version' - 'tus-extension' - 'tus-max-size' - 'upload-offset' - 'upload-length' ``` Without these headers, the CORS preflight fails and no upload starts. #### Restricting Who May Create Tags and Folders By default, every user may propose new tags and folders. You may restrict this on the **Languages** tab of the DAM settings: | Setting | Default | Description | |--------------------------------------------|---------|-----------------------------------------------------------------| | Users may create structure (tags, folders) | on | Allows frontend users to propose new tags and folders. | | Also users with another language | off | Shown while [multilingual names](30_Multilingual.md) are enabled. | While multilingual names are enabled and the second setting is off, only users whose language is the base language may create tags and folders. A region of the base language is treated as the base language, so with the base language `de`, a user with `de_AT` may create them. A user without a language, or with a language the system does not support, is treated as a user of the base language. Reviewers in the backend are not bound by these settings. Every job response has the field `structureCreationAllowed`, which indicates whether the authenticated user may create tags and folders: ```json { "jobId": "01a0b3cc-87a8-7974-a916-f10fecfcec7e", "status": "draft", "structureCreationAllowed": false } ``` While it is `false`, hide the input of new tags and folders. Saving a file with a new tag or with `targetSubFolders` returns `403` "Creating tags and folders is not allowed". The submit checks this again, because the settings may have changed in the meantime. ### Uploading Files The frontend uploads files in six steps. Every request needs the headers listed under [Request Headers](#request-headers). #### Opening a Draft A user has one draft at a time. The first call creates it, and every later call returns the same job: ``` POST /dam/upload/jobs {} -> { "jobId": "01a0b3cc-87a8-7974-a916-f10fecfcec7e", "status": "draft", ... } ``` The job keeps the language of `X-OpenDxp-Api-Locale` and the site of `X-OpenDxp-Api-Site`, and the bundle uses both for its emails. Use `GET /dam/upload/jobs/{jobId}` to read the files that a draft already contains. To discard a draft with its uploaded data, send `DELETE /dam/upload/jobs/{jobId}`. #### Sending the Files Uploads use tus 1.0.0 with the creation extension. With [tus-js-client](https://github.com/tus/tus-js-client), point `endpoint` at the job and pass the headers and the file name: ```js import * as tus from 'tus-js-client'; const upload = new tus.Upload(file, { endpoint: `https://api.example.com/dam/upload/${jobId}`, headers: { 'Authorization': `Bearer ${token}`, 'X-OpenDxp-Api-Locale': 'de', 'X-OpenDxp-Api-Site': '1', }, metadata: { filename: file.name, filetype: file.type }, chunkSize: 10 * 1024 * 1024, }); upload.start(); ``` The client handles creation, chunking and resuming. The last segment of `upload.url` is the `fileId` of the file. Other tus clients work as well, as long as they send the same headers. The raw requests are listed under [tus Requests](#tus-requests). > [!IMPORTANT] > The tus endpoints only answer over HTTPS, and `filename` must be part of the metadata, including the extension. #### Checking the Files When the last byte arrives, the bundle checks the file against the allowed asset types and the maximum size, and asks OpenDXP whether it accepts the file as an asset. The result is the status of the file in the job: ``` GET /dam/upload/jobs/{jobId} -> { "jobId": "...", "status": "draft", "files": [ { "fileId": 76, "declaredFilename": "grundriss.jpg", "status": "upload_failed", "failureReason": "Image dimensions of grundriss.jpg are too large. Max size: 40 Megapixels. Suggestion: resize to 6600×4700 pixels or smaller." } ] } ``` `failureReason` is written for the user and may be displayed as it is. A refused file keeps its row, but its bytes are discarded. Remove it with `DELETE /dam/upload/jobs/{jobId}/files/{fileId}` and upload a different file. #### Describing the Files Each file needs a target folder before the job can be submitted. Everything else is optional: ``` PATCH /dam/upload/jobs/{jobId}/files/{fileId} { "title": "Skyline Singapore At Night", "description": "Taken from Marina Bay.", "copyright": "ACME AG", "targetFolderId": 13, "targetSubFolders": [ { "name": "Campaign 2026", "isCollection": true }, { "name": "Shooting 02" } ], "tagAssignments": [{ "tagId": 2 }, { "name": "Travel", "parentId": 4 }] } ``` The target folder comes from `GET /dam/upload/folders`. Existing tags come from `GET /dam/upload/tags` or `GET /dam/tags?term=`, and a new tag goes below the tag in `parentId`. Send the names of new tags and folders as the user typed them. The bundle creates them when the job is approved. The rules for every field are listed under [File Fields](#file-fields). > [!NOTE] > A new tag or folder is a proposal. Once a reviewer edits it, the job returns the name of the reviewer instead of > the name the user typed. The job keeps no history of the proposal. #### Submitting the Job Once every file is uploaded and has a target folder, submit the job: ``` POST /dam/upload/jobs/{jobId}/submit {} -> { "jobId": "...", "status": "processing", ... } ``` The submit returns `409` unless the job has at least one file and every file is `upload_verified` and has a `targetFolderId`. The job detail shows which file is missing what. After the submit, the job is read only, and adding, changing or removing files returns `409`. A queue worker then stores the files in the review folder and moves the job to `submitted`. A file that fails at this point becomes `upload_failed` with a `failureReason`, and the other files go on to the review. If no file makes it, the job is `failed`. #### Following the Job `GET /dam/upload/jobs` returns the own jobs of the user, newest first. You may filter by one of the [job statuses](#job-statuses): ``` GET /dam/upload/jobs?status=submitted ``` An unknown status returns `400`. The statuses `processing` and `approved` last as long as a queue worker needs, so treat both as work in progress. The user receives an email once the job is completed or rejected. ### Reviewing Uploads Submitted jobs appear in **DAM > Upload Review**, which requires the `opendxp_dam_upload_review` permission. Every change you make is stored in the job. The bundle creates no tag, folder or asset before you approve the job. > [!NOTE] > Once you edit a new tag or folder, the frontend shows your name for it instead of the name the user typed. The job > keeps no history of the proposal. #### Editing Files Double-click a file to edit its file name, title, description, copyright, target folder, new folders and tags. The extension cannot be changed. If the file name is taken at the target, the bundle reports the name it will use instead. To change several files at once, see [Batch Editing](#batch-editing). #### Review Marks The bundle marks every tag and folder that comes from the upload with an icon. In the tag tree, these tags are also shown in orange: | Tooltip | Meaning | |--------------------------------------------------------------|---------------------------------------------------------------| | Chosen by the user | An existing tag that the user assigned. | | Proposed by the user, not reviewed yet | A new tag or folder that nobody has edited yet. | | Reviewed, translations missing | A reviewed tag or folder that lacks at least one translation. | | Reviewed and translated, created when the upload is approved | A reviewed tag or folder with every translation. | Translations can only be missing while [multilingual names](30_Multilingual.md) are enabled. An existing tag that you check yourself is not marked. #### Reviewing New Tags A new tag belongs to the job, not to a file. The tag tree of every file lists all new tags of the job, and checking one assigns it once you save the file. Changes to the new tag itself are saved at once and apply to every file that has it: | Action | Result | |-----------------------------------|-------------------------------------------------------------------------------------------| | Right-click a tag, **New tag** | Adds a new tag below it, also below a new tag, and assigns it to the files of the window. | | Double-click, or **Edit new tag** | Opens the [name dialog](#translating-new-tags-and-folders). **Apply** marks the tag as reviewed. | | Drag onto or between tags | Places the tag below or next to them. The new tags below it move along. | | **Discard new tag** | Removes the tag and the new tags below it from every file, after a confirmation. | If you rename or move a new tag onto another new tag at the same place, the two become one tag. Names are compared regardless of case. A new tag stays in the job while at least one file has it or a new tag below it. #### Reviewing New Folders The **Sub Folders** grid lists the new folders of a file, starting with the outermost one. Files with the same target folder and the same folders above a new folder share that folder: | Action | Applies To | |------------------------------------|-------------------------------------------------------------------| | Edit icon, then **Apply** | Every file that shares the folder, at once. Marks it as reviewed. | | **Collection** checkbox | Every file that shares the folder, at once. | | **Add folder**, reordering, delete | This file, when you save it. | The edit icon opens the [name dialog](#translating-new-tags-and-folders). The **Target** line below the grid shows the resulting path. > [!NOTE] > If a proposed folder already exists and the uploader may upload into it, the bundle uses it as the target folder > and removes the row. It checks this on every save and again before it moves the files. #### Translating New Tags and Folders New tags and folders are named in the name dialog. It has a field for the base name and, while [multilingual names](30_Multilingual.md) are enabled, a field for every other language. A proposal typed in another language is shown in the field of that language, with an empty base name. > [!TIP] > The **Translate empty fields** button of the dialog fills every empty field from the base name, or from the first > filled field while the base name is empty. See [Using the Name Dialog](30_Multilingual.md#using-the-name-dialog). #### Batch Editing **Batch Edit** changes every selected file, and fields you leave empty stay unchanged. For tags, you may choose a mode: - **Add** adds the checked tags to the tags of each file. - **Replace** makes the checked tags the only tags of each file, after a confirmation. With no tag checked, it removes every tag. A new tag that you create in the batch window is assigned to every selected file at once. Folders in the **Sub Folders** grid replace the new folders of every selected file. #### Approving and Rejecting When you approve a job, a queue worker creates the new tags and folders and moves the files: - A new tag is created where you placed it, with its translations and after the new tags above it. A tag with the same name at that place, regardless of case, is reused and only receives the translations it lacks. - A new folder uses its name as `dam_folder_name` and receives its collection flag and translations. A folder with the same key is reused if the uploader may upload into it. Otherwise the new key ends in a number, such as `_1`. - A file whose name is taken at the target is stored with a number before its extension, such as `skyline_1.jpg`. The title, description and copyright become the metadata of the asset, and the asset receives a note `Frontend upload` with the uploader and the job. > [!WARNING] > An untouched proposal is created as the user typed it. Nothing is translated, and a name in another language > becomes the base name. When you reject a job, the bundle deletes the review folder with the uploaded files. The optional reason is returned to the user in `rejectionReason`. ### Email Notifications The bundle sends three emails through the mail resolver of the headless bundle: | Name | Recipient | Sent When | |---------------------------|-------------------------------------------------|----------------------------------------------| | `dam_upload_job_review` | every Notification Recipient with an email address | the files of a submitted job are ready for review | | `dam_upload_job_approved` | the user who uploaded the job | the files of an approved job are in the DAM | | `dam_upload_job_rejected` | the user who uploaded the job | a reviewer rejects the job | Add a template path for each of them to your `config/packages/opendxp_headless.yaml`. The paths are up to you: ```yaml opendxp_headless: email_template_paths: dam_upload_job_review: path: '/{_site}/{_locale}/mail/dam-upload-job-review' dam_upload_job_approved: path: '/{_site}/{_locale}/mail/dam-upload-job-approved' dam_upload_job_rejected: path: '/{_site}/{_locale}/mail/dam-upload-job-rejected' ``` `{_site}` and `{_locale}` are the site and the language that the job kept when its draft was opened. #### Writing the Templates Every template receives `job`, the `UploadJob` entity. Use `job.requestedBy.*` for the fields of the user, because those are specific to your project. `dam_upload_job_review` also receives `reviewFolderUrl`, a link that opens the review folder in the asset tree. A button on the folder leads on into the review panel. ```html

Hello,

{{ job.requestedBy.firstname }} {{ job.requestedBy.lastname }} submitted a new upload for review ({{ job.files|length }} file(s)).

{% if reviewFolderUrl %}

Open the upload review

{% endif %} ``` > [!IMPORTANT] > The mail is sent by a queue worker, so the host of `reviewFolderUrl` comes from the site marked as **General > Domain** in the headless site settings. Without it, or once the review folder is gone, `reviewFolderUrl` is `null`. The two emails to the user: ```html

Hello {{ job.requestedBy.firstname }},

Your upload of {{ job.files|length }} file(s) is now available in the DAM.

``` ```html

Hello {{ job.requestedBy.firstname }},

Your upload of {{ job.files|length }} file(s) was rejected.

{{ job.rejectionReason }}

``` ### Cleaning Up Abandoned Drafts A draft that is never submitted leaves its data in the temporary storage. The OpenDXP maintenance task `dam_stale_upload_job_cleanup` deletes drafts that were created more than seven days ago, together with their data. ### API Reference The request and response schemas of every endpoint are also part of the OpenAPI document. #### Request Headers | Header | Value | |------------------------|------------------------------| | `Authorization` | `Bearer ` | | `X-OpenDxp-Api-Locale` | the language of the user, for example `de` | | `X-OpenDxp-Api-Site` | the site id | | `Content-Type` | `application/json` | > [!IMPORTANT] > `Content-Type: application/json` is required on every JSON call, including `DELETE`, which has no body. Without it > the API returns `415`. The tus requests use their own content type. #### Endpoints | Method | Path | Description | |-----------|-------------------------------------------|---------------------------------------------------------------------| | `GET` | `/dam/settings` | `uploadAllowedAssetTypes`, `uploadMaxFileSizeBytes`, `guidelines` and `locale` | | `GET` | `/dam/tags` | tag search in the allowed tag branches with `?term=` of at least two characters, returns `id`, `name` and `path` | | `GET` | `/dam/upload/folders` | the folder tree, `?parentId=` for the sub folders of a folder | | `GET` | `/dam/upload/tags` | the tag tree, `?parentId=` for the child tags of a tag | | `POST` | `/dam/upload/jobs` | opens or resumes the draft | | `GET` | `/dam/upload/jobs` | the own jobs of the user, `?status=` to filter | | `GET` | `/dam/upload/jobs/{jobId}` | one job with all its files | | `DELETE` | `/dam/upload/jobs/{jobId}` | cancels the draft, `409` once it is submitted | | `OPTIONS` | `/dam/upload/{jobId}` | tus discovery | | `POST` | `/dam/upload/{jobId}` | tus creation | | `HEAD` | `/dam/upload/{jobId}/{fileId}` | tus offset | | `PATCH` | `/dam/upload/{jobId}/{fileId}` | tus chunk | | `PATCH` | `/dam/upload/jobs/{jobId}/files/{fileId}` | title, description, copyright, tags and target folder of a file | | `DELETE` | `/dam/upload/jobs/{jobId}/files/{fileId}` | removes a file from the draft, `409` once it is submitted | | `POST` | `/dam/upload/jobs/{jobId}/submit` | submits the job for review | A job has the fields `jobId`, `status`, `creationDate`, `submittedAt`, `rejectionReason` and `structureCreationAllowed`. The job list and the job detail add its `files`. A job or file of another user returns `404`. #### File Fields | Field | Rules | |--------------------|----------------------------------------------------------------------------------------------------------| | `targetFolderId` | A folder from `GET /dam/upload/folders` whose `permissions` contain `upload`. Another folder, or a folder outside the DAM, returns `403`. An unknown id returns `400`. Required for the submit. | | `targetSubFolders` | Folders that do not exist yet, outermost first, relative to the target folder. Each has a `name` of at most 255 characters and an optional `isCollection`. | | `tagAssignments` | Each entry has either the `tagId` of an existing tag or the `name` of a new tag, never both. A new tag also needs the `parentId` of a tag from `GET /dam/upload/tags`. Another parent returns `400`. A name has at most 255 characters. A `tagId` that no longer exists is dropped. | | `title` | A display name, not the name under which the file is stored. It may contain spaces and punctuation and does not have to be unique. Without a title, the asset uses the file name without its extension. | | `description` | Free text. | | `copyright` | Free text. | A node of `GET /dam/upload/folders` has `id`, `key`, `name`, `path`, `isCollection`, `hasSubFolders` and `permissions`. Without `parentId`, the endpoint returns the folders at which the tree of the user starts. Folders without the `upload` permission are part of the tree for navigation only. Display them, but do not allow selecting them or adding sub folders below them. A node of `GET /dam/upload/tags` has `id`, `name`, `path` and `hasChildren`. Without `parentId`, the endpoint returns the roots of the [allowed tag branches](25_TagSuggestions.md#building-the-vocabulary). A tag outside these branches returns `404`. The key of a new folder is its name without control characters, slashes and the characters `#?*:\<>|"%+`, and without dots and spaces at its ends. Case and inner spaces stay, so `Campaign 2026` keeps the key `Campaign 2026` and the name as its display name. The asset keeps the uploaded file name as its key, and downloads use that name, including the extension. #### tus Requests Announce a file: ``` POST /dam/upload/{jobId} Tus-Resumable: 1.0.0 Upload-Length: 5960367 Upload-Metadata: filename c2t5bGluZS5qcGc=,filetype aW1hZ2UvanBlZw== -> 201, Location: /dam/upload/{jobId}/76 ``` `Upload-Metadata` uses the tus encoding `key base64value`, with pairs separated by commas. `filename` is required, `filetype` is optional and is verified on the server. `Location` may be relative and is resolved against the request origin. Its last segment is the `fileId`. Send the bytes: ``` PATCH /dam/upload/{jobId}/76 Tus-Resumable: 1.0.0 Upload-Offset: 0 Content-Type: application/offset+octet-stream -> 204, Upload-Offset: 10485760 ``` The client chooses the chunk size. `HEAD` on the same URL returns the current `Upload-Offset` and the `Upload-Length`, and is used to resume. `OPTIONS /dam/upload/{jobId}` returns `Tus-Version`, `Tus-Extension` and `Tus-Max-Size`. #### Protocol Errors These errors concern the protocol, not the file: | Status | Reason | |--------|--------------------------------------------------------------------------------------------------------------------------------| | `400` | `Upload-Length` or `Upload-Offset` is missing or malformed, `Upload-Length` is zero, `Upload-Defer-Length` is sent, or `filename` is missing, has no usable character or is longer than 255 characters | | `403` | the user has no folder with the `upload` permission | | `404` | the job or the file does not exist or belongs to another user | | `409` | the offset does not match, the file is no longer pending, the job is not a draft, or another request holds the file | | `412` | `Tus-Resumable` is missing or is not `1.0.0` | | `413` | the announced length exceeds the maximum file size, or a chunk goes beyond the announced length | | `415` | the `PATCH` is missing `Content-Type: application/offset+octet-stream` | #### File Statuses A file has the fields `fileId`, `declaredFilename`, `declaredSizeBytes`, `currentOffset`, `status` and `failureReason`. In the job detail, it also has `title`, `description`, `copyright`, `tagAssignments`, `targetFolderId` and `targetSubFolders`. | Status | Description | |--------------------|----------------------------------------------------------------| | `upload_pending` | Bytes are missing. `currentOffset` reports how many arrived. | | `upload_verified` | The file has been accepted. | | `upload_promoted` | The file is in the review folder. | | `upload_completed` | The file has been moved into the DAM. | | `upload_failed` | The file has been refused, see `failureReason`. | #### Job Statuses | Status | Description | |--------------|--------------------------------------------------------------| | `draft` | The user is working on the job. | | `processing` | The job has been submitted, and the files are being prepared for the review. | | `submitted` | The job waits for a reviewer. | | `approved` | The job has been approved, and the files are being moved into the DAM. | | `completed` | The files are in the DAM. | | `rejected` | A reviewer has refused the job, see `rejectionReason`. | | `canceled` | The user has cancelled the draft. | | `failed` | The bundle could not process the job. | --- ## Image Search - [Introduction](#introduction) - [Requirements](#requirements) - [Choosing an Embedding Service](#choosing-an-embedding-service) - [Using SigLIP on Your Own Server](#using-siglip-on-your-own-server) - [Using Jina AI](#using-jina-ai) - [Using a Managed API](#using-a-managed-api) - [Indexing Assets](#indexing-assets) - [Embedding Automatically](#embedding-automatically) - [Covered Assets](#covered-assets) - [Search Results](#search-results) - [What a Vector Captures](#what-a-vector-captures) - [Languages and Spelling](#languages-and-spelling) - [Tuning the Vector Lower Bound](#tuning-the-vector-lower-bound) - [Changing the Embedding Model](#changing-the-embedding-model) - [Custom Embedding Providers](#custom-embedding-providers) ### Introduction Image search finds an asset by what its picture shows, in addition to everything the media search already finds by file name, tags and metadata. Someone looking for a mountain gets the photo of a mountain, whether or not the word appears anywhere on the asset. To do this, an embedding service turns every picture into a vector, and every search term into another one. The DAM compares the two. The same vectors also drive [tag matching](25_TagSuggestions.md#tag-matching). ### Requirements The search index has to store vectors. That means OpenSearch as the index provider, with `index.knn: true` on the index. > [!IMPORTANT] > OpenSearch needs `index.knn: true` before it accepts a `knn_vector` mapping. Set it before the first indexing run. Image search stays off until an embedding service is configured. The AI settings name the missing configuration key in place of its fields. ### Choosing an Embedding Service The model behind the service decides which languages a search term may be written in. The bundle does not translate a term before it is embedded: | Service | Languages | Licence | Runs On | |-----------------------------------------------------------------|-------------------------------------------------|---------------------------------------------|-------------------------| | [SigLIP on your own server](#using-siglip-on-your-own-server) | the European languages measured below | Apache 2.0 | your server, CPU | | [Jina AI](#using-jina-ai) | many, in one space with images, audio and video | weights CC BY-NC 4.0, commercial use by API | the Jina API | | [A managed API](#using-a-managed-api), such as Voyage or Cohere | depends on the model | the terms of the provider | the API of the provider | #### Using SigLIP on Your Own Server The `http` provider sends pictures and terms to a service of your own. The [SigLIP Embedding Service](20_ImageSearch_SiglipService.md) page contains the complete source of one that runs `google/siglip2-base-patch16-256` on a CPU. Once it is running, point the provider at it: ```yaml # config/packages/opendxp_dam.yaml opendxp_dam: ai: embedding: provider: 'http' options: endpoint: 'http://dam-ai:8080' model: 'google/siglip2-base-patch16-256' timeout: 30 ``` | Option | Default | Description | |------------|----------|-------------------------------------------------------| | `endpoint` | required | The base address. The provider appends `/embeddings`. | | `model` | required | The model name sent with every request. | | `api_key` | none | Sent as a bearer token when it is set. | | `timeout` | `30` | Seconds per request. | The same picture, found by the same concept in five languages with this model: | | German | English | French | Italian | Polish | |-----------------|--------|---------|--------|---------|--------| | Skyscrapers | 1.1174 | 1.1248 | 1.0959 | 1.1197 | 1.1100 | | A logo on white | 1.1125 | 1.1150 | 1.1169 | 1.1148 | 1.1100 | A tag tree in one of these languages needs nothing else. For a language the model saw far less of, choose another service, and measure it against your own collection first. #### Using Jina AI The `jina` provider uses the [Jina embeddings API](https://jina.ai/embeddings). Jina expects every input as an object with a `text` or an `image` key, which is why the `http` provider cannot talk to it: ```yaml opendxp_dam: ai: embedding: provider: 'jina' options: api_key: '%env(JINA_API_KEY)%' ``` | Option | Default | Description | |--------------|---------------------------------|-------------------------------------------------------------| | `api_key` | required | The key of your Jina account. | | `model` | `jina-embeddings-v5-omni-small` | The model. | | `dimensions` | none | The vector size, 32 or more. Without it, the model decides. | | `endpoint` | `https://api.jina.ai/v1` | The base address. | | `timeout` | `30` | Seconds per request. | The provider sends every term as a `retrieval.query` and every picture as a `retrieval.passage`, and asks for normalized vectors, because the index compares them by inner product. > [!WARNING] > Jina charges by token. A picture of 1024 by 768 pixels costs about 770 tokens, a search term about ten, and every > search term is one call. Limit who may search and how often. The weights of `jina-embeddings-v5-omni-small` are licensed under CC BY-NC 4.0, so you may not run them on your own server for commercial use. Commercial use goes through the Jina API. #### Using a Managed API Services such as Voyage AI and Cohere embed pictures and text into one space, but none of them accepts the request of the `http` provider: | Service | Model | How a Picture Is Sent | |-------------------------------------------------------------------|-------------------------|--------------------------------------------------| | [Voyage AI](https://docs.voyageai.com/docs/multimodal-embeddings) | `voyage-multimodal-3.5` | `inputs[].content[]` with `type: "image_base64"` | | [Cohere](https://docs.cohere.com/reference/embed) | `embed-v4.0` | `images: ["data:;base64,..."]` | Such a service needs a provider class of its own, see [Custom Embedding Providers](#custom-embedding-providers). ### Indexing Assets An asset receives its vector while it is indexed: ```bash bin/console dynamic-search:run ``` From then on, the search finds assets by their content. A picture is only embedded again once its bytes change, so an ordinary reindex costs nothing, and a fresh search index costs one call per picture. #### Embedding Automatically By default, every picture is embedded while it is indexed. You may turn this off: ```yaml opendxp_dam: ai: embedding: automatic: false ``` > [!TIP] > Turn it off on a paid endpoint. An indexing run is started by the whole project, so a developer who reindexes > their objects would pass every DAM asset through the service as well. While it is off, only the action **Create image vectors** writes vectors, see [Running the Analysis](25_TagSuggestions.md#running-the-analysis). The switch is also part of the AI settings. #### Covered Assets Every asset for which the DAM can produce a picture is embedded: images, and the preview page of a video or a document. An asset without a picture is skipped. The picture is the thumbnail `dam_ai_analysis`, which the installer creates. You may name another one under `opendxp_dam.ai.thumbnail`. ### Search Results #### What a Vector Captures A picture becomes one vector, and everything in the picture competes for room in it: | Query | Result | |-----------------------------------------------------|-----------| | beach at sunset, person with a laptop, overall mood | found | | a cow filling the frame | found | | the small logo in the corner | not found | | text written in the image | not found | | "the third person from the left" | not found | For details that a picture only shows in passing, tags and metadata remain the better answer. That is what [tag matching](25_TagSuggestions.md#tag-matching) is for. #### Languages and Spelling A multilingual model handles other languages inside the vector space, at no extra call. What a model does not forgive is a term spelled differently from the tag tree. A Polish tag tree writes `wieżowce`, while people type `wiezowce`: | Term | Top Hit | |------------|---------------------------| | `wiezowce` | the wrong picture, 1.0777 | | `wieżowce` | the right picture, 1.1100 | The same holds for every language whose keyboard form differs from its written form. The bundle ships no rule for this, because the right rule depends on the language and the installation. A [custom embedding provider](#custom-embedding-providers) may restore the diacritics in `embedText()`. ### Tuning the Vector Lower Bound A vector search always answers. Ask for something the DAM does not have, and it still returns the least unlike pictures. Because the lexical and the vector scores are normalized against whatever came back, the best of these misses would be mixed into the result as if it were a hit. `vector_lower_bound` anchors the scale to an absolute score, below which a vector hit counts for nothing: ```yaml opendxp_dam: ai: search: vector_lower_bound: 1.09 ``` The default `1.09` was measured against `google/siglip2-base-patch16-256` over a collection of a thousand photographs. For another model or another kind of collection, measure the bound: ```bash bin/console opendxp:dam:ai:calibrate bin/console opendxp:dam:ai:calibrate -t "hippo in space" -t "chainsaw made of marzipan" ``` The command sends terms that nothing in the DAM can answer and prints the score that they reach. You may pass your own terms with `-t` when a built-in one could match something in your DAM, the hits per term with `--hits` (default `5`) and the percentile of the recommendation with `-p` (default `95`). Put the value into `vector_lower_bound`. The next `bin/console dynamic-search:run -c opendxp_dam_media` builds the search pipeline with it. > [!NOTE] > The printed value is a starting point. Run a few searches that have to keep working and check that their hits stay > above it. A bound that is too high drops real results for niche terms. ### Changing the Embedding Model Vectors of two models cannot be compared, so a new model needs new tag vectors, a new bound and a new index: ```bash bin/console opendxp:dam:ai:rebuild-tag-vectors bin/console opendxp:dam:ai:calibrate bin/console dynamic-search:run ``` ### Custom Embedding Providers A provider implements `EmbeddingProviderInterface` and is tagged with `dam.ai.embedding_provider`. The `identifier` of the tag is the name you configure under `ai.embedding.provider`: ```php interface EmbeddingProviderInterface extends AiProviderInterface { public function info(): EmbeddingInfo; public function embedImage(string $bytes, string $mimeType): Embedding; public function embedText(string $text): Embedding; } ``` `configureOptions()` declares the keys that the class reads from `options`, and `info()` returns the model name and the vector length. Register the class and name it: ```yaml services: App\Dam\VoyageEmbeddingProvider: tags: - { name: dam.ai.embedding_provider, identifier: 'voyage' } ``` ```yaml # config/packages/opendxp_dam.yaml opendxp_dam: ai: embedding: provider: 'voyage' options: endpoint: 'https://api.voyageai.com/v1' model: 'voyage-multimodal-3.5' api_key: '%env(VOYAGE_API_KEY)%' ``` The keys under `options` are read by your class, so it decides them. Check the documentation of the service for current model names, limits and prices. > [!WARNING] > The vector length from `info()` goes into the index mapping. A length that the vectors do not have makes > OpenSearch reject every document, so read it from the service instead of writing a constant. The `http` provider > embeds one short text and counts the result. --- ## SigLIP Embedding Service - [Introduction](#introduction) - [Running the Service in ddev](#running-the-service-in-ddev) - [Choosing a Model](#choosing-a-model) - [Text Requirements of SigLIP](#text-requirements-of-siglip) - [Service Source](#service-source) - [`app.py`](#apppy) - [`requirements.txt`](#requirementstxt) - [`Dockerfile`](#dockerfile) - [Reference](#reference) - [Routes](#routes) - [Request and Response Format](#request-and-response-format) ### Introduction This page contains a complete embedding service for [image search](20_ImageSearch.md) that you may run yourself. It serves `google/siglip2-base-patch16-256`, which is free for commercial use under Apache 2.0, on a CPU. The bundle talks to it through the `http` provider, configured as described in [Using SigLIP on Your Own Server](20_ImageSearch.md#using-siglip-on-your-own-server). The service is one FastAPI file, because two details of SigLIP have to be right and most ready-made servers get them wrong, see [Text Requirements of SigLIP](#text-requirements-of-siglip). ### Running the Service in ddev Copy the three files of the [Service Source](#service-source) into `.ddev/dam-ai/` and add the service to ddev: ```yaml # .ddev/docker-compose.dam-ai.yaml services: dam-ai: container_name: ddev-${DDEV_SITENAME}-dam-ai hostname: ${DDEV_SITENAME}-dam-ai build: context: dam-ai expose: - "8080" environment: - EMBEDDING_MODEL=google/siglip2-base-patch16-256 - TORCH_THREADS=8 labels: com.ddev.site-name: ${DDEV_SITENAME} com.ddev.approot: $DDEV_APPROOT volumes: - dam_ai_cache:/cache web: links: - dam-ai:dam-ai volumes: dam_ai_cache: ``` `ddev restart` builds the image. On a server, the same image runs next to your other services, and only `endpoint` in the bundle configuration changes. > [!NOTE] > The first build downloads torch and the model and takes a while. Once the service is up, > `curl http://dam-ai:8080/health` from the web container returns the model name. ### Choosing a Model `EMBEDDING_MODEL` accepts any SigLIP 2 checkpoint. The default is `google/siglip2-base-patch16-256`. The larger `google/siglip2-so400m-patch16-512` separates right from wrong hits about twice as clearly, but needs eighteen times the compute. On a CPU, that turns a run over 100,000 assets from one night into five days, which is why the small variant is the default. > [!WARNING] > A new model makes every stored vector useless, see > [Changing the Embedding Model](20_ImageSearch.md#changing-the-embedding-model). ### Text Requirements of SigLIP The text side of SigLIP has two hard requirements from its training, so the service applies both and has no setting for them: | Requirement | Reason | |------------------------|---------------------------------------------------------------------------------------------| | padded to `max_length` | Dynamic padding collapses text embeddings into a near-constant vector. | | lowercased | The training captions were lowercased, so capitalized input lands outside the distribution. | The effect of the casing alone, measured against three images in the test DAM: | Query | As Written | Lowercased | |--------------------------|-----------------------------------------|-----------------------------------------| | Volkswagen Polo | wrong image, +0.0700 | right image, +0.1115 | | A City Skyline | wrong image, +0.0713 | right image, +0.1490 | | Skyline einer Grossstadt | right image, +0.0986, runner-up +0.0762 | right image, +0.1280, runner-up +0.0147 | A server that skips either step returns embeddings that look fine and rank badly. ### Service Source Put these three files next to each other. #### `app.py` ```python import base64 import binascii import io import os from typing import Literal import torch from fastapi import FastAPI, HTTPException from PIL import Image from pydantic import BaseModel from transformers import AutoModel, AutoProcessor MODEL_ID = os.getenv("EMBEDDING_MODEL", "google/siglip2-base-patch16-256") torch.set_num_threads(int(os.getenv("TORCH_THREADS", os.cpu_count() or 1))) processor = AutoProcessor.from_pretrained(MODEL_ID) model = AutoModel.from_pretrained(MODEL_ID, dtype=torch.float32).eval() app = FastAPI(title="OpenDXP DAM AI service") class EmbeddingRequest(BaseModel): input: list[str] model: str | None = None def decode_image(value: str) -> Image.Image: payload = value.split(",", 1)[1] if value.startswith("data:") else value try: raw = base64.b64decode(payload, validate=True) except (binascii.Error, ValueError) as error: raise HTTPException(status_code=400, detail=f"Input is not valid base64: {error}") from error try: return Image.open(io.BytesIO(raw)).convert("RGB") except OSError as error: raise HTTPException(status_code=400, detail=f"Input is not a readable image: {error}") from error def classify(value: str) -> Literal["image", "text"]: return "image" if value.startswith("data:image/") else "text" def pooled(output) -> torch.Tensor: return getattr(output, "pooler_output", output) @torch.inference_mode() def embed_texts(values: list[str]) -> torch.Tensor: # SigLIP was trained on captions canonicalized to lowercase and with the text side padded to # max_length. Capitalized input lands outside that distribution and dynamic padding collapses # the embeddings into a near-constant vector. inputs = processor( text=[value.lower() for value in values], padding="max_length", truncation=True, return_tensors="pt", ) return pooled(model.get_text_features(**inputs)) @torch.inference_mode() def embed_images(values: list[str]) -> torch.Tensor: inputs = processor(images=[decode_image(value) for value in values], return_tensors="pt") return pooled(model.get_image_features(**inputs)) DIMENSIONS = embed_texts(["dimension probe"]).shape[-1] @app.get("/health") def health() -> dict: return { "status": "ok", "model": MODEL_ID, "dimensions": DIMENSIONS, } @app.get("/models") def models() -> dict: return { "object": "list", "data": [{"id": MODEL_ID, "object": "model", "dimensions": DIMENSIONS}], } @app.post("/embeddings") def embeddings(request: EmbeddingRequest) -> dict: if not request.input: raise HTTPException(status_code=400, detail="input must not be empty") grouped: dict[str, list[int]] = {"text": [], "image": []} for index, value in enumerate(request.input): grouped[classify(value)].append(index) vectors: list[list[float]] = [[] for _ in request.input] for kind, indexes in grouped.items(): if not indexes: continue values = [request.input[index] for index in indexes] features = embed_texts(values) if kind == "text" else embed_images(values) features = torch.nn.functional.normalize(features, p=2, dim=-1) for position, index in enumerate(indexes): vectors[index] = features[position].tolist() return { "object": "list", "model": MODEL_ID, "data": [ {"object": "embedding", "index": index, "embedding": vector} for index, vector in enumerate(vectors) ], "usage": {"prompt_tokens": 0, "total_tokens": 0}, } ``` #### `requirements.txt` ``` fastapi==0.141.1 uvicorn[standard]==0.54.0 transformers==5.17.0 pillow==12.3.0 sentencepiece==0.2.2 protobuf==6.33.1 ``` #### `Dockerfile` ```dockerfile FROM python:3.12-slim ENV PYTHONUNBUFFERED=1 \ HF_HOME=/cache/huggingface \ EMBEDDING_MODEL=google/siglip2-base-patch16-256 WORKDIR /srv RUN pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch==2.14.0 COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY app.py . EXPOSE 8080 HEALTHCHECK --interval=15s --timeout=5s --start-period=600s --retries=60 \ CMD python -c "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8080/health',timeout=3)" CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"] ``` ### Reference #### Routes | Route | Returns | |--------------------|-----------------------------------------------------------------| | `GET /health` | the loaded model and the number of dimensions of its vectors | | `GET /models` | the models the service can serve | | `POST /embeddings` | a vector for an image or for a text | The bundle never asks for the vector dimension. It embeds one short text, counts the numbers in the result and writes that length into the index mapping. #### Request and Response Format The `http` provider posts JSON to `{endpoint}/embeddings`. With `api_key` set, it sends `Authorization: Bearer `. A search term is sent as text: ```json { "model": "google/siglip2-base-patch16-256", "input": ["a red bicycle"] } ``` A picture is sent in the same field as a data URI: ```json { "model": "google/siglip2-base-patch16-256", "input": ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA..."] } ``` The response contains the vector: ```json { "data": [ { "embedding": [0.0137, 0.0053, -0.0170] } ] } ``` > [!IMPORTANT] > One model has to answer both requests. A picture and a term embedded by different models land in different > spaces, and the scores stop meaning anything. --- ## Tag Suggestions - [Introduction](#introduction) - [Building the Vocabulary](#building-the-vocabulary) - [Vocabulary Limits](#vocabulary-limits) - [Tag Matching](#tag-matching) - [Setting the Suggestion Threshold](#setting-the-suggestion-threshold) - [Tag Vectors](#tag-vectors) - [Preferring the Most Precise Tag](#preferring-the-most-precise-tag) - [Choosing Tag Names](#choosing-tag-names) - [Vision](#vision) - [Setting a Timeout](#setting-a-timeout) - [Tag Proposals](#tag-proposals) - [Writing Descriptions](#writing-descriptions) - [Customizing Prompts](#customizing-prompts) - [Running the Analysis](#running-the-analysis) - [Watching and Stopping a Run](#watching-and-stopping-a-run) - [Running the Analysis From the Console](#running-the-analysis-from-the-console) - [Reviewing Suggestions](#reviewing-suggestions) - [Accepting Proposals](#accepting-proposals) - [When Suggestions Are Recomputed](#when-suggestions-are-recomputed) - [Custom Analysis Actions](#custom-analysis-actions) - [Custom Vision Providers](#custom-vision-providers) - [Reference](#reference) - [Database Tables](#database-tables) - [Console Commands](#console-commands) ### Introduction Tag suggestions put the right tags on your pictures without anyone tagging them by hand. The bundle offers two engines, and you may use either or both: | Engine | How It Works | Needs | |-------------------------------|------------------------------------------------------------------|--------------------------------------| | [Tag matching](#tag-matching) | compares the vector of a picture with the vectors of your tags | an [embedding service](20_ImageSearch.md#choosing-an-embedding-service) | | [Vision](#vision) | lets a vision model look at the picture and name the tags | a vision model | For example, a DAM with ten thousand product photos may use tag matching to put `Shoes` and `Bags` on every picture at no extra cost, and vision to propose `Sandals` where the tag tree has no word for a picture yet. > [!NOTE] > Neither engine writes to an asset. Both produce suggestions, and a reviewer decides each one in the > [tag review](#reviewing-suggestions). ### Building the Vocabulary The vocabulary is the list of tags the DAM may suggest. Both engines use it: tag matching embeds exactly these tags, and a vision model may name exactly these tags. Without a vocabulary, neither engine runs. You pick the vocabulary from your tag tree under **DAM > Tag vocabulary**, which requires the `opendxp_dam_admin_settings` permission. The panel shows the tags to pick from on the left and the vocabulary on the right. The setting **Allowed tag branches** in the AI settings bounds what may be picked. Both sides read the paths from the tag tree, so a renamed tag appears under its new name without further action. #### Vocabulary Limits The vocabulary travels with every picture that goes to a vision model, and a response schema holds a limited number of values. Two limits therefore bound it, and the panel shows both while you edit: ```yaml opendxp_dam: ai: vocabulary: max_characters: 7000 ``` `max_characters` limits the serialized list, at about 3.5 characters per token, and the panel also counts the entries. A save that would exceed either limit is refused. ### Tag Matching Tag matching compares the vectors that image search writes with the vectors of the vocabulary: ```yaml opendxp_dam: ai: tagging: min_similarity: 1.08 automatic: false ``` With `automatic` turned on, a picture is matched on its own whenever it or a vocabulary tag changes. Otherwise, matching runs when you start it, see [Running the Analysis](#running-the-analysis). > [!IMPORTANT] > Tag matching needs `ai.embedding.provider`. Setting `min_similarity` without it fails the container build. #### Setting the Suggestion Threshold `min_similarity` is the absolute score that a tag has to reach. Without it, nothing is suggested. Scores sit in a narrow band, so a value slightly too low buries the good suggestions under noise. In the test DAM, where almost nothing matched the tag tree, `1.05` gave a video three suggestions and `1.08` left only the genuine hits. > [!TIP] > Start low and read the score that the tag review shows next to each suggestion. Raise the threshold until only the > right suggestions remain. The value is also part of the AI settings. #### Tag Vectors A tag needs a vector of its own before a picture can be compared with it. **Match tags** brings the vectors of the vocabulary up to date before it matches, and so does every change to a vocabulary tag. The window reports how many pictures it has to embed first. After a change of the embedding model, embed the whole vocabulary again: ```bash bin/console opendxp:dam:ai:rebuild-tag-vectors ``` #### Preferring the Most Precise Tag A motorcycle matches `Vehicles` as well as `Vehicles > Motorcycle`, and both are right. Only the more precise tag reaches the review, because a tag is dropped when one of its descendants matched as well. A root of the allowed branches is never a candidate. #### Choosing Tag Names Only the name of a tag is embedded, not its path: - `Car` or `Beach` work well. `Project 2024` or `Approved` describe nothing a picture can show, and still get a score, because a vector search always answers. Keep such tags outside the allowed branches. - Depth costs nothing. `Vehicles > Motorcycle` and `Motorcycle` produce the same vector. - A name with several meanings gets one vector for all of them. `Absatz` below `Schuhe` and below `Vertrieb` is the same word. ### Vision A vision model looks at a picture and names the tags from the vocabulary that fit it. Vision needs no embedding service: ```yaml opendxp_dam: ai: vision: provider: 'symfony_ai' automatic: false tags: true description: false max_proposals: 10 options: platform: 'openai' model: 'gpt-5-mini' language: 'de' max_tags: 3 max_new_tags: 1 ``` `platform` names a platform of `symfony/ai`, which your project configures, and `model` one of its models. The provider requests structured output under `response_format` with a JSON schema and `strict: true`, and each platform translates that into its own API. The tag ids are an enum in that schema, which binds the model to the vocabulary. > [!IMPORTANT] > The model has to support structured output. The bundle was measured against `gpt-5-mini` on the OpenAI platform, > which is why `composer.json` suggests it. | Key | Default | Description | |-----------------|----------|-----------------------------------------------------------------------------| | `automatic` | `false` | Sends a picture to the model on its own whenever it changes. | | `tags` | `true` | Lets the model name tags. Turn it off to use the model for descriptions only. | | `description` | `false` | See [Writing Descriptions](#writing-descriptions). | | `max_proposals` | `10` | See [Tag Proposals](#tag-proposals). | The options of the `symfony_ai` provider: | Option | Default | Description | |----------------------|----------|-----------------------------------------------------------------------| | `platform` | required | The platform in the `ai` configuration. | | `model` | required | The model of that platform. | | `language` | `en` | The language the model writes in. While [multilingual names](30_Multilingual.md#ai-tag-proposals) are enabled, the base language is used instead. | | `max_tags` | `3` | The most tags the model may name per picture. | | `max_new_tags` | `1` | The most new tags it may propose. `0` turns proposals off. | | `prompt`, `tags_prompt`, `new_tags_prompt`, `description_prompt` | shipped wording | See [Customizing Prompts](#customizing-prompts). | | `guidance` | none | Text appended to the instruction. | | `model_options` | none | Passed to the platform as they are. | The model, the language, the limits and the prompts are also part of the AI settings, where they override the configuration. #### Setting a Timeout Give the platform an HTTP client with a timeout: ```yaml # config/packages/ai.yaml framework: http_client: scoped_clients: dam.openai.client: base_uri: 'https://api.openai.com' timeout: 120 max_duration: 180 ai: platform: openai: api_key: '%env(OPEN_AI_API_KEY)%' http_client: 'dam.openai.client' ``` `timeout` is the idle time between two chunks, `max_duration` the length of the whole call. You need both: a model that thinks for ninety seconds would fail on a short `timeout`, and a call that trickles would run forever without `max_duration`. A call normally takes seconds, so these values only catch a hang. > [!WARNING] > Without a timeout, a call that never returns holds a worker forever. The run never finishes and blocks every other > action. #### Tag Proposals A picture may show something the vocabulary has no word for. The model may then propose one new tag, within narrow rules: - **Only when nothing fits.** An answer that names an entry and also proposes a tag has its proposal dropped. - **Beside an existing entry.** A proposal goes below the parent of a vocabulary entry. A model never creates a level of its own. - **As broad as its neighbours.** A vocabulary with `Trees` and without `Spruce` has said how fine it wants to be. - **A single name.** A name containing `>` or `/` is refused, from the model and from the reviewer alike. Open proposals are part of the vocabulary that the model receives, with the negative id of their draft, so the model points at an existing proposal instead of inventing the same word again: ``` 2 | DAM > Autos 24 | DAM > Natur > Bäume -7 | DAM > Technik ``` > [!NOTE] > While a proposal waits for a decision, vision cannot be started and the automatic run pauses. Within a run, once > `max_proposals` proposals are open, the remaining pictures are still tagged but stop proposing. #### Writing Descriptions With `description: true`, the same answer contains one or two sentences about the picture, at no extra call. You choose the metadata field and its language in the AI settings. Without a language, the description goes into the entry that applies to all languages. Turning descriptions on without a field is refused. #### Customizing Prompts There are four prompts, and the first one contains the others: ``` Look at the picture and say what is in it. {tasks} Write every value in {language}. ``` `{tasks}` receives the prompts for tags, for new tags and for the description, each only while it is turned on. The other placeholders are `{language}`, `{max_tags}` and `{max_new_tags}`. In the AI settings, every prompt field starts empty and shows the shipped wording as a hint. A button copies the wording into the field for editing. An empty field keeps the shipped wording and receives later updates of it. > [!WARNING] > A first prompt without `{tasks}` gives the model nothing to do. ### Running the Analysis Nothing is analyzed on the spot. Every asset goes onto the DAM queue, because a vision model takes seconds per picture and costs money per call. You start a run in **DAM > Tag suggestions** with the **Action** button, which requires the `opendxp_dam_ai_analyze` permission: | Action | Result | Cost | |--------------------------|-------------------------------------------------------------|---------------| | **Create image vectors** | writes the vectors of [image search](20_ImageSearch.md) | one call each | | **Match tags** | compares the images with the vocabulary | none | | **Analyze images** | lets the vision model suggest tags and write a description | one call each | Each action opens a window that is not modal, so you may drag a folder from the asset tree into it. The window shows what the action does, which assets it covers, when it last ran and why it cannot run, and asks for confirmation with the number of assets. By default, only pictures that were never analyzed are queued. A picture is treated as analyzed while its bytes are unchanged, so saving its metadata changes nothing. A checkbox in the window includes the others, which a changed vocabulary or prompt calls for. > [!NOTE] > **Create image vectors** is blocked while `embedding.automatic` is on. **Match tags** embeds the pictures that have no > vector yet on its own, and the window reports how many that are. An action cannot start while another run is going or while a proposal waits for a decision. Both reasons are shown at the action and apply to the automatic run as well. #### Watching and Stopping a Run While a run is going, a bar below the review list shows its progress and lets you stop it. Every message of a run contains its id, so a stopped run's remaining messages arrive and do nothing. The bar polls every three seconds while something runs and stays quiet otherwise. #### Running the Analysis From the Console ```bash bin/console opendxp:dam:ai:analyze bin/console opendxp:dam:ai:analyze --path=/campaigns --limit=50 ``` | Option | Description | |-----------|-----------------------------------------------------| | `--path` | Only assets below this folder path. Default `/`. | | `--id` | A single asset. | | `--all` | Also queues assets that were analyzed before. | | `--limit` | Stops after this many assets. | | `--force` | Queues without asking, for a scheduled run. | `opendxp:dam:ai:match-tags` compares the assets that already have a vector with the tag vectors again. Both commands record their run like the tag review does. ### Reviewing Suggestions **DAM > Tag suggestions** requires the `opendxp_dam_tag_review` permission and lists one row per decision, in two groups: **Matched tags** for existing tags, and **New tags** for the proposals of a vision model. Nine assets with ten suggestions each come down to the handful of tags behind them. Selecting a row shows its assets, each marked with its source: **Similarity**, **AI**, or both. A click on a picture excludes that asset from the decision. **Apply** puts a matched tag on the remaining assets. **Discard** deletes the row, and the same suggestion stays away until the picture itself changes. > [!NOTE] > An accepted suggestion keeps its row, so the same tag is never suggested twice for an asset. The bundle adds a tag > to an asset only when asked to and never removes one. #### Accepting Proposals A proposal row shows the vocabulary as a tree, with the proposal at the place where it would go. **Create and assign** creates the tag there, takes it into the vocabulary and assigns it. **Use an existing tag** maps the proposal onto a tag that turns out to be another spelling. A proposal is decided once for the whole installation, however many pictures named it. If a tag of that name already exists at the place, it is used as it is, and the panel shows a hint before you click. A vocabulary that is too full to take the tag keeps the tag and reports the problem. While multilingual names are enabled, **Create and assign** first asks for the translations, see [AI Tag Proposals](30_Multilingual.md#ai-tag-proposals). #### When Suggestions Are Recomputed | Event | Result | |----------------------------------------------|------------------------------------------------------| | The picture of an asset changes | Its open suggestions are recomputed. | | A vocabulary tag is added or renamed | Its vector follows, and so do the pictures it reaches. | | A vocabulary tag is deleted | Its vector and its entry are removed. | | A reviewer accepts | The tag is put on the asset, and the row stays accepted. | | A reviewer discards | The row is deleted. | | Someone puts the tag on the asset directly | The open suggestion for it is deleted. | Saving an asset, rebuilding the index or a full crawl leave the suggestions alone, because the analysis remembers a checksum of the picture it last looked at. ### Custom Analysis Actions An action is a service tagged with `dam.ai.action` that implements `AnalysisActionInterface`. The **Action** menu is built from the registered actions, so you may add your own without touching the bundle: ```php interface AnalysisActionInterface { public function getIdentifier(): string; public function describeTarget(): ?string; public function findBlocker(): ?AnalysisBlocker; public function supportsForce(): bool; public function collect(?Asset $scope, bool $force): array; public function countNotReady(array $assetIds): int; public function run(array $assetIds, int $runId): void; } ``` The identifier is also the translation key `opendxp.dam.ai_action.` and `opendxp.dam.ai_action._help`. > [!IMPORTANT] > Every message that `run()` dispatches must carry the run id. Otherwise the run cannot be counted or stopped. ### Custom Vision Providers A model that `symfony/ai` cannot reach, such as a self-hosted one behind your own HTTP call, needs a provider of its own. It implements `VisionProviderInterface`, whose single method `analyze()` returns a `VisionResult`, and is tagged with `dam.ai.vision_provider`: ```yaml services: App\Dam\MyVisionProvider: tags: - { name: dam.ai.vision_provider, identifier: 'my_vision' } ``` Name the identifier under `ai.vision.provider`. Every provider is held to the same contract, so the vocabulary, the review and the queue work the same behind it. ### Reference #### Database Tables | Table | Contents | |----------------------|----------------------------------------------------------------------------------| | `dam_asset_analysis` | One row per asset, see below. | | `dam_tag_vocabulary` | One row per vocabulary tag, with `embedded_checksum` and `embedded_at` of its vector. | | `dam_analysis_run` | One row per run: the action, its state, the number of assets covered and done, start, end and the user who started it. | The columns of `dam_asset_analysis`: | Column | Contents | |----------------------------------|--------------------------------------------------------------------------| | `embedded_checksum` | the picture that was embedded, so unchanged assets are skipped | | `analyzed_checksum` | the picture that was analyzed, for the same reason | | `embedded_at`, `embedding_error` | when the vector was written, or why it failed | | `analyzed_at`, `vision_error` | when vision last ran, or why it failed | | `matched_at`, `run_requested_at` | when the tags were last matched, and what is still waiting | | `run_id` | the run waiting for this asset, so it learns when the indexer is done | Nothing the model said is kept there. Tags become suggestions, and a description becomes asset metadata. The checksum of a vocabulary entry is built from the name of the tag, so renaming the tag makes the entry stale and the next match embeds it again. An entry whose tag was deleted is dropped. A run is finished when its count is reached, and stopped when someone stops it. #### Console Commands | Command | Description | |--------------------------------------|-------------------------------------------------------| | `opendxp:dam:ai:analyze` | Queues assets for a vision model. | | `opendxp:dam:ai:match-tags` | Compares assets with the tag vectors again. | | `opendxp:dam:ai:rebuild-tag-vectors` | Embeds the whole vocabulary again. | | `opendxp:dam:ai:calibrate` | Measures the [vector lower bound](20_ImageSearch.md#tuning-the-vector-lower-bound). | Embedding has no command of its own. The indexer writes the vector, and **Create image vectors** asks it to. --- ## Multilingual Tags and Folders - [Introduction](#introduction) - [Configuration](#configuration) - [Enabling Multilingual Names](#enabling-multilingual-names) - [Updating the Search Index](#updating-the-search-index) - [Choosing a Translation Provider](#choosing-a-translation-provider) - [Using DeepL](#using-deepl) - [Using Symfony AI](#using-symfony-ai) - [Using Your Own Service](#using-your-own-service) - [Translating Tags and Folders](#translating-tags-and-folders) - [Using the Translations Panel](#using-the-translations-panel) - [Using the Sync Command](#using-the-sync-command) - [Using the Name Dialog](#using-the-name-dialog) - [Name Resolution](#name-resolution) - [Changing the Base Language](#changing-the-base-language) - [Proposals in Other Languages](#proposals-in-other-languages) - [AI Tag Proposals](#ai-tag-proposals) - [OpenID Users](#openid-users) - [Frontend Integration](#frontend-integration) - [Sending the Request Language](#sending-the-request-language) - [Reading the Locale Settings](#reading-the-locale-settings) - [Displaying Breadcrumbs](#displaying-breadcrumbs) - [Custom Translation Providers](#custom-translation-providers) - [Limitations](#limitations) - [Reference](#reference) - [Where Localized Names Appear](#where-localized-names-appear) - [Search Index Fields](#search-index-fields) ### Introduction Multilingual names let every user see tags and folders in their own language. Each tag and folder has one **base name** in the **base language** of the DAM, and a **translation** for every other language of the system. The DAM returns each name in the language of the request. For example, if your DAM serves a company in Switzerland, editors may name a tag `Berge` in German while the frontend shows `Montagnes` to French-speaking users. A photographer from Lausanne may propose a new tag in French during an upload, and the reviewer gives it its German base name. The feature is disabled by default. While it is disabled, every tag and folder has a single name. ### Configuration #### Enabling Multilingual Names Configure a [translation provider](#choosing-a-translation-provider) first. Then open the DAM settings and go to the **Languages** tab: | Setting | Key | Default | |--------------------------------------------|-----------------------------------------|---------| | Manage in multiple languages | `multilingual` | off | | Base language | `baseLocale` | none | | Users may create structure (tags, folders) | `allowStructureCreation` | on | | Also users with another language | `allowStructureCreationForOtherLocales` | off | The languages are the system languages of OpenDXP, and the base language must be one of them while the feature is enabled. The last two settings decide who may propose tags and folders during an upload, see [Restricting Who May Create Tags and Folders](10_Uploads.md#restricting-who-may-create-tags-and-folders). > [!IMPORTANT] > Saving the settings renames nothing, translates nothing and indexes nothing. The existing tags and folders have no > translations yet. Translate them in the [Translations panel](#using-the-translations-panel) or with the > [sync command](#using-the-sync-command). The translations live in the table `dam_translation`, one row per element and language, with the type (`tag` or `folder`), the id of the element, the language and the name. When you disable the feature again, the translations stay in the table. #### Updating the Search Index The index stores the names in every language in the field `names`. The update that brings the field is described in the [changelog](../CHANGELOG.md). Index the DAM once after you enable or disable the feature: ```bash bin/console dynamic-search:run ``` Until then, the search does not find names in other languages. After disabling the feature, the run empties `names`. ### Choosing a Translation Provider Every translation goes through a provider, which you name under `opendxp_dam.translation`. The bundle ships three: | Provider | Description | |--------------|--------------------------------------------------------------------------------| | `deepl` | The DeepL API, one request per target language with all texts. | | `symfony_ai` | One prompt per request through a platform of `symfony/ai`, with all texts and languages. | | `http` | A service of your own. | > [!NOTE] > Without a provider, every translation fails with a message that names `opendxp_dam.translation`. Reviewers and > editors may still fill in the names by hand. #### Using DeepL The provider calls the DeepL REST API directly and needs no further package. Put the key of your DeepL account into the environment and name the provider: ```dotenv DEEPL_API_KEY=your-key ``` ```yaml opendxp_dam: translation: provider: 'deepl' options: api_key: '%env(DEEPL_API_KEY)%' ``` | Option | Default | Description | |--------------------|--------------------------|-----------------------------------------------------------------| | `api_key` | required | The key of the DeepL account. | | `server_url` | derived from the key | `https://api-free.deepl.com` for a free key ending in `:fx`, `https://api.deepl.com` for any other. Set it for a proxy. | | `timeout` | `30` | Seconds per request. | | `target_languages` | `en: EN-GB`, `pt: PT-PT` | The DeepL target language by locale or language. | | `type_contexts` | one sentence per type | The `context` that DeepL receives for `tag` and `folder`. It steers the translation and is not translated itself. | | `request_options` | none | Further request parameters, for example `formality` or `glossary_id`. | When the provider maps a locale to a DeepL target language, it tries in this order: 1. The locale in `target_languages`, for example `de_CH: DE`. 2. The locale as a regional variant that DeepL offers, for example `en_US` as `EN-US`. 3. The language of the locale in `target_languages`, for example `en` as `EN-GB`. 4. The language of the locale, for example `de_CH` as `DE`. The source language is always the language without its region. When DeepL refuses the key (`403`), receives too many requests (`429`) or reports a used-up quota (`456`), the failed translation reports the reason. #### Using Symfony AI ```yaml opendxp_dam: translation: provider: 'symfony_ai' options: platform: 'openai' model: 'gpt-5-mini' ``` | Option | Default | Description | |-----------------|--------------------|--------------------------------------------------------------------| | `platform` | required | The platform in the `ai` configuration. | | `model` | required | The model of that platform. | | `prompt` | shipped wording | The instruction, with the placeholders `{source}`, `{targets}` and `{type}`. | | `type_prompts` | one text per type | The text for `{type}`, by type `tag` and `folder`. | | `model_options` | none | Passed to the platform as they are, for example a token limit. | > [!IMPORTANT] > The model has to support structured output. The answer is bound to a schema with one entry per text and one field > per language. #### Using Your Own Service ```yaml opendxp_dam: translation: provider: 'http' options: endpoint: 'http://translation:8080' api_key: '%env(TRANSLATION_API_KEY)%' timeout: 60 ``` The `http` provider posts to `{endpoint}/translate`. The key is sent as a bearer token when it is set, and `timeout` defaults to `60` seconds: ``` POST /translate { "source": "de", "targets": ["en", "fr"], "type": "folder", "texts": ["Berge"] } 200 { "translations": [ { "en": "Mountains", "fr": "Montagnes" } ] } ``` `type` is `tag` or `folder`. The response has one entry per text, in the order of the request, with one text per target language. A name may have up to 255 characters. Any other response is treated as an error. ### Translating Tags and Folders The bundle never translates on its own. After you enable the feature, translate the existing names in the panel or with the command. New tags and folders are named and translated in the name dialog. #### Using the Translations Panel **DAM > Translations** requires the `opendxp_dam_admin_settings` permission. It has a tab for tags and a tab for folders, which lists the folders and collections below the root folder of the DAM. While the feature is disabled, the panel shows a message instead of the grids. Each row shows the path and the base name, which cannot be edited here. Every other language has an editable column: | Control | Result | |------------------------|---------------------------------------------------------------------------------| | Search | Filters by the base name, and for folders by the key as well. | | **Incomplete only** | Shows only rows that lack a translation. | | **Translate selection** | Translates the empty cells of the checked rows from the base name, after a confirmation with the number of cells. Filled cells stay as they are. | | **Save** | Writes the changed rows. An empty cell deletes its translation. | > [!NOTE] > **Translate selection** saves nothing. Its result stays in the grid until you click **Save**, and the panel asks > before it discards unsaved changes. Rows that lack the same languages share one request to the provider. #### Using the Sync Command ```bash bin/console opendxp:dam:translations:sync [--previous-base-locale=] ``` The command works through every tag and folder: 1. With `--previous-base-locale`, it renames every tag and folder into the base language first, see [Changing the Base Language](#changing-the-base-language). 2. It translates the missing names, and asks the provider only for the missing languages. Existing translations stay. 3. It deletes the translations of tags and folders that no longer exist, and of languages the system no longer supports. 4. It prints how many tags and folders it renamed and translated, how many failed, and how many translations it deleted. The exit code is `1` when something failed, and the command may be repeated. It refuses to run while the feature is disabled, and when `--previous-base-locale` is not a supported language other than the base language. #### Using the Name Dialog The [upload review](10_Uploads.md#translating-new-tags-and-folders) and the [tag review](#ai-tag-proposals) open the same dialog whenever you name a new tag or folder. It has a field for the base name and, while the feature is enabled, a field for every other language: | Button | Result | |----------------------------|------------------------------------------------------------------------------------------------| | **Translate empty fields** | Asks the translation provider to fill every empty field. It translates the base name, or the first filled field while the base name is empty. Filled fields are kept. | | **Apply** | Takes over the names. It requires a base name. | A reviewer with `opendxp_dam_upload_review` or `opendxp_dam_tag_review` may use **Translate empty fields** without the settings permission. ### Name Resolution When the DAM resolves the name of a tag or folder, it uses the language of the header `X-OpenDxp-Api-Locale`: 1. In the base language, the name is the base name. 2. In another language, the name is the translation. 3. Without a translation, the name is the base name. A name is never empty. Without a request, as in a console command, the name is the base name. The base name of a tag is its name. The base name of a folder, and of a collection, is its property `dam_folder_name`, or its key while the property is empty. Renaming or moving a tag or folder keeps its translations. Deleting it deletes them, including those of every tag and folder below it. ### Changing the Base Language You may change the base language in the settings. Saving renames nothing, so the existing names keep their text and are treated as names in the new base language. To rename them, run the command with the old base language: ```bash bin/console opendxp:dam:translations:sync --previous-base-locale=de ``` For every tag and folder, the command: 1. turns the old base name into the translation of the old language, 2. renames the element to its name in the new base language, using an existing translation or asking the provider, 3. deletes the translation in the new base language, because it is now the base name. A folder keeps its key, and only `dam_folder_name` changes. > [!TIP] > A tag or folder that already has a translation in the old language is treated as renamed and skipped, so you may > repeat the command after a failure. An element whose translation failed keeps its old name, and the command > reports the failure. ### Proposals in Other Languages A user of the frontend proposes new tags and folders in their own language, which is the language of the user who created the upload job. The reviewer gives each proposal its base name and its translations in the name dialog of the [name dialog](#using-the-name-dialog) of the [upload review](10_Uploads.md#reviewing-uploads). A proposal typed in another language is shown in the field of that language, with an empty base name. On approval, the bundle creates each new tag and folder with its translations. An existing tag or folder at the same place only receives the translations it lacks. > [!NOTE] > The bundle does not detect the language of a typed name. A user who types in another language than their own is > not noticed, but the reviewer sees the typed text. ### AI Tag Proposals While the feature is enabled, the [vision model](25_TagSuggestions.md#vision) writes in the base language, and the **Answer language** of the AI settings is hidden. **Create and assign** in the tag review first opens the [name dialog](#using-the-name-dialog) as **Create tag**, with the name of the proposal as the base name. A tag with the same name at the same place is used instead and only receives the translations it lacks. **Use an existing tag** asks for no translations. ### OpenID Users A new user receives a language when the user is created: ```yaml opendxp_dam: security: openid: locale_claim: 'locale' fallback_locale: ~ ``` | Feature | Language of the New User | |----------|----------------------------------------------------------------------------------| | disabled | `fallback_locale`, or the default language of the system while it is not set | | enabled | the language of the claim if the system supports it, otherwise the base language | The claim is a BCP 47 tag, so `de-CH` becomes `de_CH`. When the system does not support it, the language part `de` is used. A later login does not change the language. ### Frontend Integration #### Sending the Request Language Read the language of the user from the field `locale` of `GET /account`, use it for the interface, and send it with every request: ``` X-OpenDxp-Api-Locale: fr ``` Tag names, folder names and the names of the items of the media list are returned in that language. A language switch saves the new language with `PATCH /account`. #### Reading the Locale Settings `GET /dam/settings` contains the block `locale`: ```json "locale": { "multilingual": true, "base": "de", "supported": ["de", "en", "fr"] } ``` While the feature is disabled, `multilingual` is `false`, `base` is `null` and `supported` is empty. Hide the input of new tags and folders while the field `structureCreationAllowed` of the upload job is `false`, see [Restricting Who May Create Tags and Folders](10_Uploads.md#restricting-who-may-create-tags-and-folders). #### Displaying Breadcrumbs The detail of an asset has the field `breadcrumb`. It lists the folders from below the root of the DAM down to the folder of the asset, each with its `id` and its `name` in the language of the request. `path` stays the technical path of the asset tree: ```json "path": "/dam/architecture-cities/details-patterns/", "breadcrumb": [ { "id": 41, "name": "Architecture & Cities" }, { "id": 57, "name": "Details & Patterns" } ] ``` ### Custom Translation Providers A provider for another service, such as Google, implements `TranslationProviderInterface` and is tagged with `dam.translation_provider`. The `identifier` of the tag is the name you configure under `translation.provider`: ```php interface TranslationProviderInterface extends AiProviderInterface { public function translate(TranslationRequest $request): TranslationResult; } ``` The request contains `texts`, the `sourceLocale`, the `targetLocales` and a `type`, which is `tag` or `folder`. The result contains one map of locale to text for each text, in the order of the request. `TranslationResult::fromAnswer($request, $entries)` builds the result from such a list and checks that every text and every target language is answered. A provider that cannot answer throws an `AiProviderException`. The provider receives its own instance with the `options` of `opendxp_dam.translation`, and `configureOptions()` declares which keys it reads. ### Limitations The bundle checks that the source language of a translation is known, but not that the translation is right. In addition, the bundle does not: - fall back from one language to another, apart from the base name, - translate tags and folders that an administrator creates in the backend. Use the panel or the command, - add the names of tags to the full-text search. Tags stay a filter, - translate asset metadata other than the title, emails or the frontend. ### Reference #### Where Localized Names Appear - the tag search, - the tags and the name of each item of the media list, - the tag filter of the media list, - the tags of an asset, the folder names and the breadcrumb in the detail, - the collections, - the folder tree of the upload, - the assigned tags of an upload job. #### Search Index Fields | Field | Contents | |---------|---------------------------------------------------------------------------------------| | `name` | the name in the base language, or the title without a language while the feature is disabled | | `names` | one entry per language with `locale` and `text`, empty while the feature is disabled | The name of an asset in a language is its metadata `title` in that language. Without it, the title without a language is used, then the file name. The search finds an item by its name in every language, and the list shows the name in the language of the request. A change to the translations of a folder indexes that folder again. Tags are a filter in the index and receive their names when the list is read. --- ## Changelog(Dam-bundle) ### 1.1.2 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.1 - [BUGFIX] The upload job returns the `parentId` of a new tag instead of leaving it out ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [CHORE] Require `open-dxp/headless-bundle` ^1.4 - [CHORE] Require `symfony/ai-platform` ^0.15 - [NEW FEATURE] [HIGHLIGHT] [OPT-IN] [MIGRATION] User uploads, see [Uploads](docs/10_Uploads.md) > Users upload files to the DAM themselves. Uploads are opt-in. 1. Add a `permission_upload` column (type `bool`) to the `assetWorkspaceDefinition` field of the `User` class and the group class. - [NEW FEATURE] [HIGHLIGHT] [MIGRATION] Image search and tag suggestions, see [Image Search](docs/20_ImageSearch.md) and [Tag Suggestions](docs/25_TagSuggestions.md) > The DAM adds image search and tag suggestions. - [NEW FEATURE] [HIGHLIGHT] [FOLLOW-UP] [MIGRATION] Multilingual tags and folders, see [Multilingual Tags and Folders](docs/30_Multilingual.md) > Tags and folders are multilingual. 1. Run `bin/console dynamic-search:os:migrate start -c opendxp_dam_media`. 2. Run `bin/console dynamic-search:run -c opendxp_dam_media`. 3. Run `bin/console dynamic-search:os:migrate switch -c opendxp_dam_media`. - [NEW FEATURE] `DamUserTrait` makes a user of the Headless Ecommerce Bundle a DAM user, see [Preparing the User Class](docs/00_Installation.md#preparing-the-user-class) - [BUGFIX] The media list and the detail of an asset use `dam_list` and `dam_detail` until other thumbnails are chosen in the settings - [BUGFIX] The download of an expired share returns 410, also for a download that was requested before the share expired - [BUGFIX] `GET /dam/bookmarks` returns only the assets the user may view - [BUGFIX] The status of a worker job that is not a share download requires a DAM user - [BUGFIX] The API documentation types `permissions` as a list of permissions. It typed the whole list as one permission before - [BUGFIX] The API documentation describes a bookmark that exists already as an error. It described a UUID before - [ENHANCEMENT] The API documentation lists 410 for the download of an expired share and 403 for the status of a worker job - [CHORE] [FOLLOW-UP] The property `dam_collection_name` has been removed. Collections use `dam_folder_name` 1. Only if your project sets the property `dam_collection_name` on a folder: set `dam_folder_name` instead. - [ENHANCEMENT] `DamUserInterface` declares `getLocale(): ?string`, which `ApiUserInterface` of the headless bundle has always required - [ENHANCEMENT] [OPT-IN] A new OpenID user gets `opendxp_dam.security.openid.fallback_locale` instead of `de` 1. Only if new OpenID users should keep the locale `de`: set `opendxp_dam.security.openid.fallback_locale` to `de`. ### 1.0.1 - [BUGFIX] Handle a missing `id` in the configuration of `loginBackgroundImage` ### 1.0.0 - [NEW FEATURE] Initial Release --- ## DAM Bundle The DAM bundle turns the OpenDXP asset tree into a digital asset management system for a headless frontend. Users search, download and upload assets, find pictures by what they show, receive tag suggestions, and see tags and folders in their own language. ### Documentation - [Installation](docs/00_Installation.md) - [Uploads](docs/10_Uploads.md) - [Image Search](docs/20_ImageSearch.md) - [SigLIP on Your Own Server](docs/20_ImageSearch.md#using-siglip-on-your-own-server) - [Running the SigLIP Service](docs/20_ImageSearch_SiglipService.md) - [Jina AI](docs/20_ImageSearch.md#using-jina-ai) - [Managed API](docs/20_ImageSearch.md#using-a-managed-api) - [Tag Suggestions](docs/25_TagSuggestions.md) - [Multilingual Tags and Folders](docs/30_Multilingual.md) ### Upgrade Info Before updating, please [check the changelog](CHANGELOG.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Genius(Deepl-translator) The bundle registers DeepL as a translator for Content Crafter. A plan can then translate text through DeepL instead of a language model. The integration loads only when the Content Crafter bundle is installed. - [Choose DeepL](#choose-deepl) - [Name DeepL in a plan](#name-deepl-in-a-plan) - [Refused plans](#refused-plans) - [Tests](#tests) ### Choose DeepL Open **Content Crafter > Crafter-Settings > Engines**. In the box *Translation*, set the translator to *DeepL*. Without this setting, Content Crafter translates with a language model. DeepL uses the same configuration as the rest of the bundle: the API key, the translation options, the glossary and the target languages. The rules for the target languages are described in [Target languages](../README.md#target-languages). ### Name DeepL in a plan A plan can choose the translator for a single value with `with`: ```json {"values": {"shortDescription": {"$translate": {"sourceLocale": "de", "with": "deepl"}}}} ``` Content Crafter accepts `with` only when more than one translator is installed. Without `with`, the setting decides. ### Refused plans Content Crafter checks the plan before the job starts. It refuses a plan with DeepL in these cases: | Message | Cause | |------------------------------------------------------------------|------------------------------------------------| | `DeepL has no API key. Set "opendxp_deepl_translator.api_key" …` | The configuration has no API key. | | `… which "deepl" does not translate.` | DeepL does not offer one of the two languages. | ### Tests The tests in `tests/Feature/ContentCrafter` run plans through the test API of Content Crafter. They never call DeepL. The test application replaces the DeepL client with `MockTranslator`. It answers with the text and the two languages. The helper `deeplTranslates()` puts the DeepL languages into the cache, so `LanguageService` calls no API either. The test API is described in [Tests](https://docs.opendxp.io/docs/bundles/content-crafter/Tests). --- ## Changelog(Deepl-translator) ### 1.3.1 - [DEPRECATION] Tags `dachcom.translator.data_extractor` and `dachcom.translator.data_writer` are deprecated and 2.0 removes them. Use `deepl_translator.data_extractor` and `deepl_translator.data_writer`. ### 1.3.0 - [CHORE] Require Content Crafter 2.1 for the Genius support - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [BUGFIX] DeepL translates into regional locales such as `de_CH` and `pt_BR`. See [Target languages](README.md#target-languages) [#5](https://github.com/open-dxp/deepl-translator-bundle/issues/5) - [BUGFIX] The backend shows a message instead of an error for an unsupported target language - [ENHANCEMENT] The translation of a document includes the inherited texts of its content main document [#9](https://github.com/open-dxp/deepl-translator-bundle/issues/9) - [BUGFIX] The context menu of a tree shows DeepL when the root is selected - [BUGFIX] The DeepL main menu works without the `SimpleBackendSearchBundle` ### 1.2.0 - [NEW FEATURE] Genius support: a Content Crafter plan can translate through DeepL instead of a language model [Read more](./docs/30_Genius.md) - [ENHANCEMENT] The languages DeepL knows are asked once instead of once per element ### 1.1.2 - [BUGFIX] [MIGRATION] Fix `deepl_autotranslate_disable` property stored with an invalid type (`checkbox` → `bool`) [#11](https://github.com/open-dxp/deepl-translator-bundle/pull/11) ### 1.1.1 - [NEW FEATURE] Support for translatable fields selection in Data Objects, including localized fields in FieldCollections and Block-Elements. - [ENHANCEMENT] PHP 8.5 support ### 1.1.0 - [NEW FEATURE] Document: opendxp_link translations (text, path (document), title) - [NEW FEATURE] Document: document links in supported editables ### 1.0.2 - [BUGFIX] Fix wrong property type [#3](https://github.com/open-dxp/deepl-translator-bundle/issues/3) ### 1.0.1 - [ENHANCEMENT] Update composer dependency to support Doctrine ORM 2.15 ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update workflows [#1](https://github.com/open-dxp/deepl-translator-bundle/pull/1) --- ## Migrating to OpenDXP(Deepl-translator) ### Version 1.0.0 / Migrating from `dachcom/pimcore-deepl-translator` * Moved Bundle to new namespace: `OpenDxp\Bundle\DeeplTranslatorBundle` * Renamed Bundle to `OpenDxpDeeplTranslatorBundle` * Change top-level config node to `opendxp_deepl_translator` --- ## Deepl Translator Bundle ### Installation - Execute: `$ composer require open-dxp/deepl-translator-bundle` - Add the following to your `bundles.php`: ```php \OpenDxp\Bundle\DeeplTranslatorBundle\OpenDxpDeeplTranslatorBundle::class => ['all' => true], ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpDeeplTranslatorBundle` #### Queue Worker for shared & admin interface translations ``` $ bin/console messenger:consume deepl_translate ``` ### Configuration Create the following configuration: ```yaml opendxp_deepl_translator: api_key: 'YOURKEYHERE' options: # DeepL Options: One of \DeepL\TranslatorOptions # @see https://github.com/DeepLcom/deepl-php#configuration connect_timeout: 5.2 translation_options: # Translation Options: One of \DeepL\TranslateTextOptions # @see https://github.com/DeepLcom/deepl-php#text-translation-options # Optional: Override the target languages, see "Target languages" # language_locale_mapping: # en: 'en-GB' # pt: 'pt-BR' autotranslate: enable: true sourceLanguage: 'de' targetLanguage: 'en' classes: - 'NewsEntry' - 'Employee' # Optional: ignore Mandatory fields while persisting data # ignore_mandatory_check: true # # Optional: Enable field selection for the translations in data objects. This is false by default. # dataobjects_enable_field_selection: true # # Optional: Define fields to ignore while translating # element_definitions: # - class: 'DataObject.NewsEntry' # enable_field_selection: false # Enable/Disable field selection for this class only # ignore_fields: # - title # - description # - class: 'FieldCollection.MyFieldCollectionName' # ignore_fields: # - myfield1 # - myfield2 ``` Important: An admin account still can do everything regardless of permissions. ### Usage This bundle adds a button to data object and document editors. Click them and see the magic happen. Translating documents will translate all input, textarea and wysiwyg editables with their key and navigation name. A document with a content main document also gets its inherited texts translated. The translated texts become editables of the document. All other editables stay inherited. While translating data objects the same input types will be translated, but only if they're in localized fields. ### Features * Translate: * Documents * Page * key * navigation_name * Supported editables: * input * textarea * wysiwyg * link * Email * subject * Objects * Supported data types: * localizedFields: * input * textarea * wysiwyg * fieldcollection * block * Ignore fields by passing `ignore_fields` in the `element_definitions` option. * Set `enable_field_selection` to true to allow the user to select which fields to translate. All allowed data types in FieldCollections or Block elements are also listed for selection. This feature is disabled by default. * Assets * Meta data (context menu) * Translate all shared translations * Glossary ### Field selection If you want to select which fields to translate of a dataobject, you can set `enable_field_selection` to true in the `element_definitions` option (example above). If you want to select fields on all data objects, you can set `dataobjects_enable_field_selection: true`. ### Target languages DeepL names its target languages differently from OpenDXP. The bundle finds the DeepL language for a locale with these rules. The first rule that applies decides. 1. The entry of the locale in `language_locale_mapping`. 2. The locale itself, if DeepL offers it as a regional variant. `pt_BR` becomes `PT-BR`. 3. The entry of the base language in `language_locale_mapping`. `en_CH` becomes `en-US`. 4. The base language. `de_CH` becomes `DE`. DeepL accepts English and Portuguese only with a region. The bundle therefore maps `en` to `en-US` and `pt` to `pt-PT`. A project overrides these entries in its configuration: ```yaml opendxp_deepl_translator: language_locale_mapping: en: 'en-GB' pt: 'pt-BR' ``` A translation into a locale without a DeepL target language fails with the message `Target language "…" is not supported`. ### Auto translate The auto translate feature can be disabled globally by setting `autotranslate.enable` to false. On save if a DataObject is in the class list defined in `autotranslate.classes`, it will be automatically translated from `autotranslate.sourceLanguage` to `autotranslate.targetLanguage`. Make sure the languages are properly configured in opendxp and are supported by DeepL to avoid exceptions. The class list can consist of a simple class name (like `Product`), then the standard OpenDXP namespace for DataObjects will be added during the check. You can also configure a FQCN, then it will be checked literally. To disable automatic translation on a specific DataObject, create the Property `deepl_autotranslate_disable` as a checkbox and check it. ### Glossaries Glossaries are disabled by default. To enable glossaries, the value must be set to true. ```yaml opendxp_deepl_translator: glossary: true ``` Glossaries can be managed in Deepl Admin Panel (https://www.deepl.com/de/glossary). There may exist multiple glossaries for a sourceLanguage-targetLanguage combination, but only one can be active. Only active glossaries are used for the translation process. If a glossary is activated all other glossaries for the same sourceLanguage-targetLanguage combination are deactivated automatically. ### Extending To support more specific Data Objects or Documents, the bundle can be easily extended: #### Create a data extractor Create a class which implements `OpenDxp\Bundle\DeeplTranslatorBundle\DataExtractor\DataExtractorInterface` ```php class MyDataExtractor implements DataExtractorInterface { public const KEY = 'myKey'; public function extract(?ModelInterface $element, array $options = []): array { // ... } public function supports(?ModelInterface $element): bool { // ... } public function getKey(): string { return static::KEY; } } ``` The `supports` method needs to check if the Extractor supports the current object (for example an `instanceof` check) The result of `extract` needs to be formatted in a specific way for the translator to be able to handle it. Example: ```php $result['name'][] = $object->getName(); ``` This is because documents can have multiple editables of the same type. #### Create a data writer Create a class which implements `OpenDxp\Bundle\DeeplTranslatorBundle\DataWriter\DataWriterInterface` ```php class MyDataWriter implements DataWriterInterface { public function supports(?ModelInterface $element): bool { // ... } public function requires(string $key): bool { return $key === MyDataExtractor::KEY; } public function write(?ModelInterface $element, array $translations, string $targetLanguage): void { // ... } } ``` - The `supports` method needs to check if the Extractor supports the current object (for example an `instanceof` check) - The `requires` method needs to check for the extractor key so the writer knows which translations it handles. #### Tying it together In your `services.yaml` create new services out of the writer and extractor and tag them accordingly: ```yaml services: MyDataExtractor: tags: [ 'deepl_translator.data_extractor' ] MyDataWriter: tags: [ 'deepl_translator.data_writer' ] ``` They then will be automatically included in the chain. *** ### Genius A Content Crafter plan can translate through DeepL instead of a language model. See [Genius](docs/30_Genius.md). *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). *** ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Deepl-translator-seo-extension) ### 1.1.1 - [CHORE] Require DeepL Translator 1.3.1 ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [ENHANCEMENT] Add php 8.5 support [#2](https://github.com/open-dxp/deepl-translator-seo-extension-bundle/pull/2) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update Workflows [#1](https://github.com/open-dxp/deepl-translator-seo-extension-bundle/pull/1) --- ## Migrating to OpenDXP(Deepl-translator-seo-extension) ### Migrating from `dachcom/pimcore-deepl-translator-seo-extension` to `open-dxp/deepl-translator-seo-extension-bundle` 1. Replace `dachcom/pimcore-deepl-translator-seo-extension` with `open-dxp/deepl-translator-seo-extension-bundle` in your `composer.json`. 2. Replace the namespace of the old bundle with `OpenDxp\Bundle\DeeplTranslatorSeoExtensionBundle\`. 3. Register `OpenDxp\Bundle\DeeplTranslatorSeoExtensionBundle\OpenDxpDeeplTranslatorSeoExtensionBundle` in `config/bundles.php` instead of the old bundle. --- ## Deepl Translator SEO Extension Adds extractors and writers to automatically translate seo texts ### Installation - Execute: `$ composer require open-dxp/deepl-translator-seo-extension-bundle` - Do the installation steps of the DeepL Translator Bundle if not already done - Add the following to your `bundles.php`: ```php \OpenDxp\Bundle\DeeplTranslatorSeoExtensionBundle\OpenDxpDeeplTranslatorSeoExtensionBundle::class => ['all' => true], ``` For more refer to https://github.com/open-dxp/deepl-translator-bundle and https://github.com/open-dxp/advanced-seo-bundle *** ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## 01_DispatchWorkflow ### Dispatch Workflow Initially, you need to create and fill your index by executing the run command: > Use the `-v flag to output some log information` ```bash $ bin/console dynamic-search:run -v ``` The run creates the index of each context first if its index provider is pre-configured, such as OpenSearch. The index exists afterwards, even if no document gets indexed. To run only some contexts, name each one with `-c`: ```bash $ bin/console dynamic-search:run -v -c shop -c blog ``` > There could be more to consider, depending on your data- and/or index provider. #### Listener If you want to update your index after modifying opendxp elements, you need to enable it first: ```yaml opendxp_dynamic_search: enable_opendxp_element_listener: true ``` This will listen to: - objects (`all`) - documents (`page`) - assets (`all`) If you want to add more document types to the listener: ```yaml opendxp_dynamic_search: enable_opendxp_element_listener: true element_listener_options: allowed_document_types: - page - hardlink ``` A new object or document reaches the index only when it is saved with `INDEX_ON_ADD`. The admin creates an empty object first, so the listener waits for its next save by default. ```php use OpenDxp\Bundle\DynamicSearchBundle\EventListener\OpenDxpElementListener; $product->save([OpenDxpElementListener::INDEX_ON_ADD => true]); ``` ##### Element Watcher At every modification/deletion event of every opendxp element, DynamicSearch will validate this element by calling [ResourceValidator](./40_ResourceValidator.md). If the resource is still present, DynamicSearch creates an `Envelope` which will be passed to a dedicated queue. ##### Queue Worker The queue is based on [symfony messenger](https://symfony.com/doc/current/messenger.html). Resources which are dispatched to the index are put into the queue and will be processed by the worker asynchronously. The queue is processed in batches. If available and resource validation passes, the transformed resource will be submitted to the index provider. To start the queue worker, execute ```bash $ bin/console messenger:consume dynamic_search_queue ``` > It is highly recommended to set up the worker to be always running with supervisor or systemd. > More details about how to set up the queue worker are found [here](https://symfony.com/doc/current/messenger.html#consuming-messages-running-the-worker). ##### Inheritance Inheritance is unknown to DynamicSearch. If you're updating an object, that very object will be transmitted to the queue. But in some cases, you're working with variants and those should get updated too. Lets' enable it: ```yaml opendxp_dynamic_search: element_inheritance: enabled: true ``` ##### Inheritance Dispatch Origin By default, a real user must be involved to dispatch the inheritance check. Which means, only if the updated comes from the opendxp backend, the child elements will be added to the queue. We're doing this to avoid confusion. If you're updating elements via api, you're most likely handling child elements there, so we don't need to add an extra round. However, you could disable it to allow queued inherited elements at every state: ```yaml opendxp_dynamic_search: element_inheritance: origin_dispatch: 'all' ``` --- ## Example Multi-Site / Multi-Locale Setup This setup is an example how you can filter content in a multi-site/-locale OpenDXP instance. It is using the Trinity data provider and the OpenSearch index provider to fetch and store data. ### Installation Add the following dependencies to your `composer.json` ```json "require": { "open-dxp/dynamic-search-bundle": "^1.1", "open-dxp/dynamic-search-data-provider-trinity-bundle": "^1.1", "open-dxp/dynamic-search-index-provider-opensearch-bundle": "^1.3" } ``` Install them with `composer update`. Then enable the bundles in your `config/bundles.php`: ``` php ['all' => true], \OpenDxp\Bundle\DsTrinityDataBundle\OpenDxpDsTrinityDataBundle::class => ['all' => true], \OpenDxp\Bundle\DsOpenSearchBundle\OpenDxpDsOpenSearchBundle::class => ['all' => true], ]; ``` And finalize the installation via command line ```bash bin/console opendxp:bundle:install OpenDxpDynamicSearchBundle ``` ### Symfony Configuration Create a YAML file in your configuration directory. ``` yaml # config/packages/dynamic-search.yaml opendxp_dynamic_search: # enable the opendxp element listener enable_opendxp_element_listener: true context: # set a context with name "default" default: # set data provider data_provider: service: trinity_data options: always: index_object: true object_class_names: - Car index_document: true index_asset: true normalizer: service: 'trinity_localized_resource_normalizer' # set index provider index_provider: service: 'opensearch' options: index: identifier: 'my_project_prefix' hosts: - 'opensearch:9200' settings: [] credentials: [] analysis: analyzer: keyword_analyzer: tokenizer: keyword type: custom filter: - lowercase - asciifolding - trim char_filter: [] edge_ngram_analyzer: tokenizer: edge_ngram_tokenizer filter: - lowercase edge_ngram_search_analyzer: tokenizer: lowercase tokenizer: edge_ngram_tokenizer: type: edge_ngram min_gram: 2 max_gram: 5 token_chars: - letter # build output channels output_channels: search: service: 'opensearch_search' use_frontend_controller: true options: result_limit: 10 normalizer: service: 'os_document_source_normalizer' paginator: enabled: true max_per_page: 10 ``` Make sure to import the config into your main config. To do so update the imports block at the top. ```yaml # config/config.yaml imports: - { resource: 'packages/*.yaml' } ``` With that the default configuration is finished. Now let's get to the interesting part: Make it work in a multi-site/-locale environment. ### Definitions First, we need the data definition files for all resources (OpenDXP document, assets and objects) we want to index. Here we have to make sure of one thing. All definitions have to return the exact same field definitions. In our example the following fields are used: - `type` (type of OpenDXP element, one of "document", "asset", "object") - `data_type` ("page" for documents, "document" for assets, "object_class_name" for objects) - `title` (main title of the resource) - `bodytext` (main content/text of the resource) - `uri` (link to where the resource is available to look at) - `locale` (language in which the resource is available) - `siteId` (ID of the site in which the resource is available)
Document Definition ```yaml App\DynamicSearch\Definition\Trinity\DocumentDefinition: tags: - { name: dynamic_search.document_definition_builder } ``` ```php getResourceCollectionType() === 'document' && $resourceMeta->getResourceType() === 'page'; } public function isApplicableForContext(string $contextName): bool { return true; } public function preConfigureIndex(IndexDocument $indexDocument): void { } public function buildDefinition(DocumentDefinitionInterface $definition, array $normalizerOptions): DocumentDefinitionInterface { return $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'type', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => 'document', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'data_type', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => 'page', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'title', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'document_meta_extractor', 'configuration' => [ 'type' => 'title', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'bodytext', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'document_meta_extractor', 'configuration' => [ 'type' => 'description', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'uri', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'document_path_generator', ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'locale', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'element_property_extractor', 'configuration' => [ 'property' => 'language', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'siteId', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'document_site_extractor', ], ]); } } ```
Asset Definition ```yaml App\DynamicSearch\Definition\Trinity\AssetDefinition: tags: - { name: dynamic_search.document_definition_builder } ``` ```php getResourceCollectionType() === 'asset' && $resourceMeta->getResourceType() === 'document'; } public function isApplicableForContext(string $contextName): bool { return true; } public function preConfigureIndex(IndexDocument $indexDocument): void { } public function buildDefinition(DocumentDefinitionInterface $definition, array $normalizerOptions): DocumentDefinitionInterface { return $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'type', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => 'asset', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'data_type', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => 'document', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'title', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'asset_meta_extractor', 'configuration' => [ 'name' => 'title', 'locale' => $normalizerOptions['locale'], ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'bodytext', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'asset_pdf_extractor', ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'uri', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'asset_path_generator', ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'locale', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'element_property_extractor', 'configuration' => [ 'property' => 'language', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'siteId', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'element_property_extractor', 'configuration' => [ 'property' => 'site_id', ], ], ]); } } ```
Object Definition ```yaml App\DynamicSearch\Definition\Trinity\CarDefinition: tags: - { name: dynamic_search.document_definition_builder } ``` ```php getResourceCollectionType() === 'object' && $resourceMeta->getResourceSubType() === 'Car'; } public function isApplicableForContext(string $contextName): bool { return true; } public function preConfigureIndex(IndexDocument $indexDocument): void { } public function buildDefinition(DocumentDefinitionInterface $definition, array $normalizerOptions): DocumentDefinitionInterface { return $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'type', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => 'object', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'data_type', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => 'car', ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'title', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'object_getter_extractor', 'configuration' => [ 'method' => 'getName', 'arguments' => [$normalizerOptions['locale']], ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'bodytext', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'object_getter_extractor', 'configuration' => [ 'method' => 'getDescription', 'arguments' => [$normalizerOptions['locale']], ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'uri', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'object_path_generator', 'configuration' => [ 'arguments' => [ '_locale' => $normalizerOptions['locale'], ], ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'locale', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => [ 'value' => $normalizerOptions['locale'], ], ], ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'siteId', 'index_transformer' => [ 'type' => 'dynamic', ], 'data_transformer' => [ 'type' => 'object_site_extractor', ], ]); } } ```
As you might have noticed, we are using two custom data transformers: `document_site_extractor` and `object_site_extractor`. Let's see how they could look like ... ### Data Transformers Extracting site ID's from a OpenDXP document is really easy. We can use the `OpenDxp\Tool\Frontend::getSiteForDocument($document)` helper method to do so.
Document Site Extractor ```yaml App\DynamicSearch\Transformer\Field\DocumentSiteExtractor: tags: - { name: dynamic_search.resource.field_transformer, identifier: document_site_extractor, resource_scaffolder: trinity_data_scaffolder } ``` ```php getResource(); if (! $document instanceof Page) { return null; } $site = Tool\Frontend::getSiteForDocument($document); if (! $site instanceof Site) { return 0; } return $site->getId(); } } ```
In order to extract site ID's from an object, we have to implement a custom strategy. In this case we are using a multiselect field, which has an option provider to make the site IDs available to the editor in the object.
Object Site Extractor ```yaml App\DynamicSearch\Transformer\Field\ObjectSiteExtractor: tags: - { name: dynamic_search.resource.field_transformer, identifier: object_site_extractor, resource_scaffolder: trinity_data_scaffolder } ``` ```php getResource(); if (! $object instanceof Concrete || !\method_exists($object, 'getSites')) { return null; } $sites = $object->getSites(); // If no sites are selected, object is available for all sites. if (empty($sites)) { $options = Service::getOptionsForMultiSelectField($object, 'sites'); return \array_keys($options); } return $sites; } } ```
Awesome! Now we are ready to index our data. ### Indexing data To index your data, execute the following in the command line. ``` bash bin/console dynamic-search:run ``` ### Querying the data Now there's one thing left to do; outputting the data! Remember, we indexed all of our data for all locales and sites. Now we need to make sure to only display the data that fits the context (current locale and site). To do so, we need to manipulate the default search mechanism. Let create our output channel modifier class.
Output Channel Modifier ```yaml App\DynamicSearch\OutputChannel\Modifier\SiteLocaleRestrictionAction: tags: - { name: dynamic_search.output_channel.modifier.action, output_channel_service_identifier: all, action: post_query_build } ``` ```php requestStack = $requestStack; } /** * {@inheritdoc} * * @throws \Exception */ public function dispatchAction(string $action, OutputChannelAllocatorInterface $outputChannelAllocator, OutputModifierEvent $event): OutputModifierEvent { /** @var Search $search */ $search = $event->getParameter('query'); // Add SimpleQueryString query $simpleQueryStringQuery = new SimpleQueryStringQuery($event->getParameter('term'), [ 'fields' => ['title^100', 'bodytext^50'], ]); $search->addQuery($simpleQueryStringQuery); $boolQuery = new BoolQuery(); // Add locale filter $locale = $this->requestStack->getMainRequest()->query->get('locale'); if ($locale === null) { $locale = $this->requestStack->getMainRequest()->getLocale(); } if ($locale !== null) { $localeQuery = new MatchPhraseQuery('locale', $locale); $boolQuery->add($localeQuery, BoolQuery::FILTER); } // Add site filter $siteId = Site::isSiteRequest() ? Site::getCurrentSite()->getId() : 0; $siteQuery = new TermQuery('siteId', $siteId); $boolQuery->add($siteQuery, BoolQuery::FILTER); // Add bool query $search->addQuery($boolQuery); $event->setParameter('query', $search); return $event; } } ```
And that's it! We are now able to search contents of a multi-site/-locale OpenDXP instance. --- ## Example Setup This setup allows you a quick start with the bundle. The setup is tested within the official opendxp demo and uses class names and properties provided there. Are you looking for an example of a more complex OpenDXP setup? Here's another [example](02_MultiSiteMultiLocaleSetup.md). ### Installation Add the following dependencies to your `composer.json` ```json "require": { "open-dxp/dynamic-search-bundle": "^1.1", "open-dxp/dynamic-search-data-provider-trinity-bundle": "^1.1", "open-dxp/dynamic-search-index-provider-lucene-bundle": "^1.1" } ``` Install them with `composer update`. Then enable the bundles in your `config/bundles.php`: ``` php ['all' => true], \OpenDxp\Bundle\DsTrinityDataBundle\OpenDxpDsTrinityDataBundle::class => ['all' => true], \OpenDxp\Bundle\DsLuceneBundle\OpenDxpDsLuceneBundle::class => ['all' => true], ]; ``` And finalize the installation via command line ```bash bin/console opendxp:bundle:install OpenDxpDynamicSearchBundle ``` ### Symfony Configuration Create a YAML file in your configuration directory ``` yaml # config/packages/dynamic-search.yaml services: App\DynamicSearch\IndexDefinition\TrinityDocument: tags: - { name: dynamic_search.document_definition_builder } App\DynamicSearch\IndexDefinition\Object\Car: tags: - { name: dynamic_search.document_definition_builder } opendxp_dynamic_search: context: # set a context with name "default" default: # set data provider data_provider: service: trinity_data options: always: index_object: true object_class_names: - Car index_document: true index_asset: false full_dispatch: document_limit: 10 normalizer: service: 'trinity_localized_resource_normalizer' # set index provider index_provider: service: 'lucene' options: database_name: 'example_index_database' # build output channels output_channels: autocomplete: service: 'lucene_autocomplete' suggestions: service: 'lucene_suggestions' #options: # restrict_search_fields: # - 'series' normalizer: service: 'lucene_document_key_value_normalizer' #options: # skip_fields: ['name'] search: service: 'lucene_search' internal: false paginator: enabled: true # adapter_class: '' max_per_page: 10 normalizer: service: 'lucene_document_key_value_normalizer' #options: # skip_fields: ['title'] multi_search: multiple: true service: 'lucene_multi_search' use_frontend_controller: true blocks: type1: reference: search type2: reference: search ``` Symfony will detect the config in `config/packages` automatically, you do not have to link it. ### Definition for a DataObject ```php getResourceCollectionType() !== 'object') { return false; } return true; } public function buildDefinition(DocumentDefinitionInterface $definition, array $normalizerOptions): DocumentDefinitionInterface { $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'opendxpId', 'index_transformer' => [ 'type' => 'keyword', ], 'data_transformer' => [ 'type' => 'element_id_extractor' ] ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'name', 'index_transformer' => [ 'type' => 'text', ], 'data_transformer' => [ 'type' => 'object_getter_extractor', 'configuration' => ['method' => 'getName'] ] ]) ->addPreProcessFieldDefinition([ 'type' => 'object_relations_getter_extractor', 'configuration' => [ 'relations' => 'categories', 'method' => 'getId', ] ], function (DocumentDefinitionInterface $definition, array $preProcessedTransformedData) { foreach ($preProcessedTransformedData as $categoryId) { $definition->addSimpleDocumentFieldDefinition([ 'name' => sprintf('category_%d', $categoryId), 'index_transformer' => [ 'type' => 'keyword', ], 'data_transformer' => [ 'type' => 'normalizer_value_callback', 'configuration' => ['value' => '1'] ] ]); } }); return $definition; } } ``` ### Definition for a Document This definition will only save index for the id, title and meta description. If you want to save the content of the page you will have to use the [WebCrawler](https://github.com/open-dxp/dynamic-search-data-provider-crawler) or read the content using callbacks. This might be a bit more complex, as you need to consider the concept of personalized content and your own set of bricks. ``` php getResourceCollectionType() !== 'document') { return false; } return true; } public function buildDefinition(DocumentDefinitionInterface $definition, array $normalizerOptions): DocumentDefinitionInterface { $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'id', 'index_transformer' => [ 'type' => 'keyword', ], 'data_transformer' => [ 'type' => 'element_id_extractor', ] ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'path', 'index_transformer' => [ 'type' => 'text', ], 'data_transformer' => [ 'type' => 'document_path_generator', ] ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'title', 'index_transformer' => [ 'type' => 'text', ], 'data_transformer' => [ 'type' => 'document_meta_extractor', 'configuration' => [ 'type' => 'title', ], ] ]) ->addSimpleDocumentFieldDefinition([ 'name' => 'description', 'index_transformer' => [ 'type' => 'text', ], 'data_transformer' => [ 'type' => 'document_meta_extractor', 'configuration' => [ 'type' => 'description', ], ] ]); return $definition; } } ``` ### Indexing To index your data, execute following in the command line: ``` bash bin/console dynamic-search:run -v ``` The parameter `-v` will make thoe output more verbose and can help you to find any problems in the config. ### Test You can test your setup in browser using the URL `/dynamic-search/default/j-search?q=xk140` where the `q` parameter is the search queue. --- ## Context Guard The context guard adds an additional layer of protection and controll on top of the set of your indexing rules. It allows you to filter the result and avoid indexing unwanted content. To implement a guard add a service that would implement `ContextGuardInterface`. ### Example Setup ``` yaml services: App\DynamicSearch\Guard\DefaultContextGuard: tags: - { name: dynamic_search.context_guard } ``` This simple guard will prevent the document with the id 1 (it is the root document in the opendxp document tree) to be added to the index. It does not check the object type, so it will filter assets and data objects as well. ``` php getResourceId() > 1) { return true; } return false; } } ``` --- ## Create Output Channel ### Basic steps - create a service tagged with `name`: `dynamic_search.output_channel` and a meaningful `identifer` - register your service: ```yaml opendxp_dynamic_search: context: default: output_channels: my_output: service: ``` - your service must implement `OpenDxp\Bundle\DynamicSearchBundle\OutputChannel\OutputChannelInterface` - add your implementation in `getQuery` and `getResult` - optional: define `options` for your output channel ### Example **config/services.yaml** ```yaml services: App\DynamicSearch\OutputChannel\MyOutputChannel: tags: - { name: dynamic_search.output_channel, identifier: my_output_channel } ``` **config/config.yaml** ```yaml opendxp_dynamic_search: context: default: output_channels: my_output: service: 'my_output_channel' use_frontend_controller: true options: query_option: true result_option: false ``` **src/DynamicSearch/OutputChannel/MyOutputChannel.php** ```php namespace App\DynamicSearch\OutputChannel; use OpenDxp\Bundle\DynamicSearchBundle\EventDispatcher\OutputChannelModifierEventDispatcher; use OpenDxp\Bundle\DynamicSearchBundle\OutputChannel\Context\OutputChannelContextInterface; use OpenDxp\Bundle\DynamicSearchBundle\OutputChannel\OutputChannelInterface; use OpenDxp\Bundle\DynamicSearchBundle\OutputChannel\Query\SearchContainerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class MyOutputChannel implements OutputChannelInterface { // properties, getters and setters of OutputChannelInterface go here // omitted in this example ... /** * {@inheritdoc} */ public static function configureOptions(OptionsResolver $optionsResolver) { // define your options $optionsResolver->setRequired([ 'query_option' ]); $optionsResolver->setDefaults([ 'query_option' => false, 'result_option' => true ]); $optionsResolver->setAllowedTypes('query_option', ['bool']); $optionsResolver->setAllowedTypes('result_option', ['bool']); } /** * {@inheritdoc} */ public function getQuery() { $queryTerm = $this->outputChannelContext->getRuntimeQueryProvider()->getUserQuery(); // create your query $query = ... // respect your options if ($this->options['query_option']) { // do something with $query } return $query; } /** * {@inheritdoc} */ public function getResult(SearchContainerInterface $searchContainer): SearchContainerInterface { $query = $searchContainer->getQuery(); // get your results $result = ... // respect your options if ($this->options['result_option']) { // do something with $result } $searchContainer->result->setData($result); $searchContainer->result->setHitCount(count($result)); return $searchContainer; } } ``` --- ## Output Channel Filters / Actions ### Filters @todo ### Actions For most scenarios, especially when using an index provider bundle with existing output channel implementations, it is not required to create a new output channel if you want to modify the search behaviour (fields, boosting, etc.). Dynamic search offers the ability to modify the query by listening to actions. #### Basic steps - create a service tagged with - `name`: `dynamic_search.output_channel.modifier.action` - `output_channel_service_identifier`: `all` to hook into all registered output channels, or the service identifier of one specific output channel. - `action`: the action (event) to which the modifier should listen. for valid action identifiers, check the docs of the package which is providing the output channel you are using (implementation of `OutputChannelInterface`), or search for `$this->eventDispatcher->dispatchAction` in the output channel implementation - `priority`: the priority, default `0` - your modifier must implement `OutputChannelModifierActionInterface` - add your implementation for `dispatchAction`, e.g. modify the query in `OutputModifierEvent` #### Example The following example shows how to modify the query in the `SearchOutputChannel` of the [OpenSearch](https://github.com/open-dxp/dynamic-search-index-provider-opensearch-bundle) package: **config/services.yaml** ```yaml App\DynamicSearch\OutputChannel\Action\Search\MySearchAction: tags: - { name: dynamic_search.output_channel.modifier.action, output_channel_service_identifier: all, action: post_query_build } ``` **src/DynamicSearch/OutputChannel/Action/Search/MySearchAction.php** ```php getParameter('query'); $term = $event->getParameter('term'); $outputChannelName = $outputChannelAllocator->getOutputChannelName(); if ($outputChannelName !== 'search') { return $event; } if ($action !== 'post_query_build') { return $event; } // modify query here, e.g. $query->addQuery(...) $event->setParameter('query', $query); return $event; } ``` --- ## Output Channels Output channels in general control how data is fetched, as well as the output of the retrieved data. The concept of output channels offers high flexibility since there's no limitation regarding the search index provider and how data is queried and output. ### Configuration #### General `dynamic_search.context.default.output_channels.` | property | description | default | |----------------------------|-----------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------| | `multiple` | wether this output channel is a composition of multiple search containers | `false` | | `service` | service for the output channel. must implement `OutputChannelInterface` or `MultiOutputChannelInterface`, if `multiple` is `true` | `null` | | `use_frontend_controller` | wether to use the `SearchFrontendController` for twig output, or the `SearchController` for json output | `false` | | `view_name` | name of the view to use. only effective if `use_frontend_controller` is `true` | `MultiList` if `multiple` is `true`, `List` otherwise. | | `runtime_query_provider` | service for query provider. must implement `RuntimeQueryProviderInterface` | `default` | | `runtime_options_builder` | service for options builder. must implement `RuntimeOptionsBuilderInterface` | `default` | | `internal` | for internal use | `false` | #### Options `dynamic_search.context.default.output_channels..options` options for the output channel go here #### Paginator `dynamic_search.context.default.output_channels..paginator` | property | description | default | |-----------------|---------------------------------------------------------------------|--------------------------------------------------------------| | `enabled` | wether paging is enabled | `false` | | `adapter_class` | implementation to use for paging. must implement `AdapterInterface` | `OpenDxp\Bundle\DynamicSearchBundle\Paginator\Adapter\DynamicSearchAdapter` | | `max_per_page` | max results per page | `10` | #### Normalizer | property | description | default | |---------------|----------------------------------------------------------------------------------------------|---------| | `service` | service to use as normalizer for each document. Must implement `DocumentNormalizerInterface` | `null` | ### Further reading Check out the following implementations of `OutputChannelInterface`: - [SearchOutputChannel](https://github.com/open-dxp/dynamic-search-index-provider-opensearch-bundle/blob/1.x/src/OutputChannel/SearchOutputChannel.php) of `dynamic-search-index-provider-opensearch-bundle` - [SearchOutputChannel](https://github.com/open-dxp/dynamic-search-index-provider-lucene-bundle/blob/1.x/src/OutputChannel/SearchOutputChannel.php) of `dynamic-search-index-provider-lucene-bundle` --- ## Testing(Dynamic-search) The bundle ships a class to test a project with Dynamic Search, under `OpenDxp\Bundle\DynamicSearchBundle\Test`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Write elements into the index `SearchIndex::add()` sends elements through the data provider and the index provider of a context, the same way the element listener does. A test reads the index right afterwards, without a queue or a run. ```php use OpenDxp\Bundle\DynamicSearchBundle\Test\SearchIndex; afterEach(fn () => SearchIndex::clear()); it('finds a product by its name', function () { $product = ProductFactory::createOne(['name' => 'Trail Runner']); SearchIndex::add('shop', $product); // search through the output channel or the API of the project }); ``` The index provider creates the index of the context if it does not exist yet, with the mapping of its definitions. > [!IMPORTANT] > The database of a test rolls back, the index does not. `SearchIndex::clear()` removes every element that `add()` > wrote. Call it after each test that uses `add()`. > [!TIP] > `add()` fails when the context does not take an element, for example a document without a language. It also fails > when the index provider fails, and the message names the reason. --- ## Resource Validation In some cases, you need to validate your resource, before it should get dispatched in a specific operation like `insert`, `update` or `delete`. Just use the `DynamicSearchEvents::RESOURCE_CANDIDATE_VALIDATION` event to manipulate the resource candidate: ```yaml App\DynamicSearch\EventListener\ResourceCandidateListener: tags: - { name: kernel.event_subscriber } ``` ```php ['validateResourceCandidate', 0] ]; } public function validateResourceCandidate(ResourceCandidateEvent $e): void { $resourceCandidate = $e->getResourceCandidate(); $resource = $resourceCandidate->getResource(); // always allow dispatching delete operation as they are if ($resourceCandidate->getDispatchType() === 'delete') { return; } // example I: change dispatch type to force delete if ($yourConditionMet && $resourceCandidate->getDispatchType() === 'update' && $resourceCandidate->isAllowedToModifyDispatchType() === true) { $resourceCandidate->setDispatchType('delete'); } // example II: set resource to null if it should not get indexed at all if ($yourConditionMet && $resourceCandidate->isAllowedToModifyResource() === true) { $resourceCandidate->setResource(null); } } } ``` --- ## Backend UI It is possible to extend the backend user interface. Listen to the event `dynamic_search.event.settings.postBuildLayout`: ```javascript document.addEventListener( 'dynamic_search.event.settings.postBuildLayout', (event) => { const dsSettings = event.detail.subject; dsSettings.panel.add({ 'xtype': 'button', 'text': 'my button' // ...etc }); } ); ``` --- ## Development Tools ### Mate [Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html) gives an AI agent tools that read the running application. This bundle adds its tool when Mate is installed. An agent reaches it through `open-dxp/mate-extension`. Set Mate up as the extension describes. `dynamic_search_contexts` shows the providers, output channels and document definitions of each context. It also shows the messages waiting in the queue and the health status. The OpenSearch index provider adds its own tool for the state of its index. The skill `mate-dynamic-search` tells the agent how a document reaches the index and what to run after a change. --- ## Changelog(Dynamic-search) ### 1.1.2 - [ENHANCEMENT] The admin gets the message of a failed index run as plain text - [NEW FEATURE] `SearchIndex` writes elements into the index of a context during a test. See [Testing](docs/400_Tests.md) - [ENHANCEMENT] A new object or document saved with `OpenDxpElementListener::INDEX_ON_ADD` reaches the index. See [Dispatch Workflow](docs/01_DispatchWorkflow.md) - [BUGFIX] SIGINT and SIGTERM stop `dynamic-search:run` and release its lock, also without the Trinity data provider - [DEPRECATION] `SignalWatchTrait` is deprecated and will be removed in 2.0. Use `SignalableCommandInterface` of Symfony instead - [BUGFIX] `SimpleRunnerInterface::runDelete()` removes the documents of an element from the index - [ENHANCEMENT] A failed save of the runners keeps the error that caused it - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.1 - [NEW FEATURE] Mate skill `mate-dynamic-search` explains how a document reaches the index. See [Development Tools](docs/60_DevelopmentTools.md) - [NEW FEATURE] Mate tool `dynamic_search_contexts` shows the contexts, the queue and the health status. See [Development Tools](docs/60_DevelopmentTools.md) - [BUGFIX] `dynamic-search:run` creates the OpenSearch index even when no document gets indexed - [BUGFIX] `dynamic-search:run` exits with an error code when a context fails - [BUGFIX] A failing context no longer stops `dynamic-search:run` for the other contexts - [BUGFIX] A cancelled `dynamic-search:run` no longer continues with the next element or context - [ENHANCEMENT] `dynamic-search:run` takes `-c` several times to run several contexts - [ENHANCEMENT] Health status names each context without a data provider or an index provider - [BUGFIX] Error for a missing document definition names `DocumentDefinitionContextBuilderInterface` ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [BUGFIX] Deleting a document removes it from the index - [BUGFIX] A field with `data_transformer: null` no longer throws a `TypeError` - [ENHANCEMENT] [MIGRATION] The queue fetches the next message faster. Run the migrations after the update. ### 1.0.4 - [ENHANCEMENT] Add explicit `symfony/doctrine-messenger:^7.4.14` requirement - [ENHANCEMENT] Update `ExtendedDoctrineConnection::configureSchema()` to match the updated doctrine-messenger v7.4.14 signature `(Schema, Connection, \Closure $isSameDatabase)` - [ENHANCEMENT] Add forward-compatibility with DBAL 4.5 immutable schema editor API (`Schema::edit()`, `Table::editor()`, `Column::editor()`) with automatic fallback to the legacy mutable API for DBAL < 4.5 - [ENHANCEMENT] Restore `LockMode` fallback path for DBAL versions without `QueryBuilder::forUpdate()` support ### 1.0.3 - [BUGFIX] Fix QueuedResourcesHandler job skipping (double-ack) - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.2 - [BUGFIX] Fix view names ### 1.0.1 - [ENHANCEMENT] Allow `data_transformer` to accept `null` values and handle null resource field transformers ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix tests [#2](https://github.com/open-dxp/dynamic-search-bundle/pull/2) --- ## Migrating to OpenDXP(Dynamic-search) ### Migrating from `dachcom-digital/dynamic-search` to `open-dxp/dynamic-search-bundle` 1. Replace `dachcom-digital/dynamic-search` with `open-dxp/dynamic-search-bundle` in your `composer.json`. 2. Replace the namespace `DynamicSearchBundle\` with `OpenDxp\Bundle\DynamicSearchBundle\`. 3. Replace `DynamicSearchBundle\DynamicSearchBundle` with `OpenDxp\Bundle\DynamicSearchBundle\OpenDxpDynamicSearchBundle` in `config/bundles.php`. 4. Rename the configuration node `dynamic_search` to `opendxp_dynamic_search`. --- ## Dynamic Search Bundle ![Dynamic Search flow from three ways to start indexing to the output channels of a context](./docs/img/dynamic_search_flow.png) | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `^7.4` | 2025 | Feature Branch | 1.x | ### Introduction The Dynamic Search Bundle allows you to redefine your search strategy. It's based on several data- and index providers. ### Providers There are several data- and index providers available. A context combines one data provider with one index provider. ![Data providers and index providers combined in contexts, with the features of the OpenSearch provider](./docs/img/dynamic_search_providers.png) #### Data Provider - [Trinity Data](https://github.com/open-dxp/dynamic-search-data-provider-trinity-bundle) | Fetch opendxp entities: object, asset, document #### Index Provider - [Open Search](https://github.com/open-dxp/dynamic-search-index-provider-opensearch-bundle) | Index data with an open search instance. - [Lucene Search](https://github.com/open-dxp/dynamic-search-index-provider-lucene-bundle) | Use the php lucene index. Not superfast but comes without any dependencies but php [_legacy, not recommended_] ### Installation ```json "require" : { "open-dxp/dynamic-search-bundle" : "~1.0.0" } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\DynamicSearchBundle\OpenDxpDynamicSearchBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpDynamicSearchBundle` - Execute optionally: `$ bin/console messenger:setup-transports` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\DynamicSearchBundle'` ### Provider Installation You need at least one data- and one index provider. They have to be installed separately. Please check out install instruction of each provider (see list above). ### Add Routes ```yaml # config/routes.yaml dynamic_search_frontend: resource: '@OpenDxpDynamicSearchBundle/config/opendxp/routing/frontend_routing.yaml' ``` ### Start Queue Worker ``` $ bin/console messenger:consume dynamic_search_queue ``` Read more details about the queue worker and the recommended setup [here](docs/01_DispatchWorkflow.md#queue-worker). ### Dispatch Dynamic Search After you've added [a definition](docs/0_ExampleSetup.md), you're ready to start the engine. Always use the verbose `-v` flag, otherwise you won't get any process information about the ongoing data / index providing process. ```bash $ bin/console dynamic-search:run -v ``` ### Further Information - [Example Setup](docs/0_ExampleSetup.md) - [Dispatch Workflow](docs/01_DispatchWorkflow.md) - Configuration - [Context Guard](docs/200_ContextGuard.md) - Document Definition - Logging - Data Creation - [Resource Validation](docs/40_ResourceValidator.md) - Enable automatic Update / Insert / Delete Service - Data Fetching - [Output Channels](docs/30_OutputChannels.md) - [Create Output Channel](docs/300_CreateOutputChannel.md) - [Channel Filter / Actions](docs/302_ChannelFilterActions.md) - Multi Search Channels - Filter (Faceted Search / Aggregation) - Create Filter Definition - [Backend UI](docs/50_BackendUI.md) - The panel under Settings > Dynamic Search shows the health status, the installed providers and the index queue. - [Development Tools](docs/60_DevelopmentTools.md) - [Testing](docs/400_Tests.md) - API *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## The Publishing/Unpublishing Problem Processing publish states of elements definitely sounds easier than it is. ### Prologue In V1 of this bundle, there was a `object_ignore_unpublished` and `object_ignore_unpublished` option flag. Back then, trinity skipped unpublished objects by default. ### New Ways In V2 we're fetching unpublished elements by default. If we wouldn't allow unpublished elements, they would stay forever in index. Imagine an published element which is published at index time. But if you're going to unpublish it, and maybe you're editing this element afterwards, it wil never get updated again, because the internal validator would disallow unpublished elements. So what can you do? There are two options: ### Way I: Index every Element regardless its publishing state You could fetch every document regardless its state. You could add a `published` flag to your document definition and filter by this flag in your frontend query. ### Way II: Resource Validation Within the `DynamicSearchEvents::RESOURCE_CANDIDATE_VALIDATION` event, you're able to modify the state of resource. So for example, you could disallow to fetch the unpublished element at `index` or `insert` operations but allow it to modify/delete it on `update` or `delete` operations. Read more about the resource validator [here](https://github.com/open-dxp/dynamic-search-bundle/blob/1.x/docs/40_ResourceValidator.md). --- ## Changelog(Dynamic-search-data-provider-trinity) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix tests [#2](https://github.com/open-dxp/dynamic-search-data-provider-trinity-bundle/pull/2) --- ## Migrating to OpenDXP(Dynamic-search-data-provider-trinity) ### Migrating from `dachcom-digital/dynamic-search-data-provider-trinity` to `open-dxp/dynamic-search-data-provider-trinity-bundle` 1. Replace `dachcom-digital/dynamic-search-data-provider-trinity` with `open-dxp/dynamic-search-data-provider-trinity-bundle` in your `composer.json`. 2. Replace the namespace `DsTrinityDataBundle\` with `OpenDxp\Bundle\DsTrinityDataBundle\`. 3. Replace `DsTrinityDataBundle\DsTrinityDataBundle` with `OpenDxp\Bundle\DsTrinityDataBundle\OpenDxpDsTrinityDataBundle` in `config/bundles.php`. 4. Rename the configuration node `ds_trinity_data` to `opendxp_ds_trinity_data`. --- ## DS Data Provider: Trinity Data A data fetch extension for [OpenDXP Dynamic Search](https://github.com/open-dxp/dynamic-search-bundle). Fetch opendxp elements by listings: `assets`, `documents` and `objects`. ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `^7.4` | 2025 | Feature Branch | 1.x | *** ### Installation ```json "require" : { "open-dxp/dynamic-search-bundle" : "~1.0.0", "open-dxp/dynamic-search-data-provider-trinity-bundle" : "~1.0.0" } ``` #### Dynamic Search Bundle You need to install / enable the Dynamic Search Bundle first. Read more about it [here](https://github.com/open-dxp/dynamic-search-bundle#installation). After that, proceed as followed: Add Bundle to `bundles.php`: ```php ['all' => true], ]; ``` *** ### Publishing State **This Bundle will fetch unpublished elements by default**. This is crucial and also a problematic fact. Read more about it [here](./docs/10_publishUnpublishedElements.md) to learn how to handle the publishing state of opendxp elements. ### Basic Setup ```yaml opendxp_dynamic_search: context: default: data_provider: service: 'trinity_data' options: always: index_object: true object_class_names: - TestClass index_document: true index_asset: false full_dispatch: object_limit: 20 document_limit: 10 normalizer: service: 'trinity_localized_resource_normalizer' ``` *** ### Provider Options #### always | Name | Default Value | Description | |:-----------------------------------|:----------------------------------------|:------------| | `index_asset` | false | | | `asset_data_builder_identifier` | true | | | `asset_types` | `Asset::getTypes()`, except folder | | | `asset_additional_params` | [] | | | | | | | `index_object` | false | | | `object_data_builder_identifier` | 'default' | | | `object_types` | `DataObject::getTypes()`, except folder | | | `object_class_names` | [] | | | `object_additional_params` | [] | | | | | | | `index_document` | false | | | `document_data_builder_identifier` | 'default' | | | `document_types` | `Document::getTypes()`, except folder | | | `document_additional_params` | [] | | #### full_dispatch | Name | Default Value | Description | |:-----------------|:--------------|:------------| | `asset_limit` | 0 | | | `object_limit` | 0 | | | `document_limit` | 0 | | *** ### Resource Normalizer #### trinity_default_resource_normalizer Scaffold simple documents Options: none #### trinity_localized_resource_normalizer Scaffold localized documents Options: | Name | Default Value | Allowed Type | Description | |:-------------------------------|:------------------------------|:-------------|:----------------------------------------------------------------------| | `locales` | all opendxp enabled languages | array | | | `skip_not_localized_documents` | true | bool | if false, an exception rises if a document/object has no valid locale | *** ### Transformer #### Scaffolder ###### TrinityDataScaffolder Identifier: `trinity_data_scaffolder` Simple object scaffolder. Supported types: `Asset`, `Document`, `DataObject\Concrete`. #### Field Transformer ###### ElementIdExtractor Identifier: `element_id_extractor` Returns id of element Return Type: `string|int|null` Options: none ###### ElementPropertyExtractor Identifier: `element_property_extractor` Returns element property. Return Type: `string|null` Options: | Name | Default Value | Allowed Type | Description | |:------------------------|:--------------|:-------------|:------------| | `property` | null | string | | | `object_getter` | null | null | string | | `allow_inherited_value` | true | bool | | ###### NormalizerValueCallback Identifier: `normalizer_value_callback` Returns given option `value`. Return Type: `string|null` Options: | Name | Default Value | Allowed Type | Description | |:--------|:--------------|:-------------|:------------| | `value` | null | string | | ###### ObjectGetterExtractor Identifier: `object_getter_extractor` Returns value of object getter. Return Type: `bool|int|float|string|array|null` Options: | Name | Default Value | Allowed Type | Description | |:---------------------|:--------------|:--------------|:------------------------------------------------| | `method` | id | string | | | `arguments` | [] | array | | | `clean_string` | true | bool | cleans HTML and whitespace (if value is string) | | `transform_callback` | null | null\|closure | a callback function for further value transform | ###### ObjectRelationsGetterExtractor Identifier: `object_relations_getter_extractor` Returns values of object relations getter. Return Type: `array|null` Options: | Name | Default Value | Allowed Type | Description | |:------------|:--------------|:-------------|:------------| | `relations` | null | string | | | `method` | id | string | | | `arguments` | [] | array | | ###### ObjectPathGenerator Identifier: `object_path_generator` Returns object path generated by link generator. Return Type: `string|null` Options: | Name | Default Value | Allowed Type | Description | |:---------------------------|:--------------|:-------------|:----------------------------------------------------------------------------------------------------------------| | `arguments` | [] | array | | | `fetch_object_for_variant` | false | bool | If true and object is type of `variant` the next parent gets fetched first until type `object` has been reached | ###### DocumentMetaExtractor Identifier: `document_meta_extractor` Returns documents meta title or description. Return Type: `string|null` Options: | Name | Default Value | Allowed Type | Description | |:-------|:--------------|:-------------|:-----------------------------------------| | `type` | title | string | Possible Types: `title` or `description` | ###### DocumentPathGenerator Identifier: `document_path_generator` Returns real full path of document Return Type: `string|null` Options: none ###### PdfDataExtractor Identifier: `asset_pdf_extractor` Extracts pdf content with ghostscript Return Type: `string|null` Options: none ###### AssetPathGenerator Identifier: `asset_path_generator` Returns real full path of document Return Type: `string|null` Options: none *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Custom Analyzer We're using the `CaseInsensitive` Analyzer by default. But it's also possible to use a custom analyzer. A Analyzer is used on indexing and query time. #### Listener ```yaml App\EventListener\LuceneAnalyzerListener: autowire: true public: false tags: - { name: kernel.event_listener, event: ds_lucene.analyzer.build, method: build } ``` #### Service ```php setAnalyzer($analyzer); } } ``` *** ### Syllable Analyzer The Lucene Data Provider Bundles comes with a pre-configured Syllable Analyzer, which is **disabled by default**. The Syllable Analyzer allows you to split your indexable strings into reasonable chunks, based on a given locale. To achive this, we're using the [OrgHeiglHyphenator Library](https://github.com/heiglandreas/Org_Heigl_Hyphenator) library ([Documentation](https://orgheiglhyphenator.readthedocs.io/en/latest/)). #### Benefits / Workflow: Example Data: `We have some really long words in german like sauerstofffeldflasche` 1. **Split Data**: `We have some re al ly long words in ger man like sau er stoff feld fla sche.` 2. **Add Original Data**: `We have some really long words in german like sauerstofffeldflasche We have some re al ly long words in ger man like sau er stoff feld fla sche.` 3. **Final Unique Data**: `We have some really long words in german like sauerstofffeldflasche re al ly ger man sau er stoff feld fla sche.` 4. Send Data to Tokenizer. If you also have enabled the [stopwords filter](./1_CustomTokenFilter.md), you can get rid of unnecessary words like `er` or `re` too. #### Setup First, you need to install the library ```bash $ composer require org_heigl/hyphenator:^2.3 ``` ### Listener Now, add the listener (basically the same as described above) ```yaml App\EventListener\LuceneSyllableAnalyzerListener: autowire: true public: false tags: - { name: kernel.event_listener, event: ds_lucene.analyzer.build, method: build } ``` #### Service Finally, add the service: ```php CaseInsensitive Analyzer if (!$event->isIndexMode()) { return; } $options = new Hyphenator\Options(); $options->setHyphen(' ') ->setDefaultLocale($this->checkLocale($event->getLocale())) ->setRightMin(4) ->setLeftMin(2) ->setWordMin(5) ->setFilters('NonStandard') ->setTokenizers(['Whitespace', 'Punctuation']); $analyzer = new Syllable(); // if you don't define any options, some default options will be generated $analyzer->setHyphenatorOptions($options); $event->setAnalyzer($analyzer); } protected function checkLocale(?string $locale): string { if (empty($locale)) { return 'en'; } switch ($locale) { case 'de': return 'de_DE'; case 'it': return 'it_IT'; default: return $locale; } } } ``` --- ## Custom Token Filter Add some token filter like stopwords or a stemming filter. By default, **no** filter is enabled. This Bundles comes with two preconfigured filters. - Stop Words - Stemmer But you're also able to add your custom filter. But first let's checkout, how to enable the preconfigured filters: ### Stop Words #### Configuration You need to add the `stop_words` block to `filter`, to enable it. There is no further configuration required. You're able to define your own stopwords library, if you want to. ```yaml opendxp_dynamic_search: context: default: index_provider: service: 'lucene' options: database_name: 'default' analyzer: # forced_locale: de filter: stop_words: on_index_time: true on_query_time: false libraries: - locale: de file: '%%dsl_stop_words_lib_path%%/de' - locale: fr file: '%%dsl_stop_words_lib_path%%/fr' - locale: it file: '%%dsl_stop_words_lib_path%%/it' - locale: en file: '%%dsl_stop_words_lib_path%%/en' ``` #### Options | Name | Default Value | Description | |:---------------------------------|:--------------|:------------| |`on_index_time` | true | Enabled filter on index time | |`on_query_time` | true | Enabled filter on query time | |`libraries` | array | Set a custom library for each locale. `dsl_stop_words_lib_path` is a default path to our internal library | ### Stemmer #### Configuration You need to add the `stemming` block to `filter`, to enable it. There is no further configuration required. You're able to choose your own stemmer class, if you want to. ```yaml opendxp_dynamic_search: context: default: index_provider: service: 'lucene' options: database_name: 'default' analyzer: # forced_locale: de filter: stemming: on_index_time: true on_query_time: true locale_aware: true class: '\OpenDxp\Bundle\DsLuceneBundle\Lucene\Filter\Stemming\SnowBallStemmingFilter' ``` #### Options | Name | Default Value | Description | |:---------------------------------|:--------------|:------------| |`on_index_time` | true | Enabled filter on index time | |`on_query_time` | true | Enabled filter on query time | |`locale_aware` | false | If set to `true`, a locale is required, otherwise the stemmer will be skipped | |`class` | `'\OpenDxp\Bundle\DsLuceneBundle\Lucene\Filter\Stemming\SnowBallStemmingFilter'` | The SnowBall Stemmer per default | ### Custom Filter Add your custom filter #### Configuration Add your custom filter block to `filter`, to enable it. ```yaml opendxp_dynamic_search: context: default: index_provider: service: 'lucene' options: database_name: 'default' analyzer: # forced_locale: de filter: my_custom_filter: on_index_time: true on_query_time: true locale_aware: true class: 'App\Lucene\Filter\MyFilter\MyFilterClass' ``` #### Options | Name | Default Value | Description | |:---------------------------------|:--------------|:------------| |`on_index_time` | true | Enabled filter on index time | |`on_query_time` | true | Enabled filter on query time | |`locale_aware` | false | If set to `true`, a locale is required, otherwise the filter will be skipped | |`class` | null | Set your custom filter class | #### Analyzer Configuration You may have noticed the `forced_locale` flag. If you don't have multiple languages, just define a default one. | Name | Default Value | Description | |:---------------------------------|:--------------|:------------| |`forced_locale` | null | Use a default locale like `en` | --- ## Debugging(Dynamic-search-index-provider-lucene) To debug a lucene index you may want to give [luke](https://code.google.com/archive/p/luke/) a try. Please keep in mind that you need to [download](https://code.google.com/archive/p/luke/downloads) Version 3.5 otherwise you're not able to open the lucene index! --- ## Changelog(Dynamic-search-index-provider-lucene) ### 1.1.2 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.1 - [ENHANCEMENT] A repeated `-c` of `dynamic-search:run` drops the Lucene index of each given context ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.1 - [BUGFIX] Fixed full re-index only writing the last processed document to the Lucene stable index ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update bundle files [#1](https://github.com/open-dxp/dynamic-search-index-provider-lucene-bundle/pull/1) --- ## Migrating to OpenDXP(Dynamic-search-index-provider-lucene) ### Migrating from `dachcom-digital/dynamic-search-index-provider-lucene` to `open-dxp/dynamic-search-index-provider-lucene-bundle` * Moved bundle to new namespace: `OpenDxp\Bundle\DsLuceneBundle`. * Renamed bundle to `OpenDxpDsLuceneBundle`. * Renamed top-level config node to `opendxp_ds_lucene`. --- ## DS Index Provider: Lucene An index storage extension for [OpenDXP Dynamic Search](https://github.com/open-dxp/dynamic-search-bundle). Store data with the PHP Lucene index service. ### ⚠️ Important - EOL announcement This extension has reached its end of life and won't be migrated for PHP 9. Support for PHP 8.x will be continued until the latest PHP 8.x version reached its end of life (as of now, 31.12.2029) ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `^7.4` | 04.02.2026 | Feature Branch | 1.x | *** ### Installation ```json "require" : { "open-dxp/dynamic-search-bundle" : "~1.0.0", "open-dxp/dynamic-search-index-provider-lucene-bundle" : "~1.0.0" } ``` #### Dependencies This package will also install a fork of [ZendSearch](https://github.com/dachcom-digital/ZendSearch) to provide the latest PHP compatibility. #### Dynamic Search Bundle You need to install / enable the Dynamic Search Bundle first. Read more about it [here](https://docs.opendxp.io/docs/bundles/dynamic-search/#installation). After that, proceed as followed: Add Bundle to `bundles.php`: ```php ['all' => true], ]; ``` *** ### Basic Setup ```yaml opendxp_dynamic_search: context: default: index_provider: service: 'lucene' options: database_name: 'my_lucene_storage' ``` *** ### Provider Options | Name | Default Value | Description | |:------------------------|:--------------|:------------| | `database_name` | null | | | `force_adding_document` | true | | | `analyzer` | [] | | *** ### Index Fields **Available Index Fields**: | Name | Description | |:------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `binary` | Binary fields are not tokenized or indexed, but are stored for retrieval with search hits. They can be used to store any data encoded as a binary string, such as an image icon. | | `keyword` | Keyword fields are stored and indexed, meaning that they can be searched as well as displayed in search results. They are not split up into separate words by tokenization. | | `text` | Text fields are stored, indexed, and tokenized. Text fields are appropriate for storing information like subjects and titles that need to be searchable as well as returned with search results. | | `unIndexed` | UnIndexed fields are not searchable, but they are returned with search hits. Database timestamps, primary keys, file system paths, and other external identifiers are good candidates for UnIndexed fields. | | `unStored` | UnStored fields are tokenized and indexed, but not stored in the index. Large amounts of text are best indexed using this type of field. Storing data creates a larger index on disk, so if you need to search but not redisplay the data, use an UnStored field. | *** ### Output Channel Services #### Autocomplete **Identifier**: `lucene_autocomplete` **Available Options**: | Name | Default Value | Description | |:---------------------------------|:--------------|:------------| | `min_prefix_length` | 3 | | | `use_fuzzy_term_search_fallback` | true | | | `fuzzy_default_prefix_length` | | | | `fuzzy_similarity` | 0.5 | | #### Suggestions **Identifier**: `lucene_suggestions` **Available Options**: | Name | Default Value | Description | |:----------------------------------|:--------------|:------------| | `min_prefix_length` | 3 | | | `result_limit` | 10 | | | `only_last_word_wildcard` | false | | | `multiple_words_operator` | 'OR' | | | `restrict_search_fields` | [] | | | `restrict_search_fields_operator` | 'OR' | | #### Search **Identifier**: `lucene_search` **Available Options**: | Name | Default Value | Description | |:--------------------|:--------------|:------------| | `min_prefix_length` | 3 | | | `max_per_page` | 10 | | #### Multi Search **Identifier**: `lucene_multi_search` **Available Options**: none *** ### Filter #### RelationsFilter **Identifier**: `relations` **Available Options**: | Name | Default Value | Allowed Type | Description | |:-------------------|:--------------|:--------------|:------------| | `identifier` | null | string | | | `value` | null | string | | | `label` | null | string, null | | | `show_in_frontend` | true | bool | | | `relation_label` | null | closure, null | | ### Output Normalizer A Output Normalizer can be defined for each output channel. #### lucene_document_key_value_normalizer **Available Options**: | Name | Default Value | Description | |---------------|---------------|-------------| | `skip_fields` | [] | | ### Further Information - Lucene Configuration - [Custom Analyzer](./docs/0_Custom_Analyzer.md) (Example: Syllable Analyzer) - [Lucene Token Filter](./docs/1_CustomTokenFilter.md) (Stemming Filter, Stop Words Filter) - [Debugging](./docs/2_Debugging.md) (Debugging Lucene Index Database) *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Dynamic-search-index-provider-opensearch) ### 1.3.3 - [ENHANCEMENT] The admin gets the message of a failed rebuild of the mapping as plain text - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.3.2 - [BUGFIX] `dynamic-search:os:migrate switch` no longer fails on OpenSearch 3 with "Cannot parse scroll id" ### 1.3.1 - [NEW FEATURE] Mate skill `mate-dynamic-search-opensearch` covers the field mapping and the rebuild after a change - [NEW FEATURE] Mate tool `dynamic_search_opensearch_indices` shows the index, the aliases and the document count of each context - [BUGFIX] `dynamic-search:os:rebuild-index-mapping` reports a declined or unanswered question as failure - [ENHANCEMENT] `dynamic-search:os:rebuild-index-mapping` rebuilds without asking with `--force` - [ENHANCEMENT] `dynamic-search:os:rebuild-index-mapping` takes `-c` several times to rebuild several contexts - [BUGFIX] Error for a missing document definition names `DocumentDefinitionContextBuilderInterface` - [CHORE] Require `open-dxp/dynamic-search-bundle` ^1.1.1 ### 1.3.0 - [BUGFIX] `switch` no longer fails when the journal of a migration names a document that never reached the new index - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.2.0 - [ENHANCEMENT] An index is created as `_` behind a read alias `` and a write alias `_write`. A plain index named `` keeps working and moves behind the aliases the next time it is rebuilt or migrated - [ENHANCEMENT] New command `dynamic-search:os:migrate` with the actions `start`, `switch`, `abort` and `status` changes an index mapping without downtime. While a migration is open both indexes receive every write, so nothing is lost while the copy runs. The copy runs as a task inside the cluster and `switch` waits for it. Deletions during the copy are journaled and removed from the new index by `switch`. `dynamic-search:os:rebuild-index-mapping` discards an open migration. The migration state is stored in the `_meta` of the new mapping - [ENHANCEMENT] New provider option `search_pipeline` declares an opensearch search pipeline with the context. It is named `_search` and created before the index - [ENHANCEMENT] `IndexPersistenceService::createIndex()` takes an index name and a mapping `_meta` array as additional optional arguments. Without an index name it creates a new timestamped index and both aliases - [ENHANCEMENT] `opensearch-project/opensearch-php` now requires `^2.4`. It carries `Client::searchPipeline()` and `NotFoundHttpException`, which replaces the deprecated `Missing404Exception` ### 1.1.1 - [BUGFIX] Fix GeoDistanceFilter passing an array instead of Location to GeoDistanceQuery ### 1.1.0 - [ENHANCEMENT] PHP 8.5 Support added - [ENHANCEMENT] Changed dependency `smoench/opensearch-dsl` to `shyim/opensearch-php-dsl` to provide better php support ### 1.0.1 - [BUGFIX] Update `coolDown` method to include `INSERT` dispatch type in condition check ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix test infrastructure [#1](https://github.com/open-dxp/dynamic-search-index-provider-opensearch-bundle/pull/1) --- ## Migrating to OpenDXP(Dynamic-search-index-provider-opensearch) ### Migrating from `dachcom-digital/dynamic-search-index-provider-opensearch` to `open-dxp/dynamic-search-index-provider-opensearch-bundle` 1. Replace `dachcom-digital/dynamic-search-index-provider-opensearch` with `open-dxp/dynamic-search-index-provider-opensearch-bundle` in your `composer.json`. 2. Replace the namespace `DsOpenSearchBundle\` with `OpenDxp\Bundle\DsOpenSearchBundle\`. 3. Replace `DsOpenSearchBundle\DsOpenSearchBundle` with `OpenDxp\Bundle\DsOpenSearchBundle\OpenDxpDsOpenSearchBundle` in `config/bundles.php`. 4. Rename the configuration node `ds_opensearch` to `opendxp_ds_opensearch`. --- ## DS Index Provider: OpenSearch An index storage extension for [OpenDXP Dynamic Search](https://github.com/open-dxp/dynamic-search-bundle). Store data with the opensearch index service. ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `^7.4` | 2025 | Feature Branch | 1.x | *** ### Installation ```json { "require" : { "open-dxp/dynamic-search-bundle" : "~1.0.0", "open-dxp/dynamic-search-index-provider-opensearch-bundle" : "~1.2.0" } } ``` #### Dynamic Search Bundle You need to install / enable the Dynamic Search Bundle first. Read more about it [here](https://github.com/open-dxp/dynamic-search-bundle#installation). After that, proceed as followed: Add Bundle to `bundles.php`: ```php ['all' => true], ]; ``` *** ### Basic Setup ```yaml opendxp_dynamic_search: enable_opendxp_element_listener: true context: default: index_provider: service: 'opensearch' options: index: identifier: 'default' hosts: - 'opensearch:9200' settings: [] credentials: # optional, empty array username: '%OS_USERNAME%' password: '%OS_PASSWORD%' analysis: analyzer: keyword_analyzer: tokenizer: keyword type: custom filter: - lowercase - asciifolding - trim char_filter: [] edge_ngram_analyzer: tokenizer: edge_ngram_tokenizer filter: - lowercase edge_ngram_search_analyzer: tokenizer: lowercase tokenizer: edge_ngram_tokenizer: type: edge_ngram min_gram: 2 max_gram: 5 token_chars: - letter output_channels: suggestions: service: 'opensearch_search' normalizer: service: 'os_document_raw_normalizer' paginator: enabled: false search: service: 'opensearch_search' use_frontend_controller: true options: result_limit: 10 normalizer: service: 'os_document_source_normalizer' paginator: enabled: true max_per_page: 10 ``` *** ### Index Names The `identifier` you configure is not the name of an index. It is the name of an alias. | Name | Is | |----------------------------|-------------------------------------------------------------| | `` | read alias, points at exactly one index | | `_write` | write alias, points at one index, at two during a migration | | `_` | the index itself | Searches go through the read alias. Writes go into every index behind the write alias. Both aliases keep their name for good. The index behind them is created fresh by a rebuild or a migration, so its name carries the moment it was created. A context that still writes into a plain index named `` keeps working. Its first migration moves it behind the aliases. *** ### Provider Options | Name | Default Value | Description | |:------------------|:--------------|:-------------------------------------------------| | `index` | [] | connection and index name, see below | | `analysis` | [] | analyzers and tokenizers the index is built with | | `search_pipeline` | [] | a search pipeline the context needs, see below | #### index | Name | Default Value | Allowed Type | Description | |:------------------------|:--------------|:-------------|:-------------------------------------------------------------------------------| | `identifier` | null | string | name of the read alias, see above | | `hosts` | null | array | one or more `host:port` entries | | `settings` | null | array | opensearch index settings, `analysis` is merged into them | | `credentials.username` | null | string, null | basic authentication | | `credentials.password` | null | string, null | basic authentication | | `force_adding_document` | true | bool | an update for a document the index does not hold yet adds it, `false` skips it | `identifier`, `hosts` and `settings` have no usable default. Set all three, an empty array is enough for `settings`. #### analysis Every entry that is not empty ends up under `settings.analysis` of the index. | Name | Default Value | |:--------------|:--------------| | `analyzer` | [] | | `char_filter` | [] | | `filter` | [] | | `normalizer` | [] | | `tokenizer` | [] | #### search_pipeline A hybrid query needs a pipeline with a normalization processor, otherwise the scores of its clauses are not comparable. Declare the pipeline with the context. It is created before the index. > [!NOTE] > Search pipelines need OpenSearch 2.8. The `normalization-processor` of the example below needs 2.10. > Without a `definition` the bundle makes no pipeline request, so older clusters are not affected. ```yaml opendxp_dynamic_search: context: default: index_provider: service: opensearch options: search_pipeline: definition: description: 'hybrid search' phase_results_processors: - normalization-processor: normalization: technique: min_max combination: technique: arithmetic_mean ``` | Name | Default Value | Allowed Type | Description | |:-----------------|:--------------|:-------------|:-------------------------------------------------------| | `definition` | [] | array | body of the pipeline, an empty array means no pipeline | | `set_as_default` | false | bool | run every search on the index through the pipeline | The pipeline is named `_search`. Pass it per search request, which is what `PostBuildSearchEvent::setSearchPipeline()` in the headless bundle is for. `set_as_default: true` writes `index.search.default_pipeline` into the index instead. Then every search on that index runs through the pipeline, including the ones that are not hybrid queries. Use it only when every query against that index is a hybrid query. *** ### Index Fields The `index_transformer` of a document field definition decides how the field is mapped. **Available Index Fields**: | Name | Description | |:-----------|:------------------------------------------------------------------------| | `dynamic` | no mapping is written, opensearch derives the type from the data | | `explicit` | the `configuration` of the transformer becomes the mapping of the field | ```php $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'title', 'index_transformer' => [ 'type' => 'explicit', 'configuration' => [ 'type' => 'text', 'analyzer' => 'keyword_analyzer', ], ], 'data_transformer' => [ 'type' => 'document_meta_extractor', 'configuration' => ['type' => 'title'], ], ]); ``` > [!IMPORTANT] > A document definition uses either `dynamic` or `explicit` fields. Mixing both fails with > `You cannot mix dynamic and explicit index fields for mappings`. *** ### Output Channel Services #### Search This channel service builds an `OpenSearchDSL\Search` object and runs it against the read alias. You're able to modify the search by hooking via `dynamic_search.output_channel.modifier.action` into the `post_query_build` action. **Identifier**: `opensearch_search` **Available Options**: | Name | Default Value | Allowed Type | Description | |:---------------|:--------------|:-------------|:--------------| | `result_limit` | 10 | int | hits per page | Before the term reaches the query it is lowercased, stripped of tags and collapsed to single spaces. Two actions are dispatched: `post_query_build` with the `OpenSearchDSL\Search` object and the cleaned `term`, and `post_result_execute` with the hits of the response. Paging is done with `from` and `size`, taken from the current page and `result_limit`. A `result_limit` above 10,000 is refused, that is where opensearch stops paging. *** ### Filter Filters come from a service that implements `FilterDefinitionBuilderInterface` of the dynamic search bundle and carries the tag `dynamic_search.filter_definition_builder`. Every definition it adds names a `type`, and that `type` picks one of the filters below. The `configuration` carries the options of that filter. ```php $definition ->addFilterDefinition([ 'type' => 'aggregation', 'name' => 'category', 'label' => 'Category', 'configuration' => [ 'field' => 'category', 'size' => 20, ], ]); ``` All four filters share these options: | Name | Default Value | Allowed Type | Description | |:---------------------|:--------------|:--------------|:---------------------------------------------------------------------------------| | `field` | null | string | the document field the filter works on | | `label` | null | string, null | handed to the view and translated there | | `show_in_frontend` | true | bool | whether the filter is rendered at all | | `add_as_post_filter` | false | bool | add a post filter instead of a query, so the aggregation counts stay untouched | | `multiple` | true | bool | the request delivers an array of values instead of a single one | | `relation_label` | null | closure, null | called with the bucket value and the locale, returns the label of that one value | | `size` | 10 | int | number of buckets | | `query_type` | `must` | string | how the selected values are combined in the bool query | #### Aggregation **Identifier**: `aggregation` A terms aggregation on `field`. Every selected value becomes a term query on the same field. #### Composite Aggregation **Identifier**: `composite_aggregation` A composite aggregation over several fields, so one bucket stands for a combination of values. `field` is not available here. | Name | Default Value | Allowed Type | Description | |:------------|:--------------|:-------------|:--------------------------------------------------------| | `fields` | [] | array | the fields the aggregation is built from, in order | | `separator` | `__` | string | joins the values of one bucket into a single form value | A selected value is split at the separator again. Each part becomes a term query on the field at the same position in `fields`. #### Range Aggregation **Identifier**: `range_aggregation` | Name | Default Value | Allowed Type | Description | |:---------|:--------------|:-------------|:------------------------------------------------------------------| | `ranges` | [] | array | the opensearch range buckets, no aggregation is added while empty | | `mode` | `gte` | string | `gt`, `gte`, `lt` or `lte`, how the submitted value is compared | The submitted value becomes one range query on `field`, it is not a bucket key. #### Geo Distance **Identifier**: `geo_distance` Narrows the result to a distance around a point. There is no aggregation, so there are no buckets and no counts. | Name | Default Value | Allowed Type | Description | |:-----------------|:-----------------------|:-------------|:-------------------------------------| | `distance_unit` | `km` | string | `m`, `km` or `mi` | | `distance_range` | 0, 10, 20, 30, 40, 50 | array | the distances the view offers | The filter reads two request values: `` holding `lat,lon` and `_distance` holding the distance. Both have to be there and the coordinates have to be numeric, otherwise the filter does nothing. #### View Vars `aggregation`, `composite_aggregation` and `range_aggregation` hand `name`, `label`, `multiple` and `values` to the view. Every entry of `values` carries `form_name`, `value`, `count`, `active` and `relation_label`. `geo_distance` hands over `form_name`, `distance_form_name`, `distance_unit` and `distance_range`. A form for both shapes ships in `templates/OutputChannel/Filter/`. *** ### Output Normalizer A Output Normalizer can be defined for each output channel. #### os_document_raw_normalizer Use this normalizer to get the untouched opensearch response. **Available Options**: Currently none #### os_document_source_normalizer Use this normalizer to get all document values (`_source`) stored in `response.hits.hits[]` **Available Options**: Currently none *** ### Commands #### Rebuild Index Mapping A mapping change with downtime. The index behind the read alias is dropped and built again from the document definition. The new index carries a new timestamp and the aliases move with it. An open migration of the context is discarded as well, together with its copy and its journal. > [!WARNING] > All data is lost. Run `dynamic-search:run` afterwards to fill the index again. Searches find nothing until > that run is done. ```bash $ bin/console dynamic-search:os:rebuild-index-mapping -c default ``` The command asks for confirmation first. `--force` skips the question. Without a terminal, the command refuses to run unless `--force` is given. Name each context with `-c` to rebuild several at once: ```bash $ bin/console dynamic-search:os:rebuild-index-mapping -c shop -c blog --force ``` The same action sits in the backend under *Settings > Dynamic Search*, with one entry per context. #### Migrate Index A mapping change without downtime. The new index is built next to the live one. The read alias moves over at the end. > [!TIP] > The live index keeps serving searches until `switch`. `abort` brings you back to where you started at any time. ##### Where the data comes from `start` creates the new index and copies every document of the live index into it. The copy runs inside OpenSearch. You do not run `dynamic-search:run` for it. `dynamic-search:run` is only needed for fields the copy cannot fill. That is a field the old documents do not have yet, or a field whose old values do not fit the new mapping. ##### All fields can be copied For example, you changed an analyzer or added a subfield. ```bash $ bin/console dynamic-search:os:migrate start -c default $ bin/console dynamic-search:os:migrate status -c default # repeat until the copy is done $ bin/console dynamic-search:os:migrate switch -c default ``` ##### Some fields have to be filled again For example, you added a field, or a field changed its type. Name these fields with `--exclude`. The copy leaves them out, and `dynamic-search:run` fills them. ```bash $ bin/console dynamic-search:os:migrate start -c default --exclude=description $ bin/console dynamic-search:os:migrate status -c default # repeat until the copy is done $ bin/console dynamic-search:run -c default $ bin/console dynamic-search:os:migrate status -c default # shows how many documents still lack the field $ bin/console dynamic-search:os:migrate switch -c default ``` `switch` refuses as long as no document has a value for an excluded field. The details are in [Excluded fields](#excluded-fields). > [!NOTE] > A migration carries over every document of the live index, including documents the current definition would > not produce anymore. Only a rebuild followed by `dynamic-search:run` removes them. ##### What happens where | Step | Searches read from | Changes are written to | |-----------------|--------------------|------------------------| | before `start` | old index | old index | | after `start` | old index | old and new index | | after `switch` | new index | new index | | after `abort` | old index | old index | The only moment that changes what a visitor sees is `switch`. It moves the read alias in one step, so there is no gap in which a search finds nothing. | Action | Does | |----------|-----------------------------------------------------------------------------------------------------| | `start` | creates the new index, adds it to the write alias, starts the copy and returns | | `status` | shows the indexes of the context, the progress of the copy and what the switch is waiting for | | `switch` | refuses while the copy runs, removes deleted documents, moves the read alias, deletes the old index | | `abort` | stops the copy, removes the new index from the write alias and deletes it | ##### The copy The copy runs inside the cluster. It does not depend on your console session, and a large index takes as long as it takes. `start` returns as soon as the copy is under way. `status` shows how many documents are done. `switch` refuses until the copy has finished. If the cluster reports a failure, or forgot the copy after a restart, `status` says so. Remove the migration with `abort` and start again. > [!NOTE] > A copy of a large index puts load on the cluster. Start it at a quiet time. Between `start` and `switch` every write goes into both indexes, so nothing that changes during the copy gets lost. An update for a document the new index does not hold yet creates it there. A document that already arrived in the new index that way is not overwritten by the copy. A document that is deleted while the copy runs may not have reached the new index yet, and the copy can still bring it there. Every deletion is therefore noted in a journal next to the new index. `switch` removes the noted documents from the new index if the live index does not hold them anymore, and moves the read alias only after that. A document that was published again in the meantime stays. ##### Guards - `start` refuses while a migration is already open. - `start` refuses when `--exclude` names every field, because there would be nothing to copy. > [!WARNING] > A context that still uses a plain index has no write alias yet. `start` creates one that holds the new index > alone. The plain index keeps serving the searches until `switch`, but it receives no writes from then on. ##### Excluded fields Every name given to `--exclude` has to exist in the document definition, otherwise `start` refuses. Those fields are empty in the new index. `dynamic-search:run` fills them, because it writes into both indexes while the migration is open. `switch` counts the documents without a value per excluded field. | Result | Follows | |------------------------------|-----------------------------------------| | no document has the field | refused, the run never happened | | some documents have no value | the number is shown and the switch asks | | every document has a value | it goes through | You name the excluded fields only once, in `start`. It stores them in the `_meta` of the new mapping, and `switch` and `status` read them from there. ### Mate With `open-dxp/mate-extension` installed, the tool `dynamic_search_opensearch_indices` shows the OpenSearch index of each context as the cluster sees it. It lists the hosts without credentials and whether a search finds an index. It also lists the indexes behind the read and the write alias, their document counts and an open migration. When the cluster cannot be read, it shows the error. The skill `mate-dynamic-search-opensearch` covers the field mapping and what to run after a change. *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Introduction ## Introduction to OpenDxp eCommerce his section is designed for developers and provides comprehensive information on utilizing the ecommerce bundle within OpenDxp, a powerful and flexible eCommerce solution. ### Quick Navigation Guide - **Getting Started**: Visit the [Getting Started](./01_Getting_Started/index.md) section for an introduction to the ecommerce bundle, including installation instructions. - **Bundles Overview**: Explore the [Bundles](./03_Bundles/index.md) section to understand the various bundles and their functionalities. - **User Documentation**: For configuration details and user-oriented instructions, see the [User Documentation](./02_User_Documentation/index.md). - **Developer Guide**: If you're looking to develop with the ecommerce bundle, check out our [Development](./03_Development/index.md) section for in-depth technical information. - **Genius**: See [Genius](./04_Genius.md) for what the AI assistant can answer about your shop data. Optional, and active on its own once Content Crafter is installed. --- ## Installation(Getting_Started) To install OpenDxp Ecommerce, ensure you have a running instance of OpenDxp on your system. ### Updating Ecommerce Bundle If you are looking to update the Ecommerce Bundle, read the [Update Guide](./02_Upgrade_Guide.md) instead. *** ### Initial Setup 1. Install with composer: `composer require open-dxp/ecommerce-bundle ^1.0` 2. Enable the bundle in `config/bundles.php` and the `EcommerceCoreBundle` to the list of Bundles to load: ```php return [ ... OpenDxp\Ecommerce\Bundle\CoreBundle\EcommerceCoreBundle::class => ['all' => true], OpenDxp\Ecommerce\Bundle\FrontendBundle\EcommerceFrontendBundle::class => ['all' => true], ]; ``` 3. To configure the Ecommerce Password Hasher, create or update the `config/packages/opendxp.yaml` and add: ```yaml opendxp: security: password_hasher_factories: OpenDxp\Model\DataObject\EcommerceUser: opendxp_ecommerce.security.user.password_hasher_factories ``` 4. Update `config/packages/security.yaml` to allow access to the backend. - Add the Ecommerce frontend parameter at the very top of your `security.yaml` (before `security`): ```yaml parameters: opendxp_ecommerce.security.frontend_regex: "^/(?!admin)[^/]*" security: ... ``` - Add the Authentication Provider. Find your existing `providers` entry and add the `opendxp_ecommerce_user` entry after the other(s): ```yaml providers: #... opendxp_ecommerce_user: id: OpenDxp\Ecommerce\Bundle\CoreBundle\Security\ObjectUserProvider ``` - Add the Firewall Config. Find your existing `firewalls` entry and add the `opendxp_ecommerce_frontend` entry after the other entries: ```yaml firewalls: opendxp_ecommerce_frontend: provider: opendxp_ecommerce_user pattern: '%opendxp_ecommerce.security.frontend_regex%' context: shop form_login: login_path: opendxp_ecommerce_login check_path: opendxp_ecommerce_login_check provider: opendxp_ecommerce_user failure_path: opendxp_ecommerce_login default_target_path: opendxp_ecommerce_index use_forward: false use_referer: true remember_me: secret: "%secret%" name: APP_OPENDXP_ECOMMERCE_REMEMBER_ME lifetime: 31536000 remember_me_parameter: _remember_me logout: path: opendxp_ecommerce_logout target: opendxp_ecommerce_login invalidate_session: false ``` - Add Access Control. Find your existing `access_control` entry and add the following lines after the existing ones: ```yaml access_control: - { path: "%opendxp_ecommerce.security.frontend_regex%/_partial", role: IS_AUTHENTICATED_ANONYMOUSLY, ips: [127.0.0.1, ::1] } - { path: "%opendxp_ecommerce.security.frontend_regex%/_partial", role: ROLE_NO_ACCESS } ``` 5. Run Install Command `php bin/console opendxp-ecommerce:install` 6. Optional: Install Demo Data `php bin/console opendxp-ecommerce:install:demo` ### Messenger OpenDxp Ecommerce also uses Symfony Messenger for async tasks like sending E-Mails or Processing DataObjects for the Index. Please run these two transports to process the data ```yaml bin/console messenger:consume opendxp_ecommerce_notification opendxp_ecommerce_index opendxp_ecommerce_variant --time-limit=300 ``` ### Payment OpenDxp Ecommerce uses Payum for Payment. Checkout Payum's Documentation on how to add payment providers. Payment providers are implemented as OpenDxp Bundles. They can be installed using composer. Here you can find all available payment modules via composer [Payum Documentation](https://payum.gitbook.io/payum) --- ## Architecture ### Core Values and Distinctions - **Components-Based Approach**: Offering modularity and flexibility. - **Unlimited Flexibility and Customization**: Easily tailored to specific needs. - **Developer-Friendly**: Incorporates the latest technologies. - **High-Quality Code**: Focus on robust and reliable coding practices. ## Architecture Overview The ecommerce bundle is built upon components and bundles. The CoreBundle and CoreComponent unify these elements into a cohesive eCommerce Suite for both B2B and B2C solutions. --- ## Upgrade Guide Please check the [changelog](../../CHANGELOG.md) for all changes. ### Upgrading via Migrations Run `bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Ecommerce\Bundle\CoreBundle\Migrations'` *** ### Versioning Strategy We follow a similar update approach as OpenDxp: **always update to the latest minor release before upgrading to the next major version.** > **Example:** If you are on `1.2.1` and want to update to `2.0`, you should first update to the latest `1.2.x` release, and only then upgrade to `2.0` or `2.1`. ### Migration Files To keep things tidy, we remove migrations between major versions. This means that if you are on `1.2.1` and you update to `2.0` directly, you might miss migrations. Always update to the latest Minor release version first before updating to the next Major! > ⚠️ **Always update to the latest minor release first before upgrading to the next major version!** After a major upgrade, old migrations may remain in your database. You can remove them manually if you want to keep your migrations table clean. #### Missing Migrations If you have already upgraded to a new major version and notice that some migrations from your previous version are missing, you can compare your current database structure against the expected schema by running: ```bash bin/console doctrine:schema:update --dump-sql ``` > ⚠️ **Please manually review all SQL statements before executing them.** --- ## Testing(Getting_Started) The bundle ships what you need to test your shop: factories for the data, the flows of a shopper, and page objects for the storefront. All of it lives under `OpenDxp\Ecommerce\Test`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Setup To use `toApplyTo`, register it once in your `tests/Pest.php`: ```php OpenDxp\Ecommerce\Test\Expectation\Rules::register(); ``` `Notifications::record()` needs a listener in the test configuration of your application: ```yaml services: OpenDxp\Ecommerce\Test\Notifications: tags: - { name: kernel.event_listener, event: opendxp_ecommerce.notification.pre_process_rules } ``` A test that lists products through an index, like a category page, needs that index. Put its definition into `tests/Fixtures/indexes/.json` and register `InstallIndexes` in `phpunit.xml.dist`, after `InstallDefinitions`: ```xml ``` ### Testing your shop A test builds the data it needs with factories and then acts as a shopper would: ```php use OpenDxp\Ecommerce\Test\Factory\CartPriceRuleFactory; use OpenDxp\Ecommerce\Test\Factory\ProductFactory; use OpenDxp\Ecommerce\Test\Rule\Action; use OpenDxp\Ecommerce\Test\Shop\Cart; use OpenDxp\Ecommerce\Test\Story\InstalledShop; it('takes the voucher off the cart', function () { Cart::add( ProductFactory::new() ->withPrice(10000) ->create(), ); CartPriceRuleFactory::new() ->withVoucherCodes('SAVE') ->withActions(Action::discountAmount(2000, InstalledShop::euro())) ->create(); Cart::redeem('SAVE'); expect(Cart::current()->getTotal(true))->toBe(8000); }); ``` Prices are in cents, as everywhere in the shop. The test uses the data that the installer of the bundle sets up: the default store, Austria and the euro. The story `InstalledShop` returns this data. A test therefore uses the existing euro and does not create one. ### Testing the storefront The page objects under `Test\Storefront` use the shop like a person does. They build on [`Page`](https://github.com/open-dxp/test-foundation#a-page-as-a-person-uses-it) of the test foundation. The page objects read products from their schema.org microdata. The templates of the bundle contain this markup. If you copied the templates into your project and kept the markup, the page objects work with your shop too. ```php use OpenDxp\Ecommerce\Test\Factory\CustomerFactory; use OpenDxp\Ecommerce\Test\Factory\ProductFactory; use OpenDxp\Ecommerce\Test\Storefront\Account; use OpenDxp\Ecommerce\Test\Storefront\CartItem; use OpenDxp\Ecommerce\Test\Storefront\CartPage; use OpenDxp\TestFoundation\Page; it('keeps the cart when the shopper logs in', function () { ProductFactory::new() ->active() ->withPrice(10000) ->create(['name' => 'T-Shirt']); CustomerFactory::new() ->withPassword('secret') ->create(['email' => 'anna@example.com']); $shop = Page::open('/en/shop/') ->clickWithin('Latest Products', 'T-Shirt') ->press('Add to Cart'); (new Account($shop)) ->logIn('anna@example.com', 'secret') ->click('Cart'); expect((new CartPage($shop))->items())->toEqual([new CartItem('T-Shirt', 1, '€100.00', '€100.00', null)]); }); ``` `Catalog`, `CartPage`, `CheckoutPage` and `Account` each know one part of the shop. Choosing a variant needs a [real browser](https://github.com/open-dxp/test-foundation#the-browser), because a script runs the choice. `VariantChooser` handles this. `choose()` clicks an attribute. `open()` clicks the last attribute and waits for the page of the variant. ### Notifications `Notifications::record()` collects the notification rules the shop fires during a test, for example the mail after an order: ```php $notifications = Notifications::record(); Cart::add($tShirt); Checkout::asCustomer($customer); Checkout::placeOrder(); expect($notifications->types())->toContain('order'); ``` ### Test API | Namespace | What it gives you | |---|---| | `Test\Factory` | A factory for each model: stores, products and their variants, categories, customers, wishlists, carriers, payment providers, taxes, currencies, countries, zones, filters, all price rules and carts. The states read like the shop, for example `ProductFactory::new()->withPrice(10000)->inCategories($shoes)->inStock(5)`. `OrderFactory` builds a stored cart that is not the cart of the current shopper, for example the cart a customer left on an earlier visit. | | `Test\Story` | `InstalledShop`, the default store and the countries and currencies the installer sets up, like `InstalledShop::euro()` or `InstalledShop::germany()`. | | `Test\Rule` | `Condition` and `Action` for every rule of the shop, and `Range` for quantity prices. A rule factory takes them in `withConditions()` and `withActions()`. | | `Test\Shop` | The flows of a shopper without a browser. `Shopper` picks the store, the country, the currency or the customer. `Cart` adds, changes and redeems. `Checkout` places the order. `Fulfillment` invoices and ships it. `Totals`, `ItemPrices` and `ProductPrices` read what the shop charges. | | `Test\Expectation` | The Pest expectation `toApplyTo`, which tells whether a rule applies to a cart or a product. | | `Test\Storefront` | Page objects for the storefront: `Catalog`, `CartPage`, `CheckoutPage`, `Account` and `VariantChooser`. | | `Test\Notifications` | `record()` collects the notification rules the shop fires during a test. | | `Test\PHPUnit` | `InstallIndexes` installs the index definitions in `tests/Fixtures/indexes` before the first test. | For example, a test checks `expect($carrier)->toApplyTo(Cart::current())`. ### The suite of this bundle - `tests/Feature` holds a folder for each part of the shop, like `Cart`, `Shipping` or `Order`. - `tests/Feature/Frontend` tests the storefront through the kernel. - `tests/Feature/Browser` drives a browser with Playwright, for the variants and the backend. These tests form the group `browser`. - `tests/Feature/Precision` runs in a shop that stores money with six decimal places. The indexes the tests use are fixtures in `tests/Fixtures/indexes`. `InstallIndexes` creates them once before the run. [Data object classes](https://github.com/open-dxp/test-foundation#data-object-classes) explains why. --- ## Getting Started This section provides a quick tutorial to get started with the ecommerce bundle. It covers the following topics: 1. **Installation of OpenDxp**: [Installation Guide](./00_Installation.md) 2. **Architecture Overview**: [Architecture Overview](./01_Architecture_Overview.md) 3. **Changelog**: [Changelog](../../CHANGELOG.md) 4. **Upgrade Guide**: [Upgrade Guide](02_Upgrade_Guide.md) 5. **UI Documentation**: [User Interface Documentation](../02_User_Documentation/index.md) 6. **Developer Documentation**: [Developer Documentation](../03_Development/index.md) 7. **Testing**: [Testing](./04_Tests.md) --- ## Stores Each installation is linked to a default store, typically associated with a OpenDxp site. Understanding how stores function is crucial for managing different aspects of your e-commerce platform. ![Stores](img/stores.png) ### Domain-Based Store Setup Default setup involves one store per domain. This means your main website domain corresponds to your default store. If your platform operates across multiple domains, you can assign a separate store to each. > **Tip:** For more information on managing multiple sites with OpenDxp, > see [OpenDxp Sites](https://opendxp.com/docs/platform/OpenDxp/MVC/Routing_and_URLs/Working_with_Sites/). ### Custom Store Locator In scenarios where you have a single site but require different stores (for example, `/de-at` for an Austrian store and `/de-de` for a German store), you'll need a custom store locator. Detailed guidance on creating a custom store locator is available in the development section. ### Setting Up Ecommerce Stores To configure stores: 1. Navigate to Ecommerce Menu -> "Stores". 2. You'll see the default store linked to your main domain. 3. To add a new store, click on the "Add" button and proceed with the setup. ### Utilizing Stores Effectively Stores can be leveraged in various ways depending on your business needs: #### Global Store - **Use Case**: Managing multiple currencies, countries, and tax calculations within a single store. - **Advantage**: Suitable for a unified product and price strategy across different regions. #### Country Store - **Use Case**: Setting up a store for each country, allowing for country-specific restrictions and customizations. - **Advantage**: Ideal for businesses targeting specific national markets. By understanding and utilizing the store configurations, you can tailor your e-commerce experience to meet diverse regional requirements and customer preferences. --- ## Settings Settings are categorized into individual shop settings and overarching system settings. These configurations are crucial for tailoring the functionality and behavior of your e-commerce store. ### Shop-Specific Settings Each store can have its unique settings. ![Settings](img/settings-shop.png) #### Base Settings - **Catalog-Mode**: Enable to view products without cart and checkout functionalities. - **Guest-Checkout**: Toggle the guest-checkout feature. #### Customer Service Settings - **Customer Email Documents**: Define email templates for customer communication. - **Contact Sales**: Set default contacts for sales-related inquiries. - **Contact Technology**: Set default contacts for technology-related inquiries. #### Stock Settings - **Default Stock Behaviour**: Set the general stock behavior for products. #### Tax Settings - **Validate VAT**: Toggle VAT number validation for European countries. - **Disable VAT for Base Country**: Enable or disable VAT-Free shopping for eligible customers in the base country. - **Taxation Address**: Determine which address is used for taxation purposes. #### Price Settings - **Prices are gross prices**: Specify whether prices entered include tax. #### Shipping Settings - **Free Shipping Options**: Set conditions for free shipping based on weight or cart value. - **Carrier Sort**: Define the sorting order for carriers. #### Product Settings - **Default Image**: Set a default image for products without images. - **Number of days as new**: Define the duration for marking a product as new. #### Category Settings - **Default Image**: Set a default image for categories without images. #### Invoice Settings - **Invoice Creation**: Set conditions for automatic invoice creation. - **Invoice Number Formatting**: Define prefixes and suffixes for order and invoice numbers. - **WKHTMLTOPDF Parameters**: Specify parameters for the WKHTMLTOPDF tool. #### Mail Settings - **Order Notification Emails**: Define admin email addresses for order notifications. - **Send OrderStates as BCC**: Choose whether to send order-state emails to admin-emails. #### Cart Settings - **Automatic Cart Cleanup**: Toggle the automatic cleanup of inactive and empty carts. --- ## Cart Price Rules Documentation The ecommerce bundle provides a versatile framework for offering discounts and promotions in your e-commerce store using the OpenDxp platform. Cart price rules can be customized based on a variety of factors, including cart subtotal, specific products, customer groups, and more. This documentation aims to guide you through the process of creating and managing cart price rules. ![Cart Price Rules](img/cart-pricerule.png) ### Crafting Your Cart Price Rules #### Available Actions Enhance your cart with these actions: - [Free Shipping](./06_Actions.md#free-shipping): Offer free shipping as an incentive. - [Gift Product](./06_Actions.md#gift-product): Add a complimentary product to the cart. - [Discount Amount](./06_Actions.md#discount-amount): Apply a fixed discount to the cart total. - [Discount Percent](./06_Actions.md#discount-percent): Reduce cart total by a percentage. #### Available Conditions Tailor your rules with these conditions: - [Customers](./07_Conditions.md#customers): Specific rules for individual customers. - [Customer Groups](./07_Conditions.md#customer-groups): Target different customer segments. - [Time Span](./07_Conditions.md#time-span): Rules active during selected time periods. - [Voucher](./07_Conditions.md#voucher): Implement rules with vouchers. - [Amount](./07_Conditions.md#amount): Rules based on cart amount. - [Countries](./07_Conditions.md#countries): Geographically targeted rules. - [Zones](./07_Conditions.md#zones): Rules for specific zones. - [Stores](./07_Conditions.md#stores): Store-specific rules. - [Currencies](./07_Conditions.md#currencies): Currency-based rules. - [Carriers](./07_Conditions.md#carriers): Rules based on shipping carriers. - [Nested Rules](./07_Conditions.md#nested-rules): Combine rules for complex scenarios. - [Products](./07_Conditions.md#products): Product-specific rules. - [Categories](./07_Conditions.md#categories): Category-specific rules. --- ## Product Price Rules Documentation The ecommerce bundle provides a dynamic and flexible approach to implementing discounts and special pricing for products in your e-commerce store, leveraging the capabilities of the OpenDxp platform. These product price rules can be tailored based on a variety of conditions, allowing you to apply them to specific products, categories, or customer groups. This guide will help you navigate the process of creating and managing these rules. ![Product Price Rules](img/product-pricerule.png) ### Available Actions Choose from a range of actions to apply as price rules: - [Price](./06_Actions.md#new-price): Set a new price for products. - [Discount Price](./06_Actions.md#discount-price): Apply a discounted price. - [Discount Amount](./06_Actions.md#discount-amount): Reduce by a specific amount. - [Discount Percent](./06_Actions.md#discount-percent): Apply a percentage-based discount. ### Available Conditions Set up price rules based on various conditions: - [Customers](./07_Conditions.md#customers): Target individual customers. - [Customer Groups](./07_Conditions.md#customer-groups): Target specific customer groups. - [Time Span](./07_Conditions.md#time-span): Apply rules within a certain time frame. - [Voucher](./07_Conditions.md#voucher): Use in conjunction with vouchers. - [Countries](./07_Conditions.md#countries): Target customers in specific countries. - [Zones](./07_Conditions.md#zones): Apply to certain geographical zones. - [Stores](./07_Conditions.md#stores): Specific to certain stores. - [Currencies](./07_Conditions.md#currencies): Apply based on currency. - [Nested Rules](./07_Conditions.md#nested-rules): Combine multiple rules. - [Products](./07_Conditions.md#products): Specific to certain products. - [Categories](./07_Conditions.md#categories): Apply to specific categories. --- ## Specific Price Rules Documentation The ecommerce bundle specific price rules enable a high level of flexibility in offering targeted discounts and special pricing for individual products or variants in your e-commerce store on the OpenDxp platform. These rules can be tailored based on customer groups, currencies, or countries, ensuring precise application of discounts. This guide will assist you in the creation and management of specific price rules. ![Specific Price Rules](img/specific-price-rules.png) ### Available Actions You can use a variety of actions for setting specific prices: - [Price](./06_Actions.md#new-price): Set a new, specific price. - [Discount Price](./06_Actions.md#discount-price): Implement a discounted price. - [Discount Amount](./06_Actions.md#discount-amount): Reduce the price by a fixed amount. - [Discount Percent](./06_Actions.md#discount-percent): Apply a percentage-based discount. ### Available Conditions Design rules based on a range of conditions: - [Customers](./07_Conditions.md#customers): Target individual customers. - [Customer Groups](./07_Conditions.md#customer-groups): Apply rules to specific customer groups. - [Time Span](./07_Conditions.md#time-span): Restrict rules to a specific time period. - [Countries](./07_Conditions.md#countries): Limit to customers in certain countries. - [Zones](./07_Conditions.md#zones): Apply within designated zones. - [Stores](./07_Conditions.md#stores): Specific to certain stores. - [Currencies](./07_Conditions.md#currencies): Target specific currencies. - [Nested Rules](./07_Conditions.md#nested-rules): Combine multiple rules for layered pricing strategies. --- ## Quantity Price Rules Documentation Quantity Price Rules offer a dynamic way to incentivize bulk purchases in your e-commerce store with the Ecommerce Bundle. These rules enable you to apply volume-based discounts to specific products, with tiered pricing that varies based on the quantity purchased. This guide will help you in effectively creating and managing quantity price rules. ![Quantity Price Rules](img/quantity-price-rules.png) ### Implementing Quantity Price Rules These rules can be applied under various conditions to best suit your sales strategy: - [Customers](./07_Conditions.md#customers): Target specific individual customers. - [Customer Groups](./07_Conditions.md#customer-groups): Apply rules to designated customer groups. - [Time Span](./07_Conditions.md#time-span): Restrict or activate rules within certain time frames. - [Countries](./07_Conditions.md#countries): Make rules applicable in selected countries. - [Zones](./07_Conditions.md#zones): Define rules for specific geographical zones. - [Stores](./07_Conditions.md#stores): Implement rules in certain stores. - [Currencies](./07_Conditions.md#currencies): Apply rules based on the currency used. - [Nested Rules](./07_Conditions.md#nested-rules): Create complex rules by combining multiple conditions. --- ## Vouchers > **Info**: In ecommerce bundle, vouchers are a type of Price Rule. > To utilize or generate Vouchers, you need to create a Cart Price Rule. ### How to Create Vouchers To create a voucher, start by making a new [cart price rule](./01_Cart_Price_Rules.md) and activate the "Is Voucher Rule" option. This will enable the "Voucher Codes" tab. ![Voucher](./img/vouchers-1.png) #### Voucher Condition For more control over Voucher handling, add the "Voucher" condition. ![Voucher](./img/vouchers-2.png) | Name | Description | |:--------------------------------|:------------------------------------------------| | Max. Usage per Code | Define the maximum usage for each voucher code. | | Allow only one Voucher per Code | Limit to one voucher per cart if checked. | #### Voucher Codes Manage your voucher codes in the "Voucher Codes" tab, where you can also export codes to a CSV file. ![Voucher](./img/vouchers-3.png) > For global statistics about vouchers, refer to the [voucher report](../09_Reports/09_Vouchers.md). | Name | Description | |:--------------|:--------------------------------------------------------| | Code | The generated voucher code. | | Creation Date | The date when the voucher was created. | | Used | Indicates if the voucher has been used (true or false). | | Uses | The number of times each code has been used. | | Action | Option to delete codes not in use. | #### Creating Voucher Codes There are two methods for generating voucher codes: ##### Single Voucher Code Create an individual voucher code. Note that duplicate strings are not allowed and will trigger an error message. ##### Voucher Codes Generator For bulk generation, use the Voucher Codes Generator: | Name | Description | |:---------------------------|:-------------------------------------------------------------| | Amount | Number of voucher codes to generate. | | Length | Length of each voucher code. | | Format | Format of the code: `Alphanumeric`, `Alphabetic`, `Numeric`. | | Prefix | A prefix for each code, e.g., `SHOP-`. | | Suffix | A suffix for each code, e.g., `-SHOP`. | | Hyphens every X characters | Inserts a dash (`-`) after every X characters. | --- ## Price Rule Actions Get a brief overview of all the available *Price Rule Actions*. ### Free Shipping > **Available for**: Cart Price Rules This action allows free shipping when added to a cart price rule. ### Gift Product > **Available for**: Cart Price Rules Add a gift to the customer's cart with this action. ##### Options | Name | Description | |:-------------|:-----------------------------------------------------------| | Gift Product | The product must be a registered Ecommerce product object. | ### Discount Amount > **Available for**: Cart Price Rules, Specific Product Price, Product Price Apply a fixed amount of discount. ##### Options | Name | Description | |:-----------------|:------------------------------------------------------------------------------------------| | Amount | Define the discount amount. | | Gross | Check if the amount includes VAT. | | Apply On | Choose `Total` or `Subtotal` as the upper limit. Only available in cart rules. | | Include Shipping | Check if the rest of the amount goes to the shipping costs. Only available in cart rules. | | Currency | Specify the currency for the amount. | `Apply On` sets the upper limit of the discount: - `Total`: The discount never exceeds what the cart or the cart item costs at this point. - `Subtotal`: The discount never exceeds the price of the products after the earlier price rules. Both limits are the same unless the project adds its own adjustments before the price rules run. A cart rule takes the amount off the products first. With `Include Shipping`, the part of the amount that exceeds the products is taken off the shipping costs. The VAT on shipping is then calculated from the reduced shipping costs. ### Discount Percent > **Available for**: Cart Price Rules, Specific Product Price, Product Price Set a percentage-based discount. ##### Options | Name | Description | |:-----------------|:------------------------------------------------------------------------------------------| | Percent | Define the discount percentage. | | Include Shipping | Check if the percentage also applies to the shipping costs. Only available in cart rules. | ### Surcharge Amount > **Available for**: Cart Price Rules Add a fixed amount to the cart, for example a small-order surcharge. ##### Options | Name | Description | |:----------------|:--------------------------------------------------------------------| | Amount | Define the surcharge amount. | | Gross | Check if the amount includes VAT. | | Currency | Specify the currency for the amount. | | Tax Calculation | Choose how the surcharge is taxed. See below. | | Tax Rule | Select the tax rule group for **based on tax rule**. | ### Surcharge Percent > **Available for**: Cart Price Rules Add a percentage of the product subtotal to the cart. A store with gross prices takes the percentage of the gross subtotal. ##### Options | Name | Description | |:----------------|:--------------------------------------------------------------------| | Percent | Define the surcharge percentage. | | Tax Calculation | Choose how the surcharge is taxed. See below. | | Tax Rule | Select the tax rule group for **based on tax rule**. | #### Taxes on a Surcharge A surcharge is split across the products in the cart. **Tax Calculation** decides how each share is taxed: - **based on cart items** is the default. Each share takes the tax rate of its product. Use it when the surcharge belongs to the goods. This is the usual case. - **based on tax rule** taxes every share with the selected tax rule group. Use it when the surcharge is a service of its own with a fixed rate, for example a small-order fee that your tax adviser treats as a separate service. [Shipping costs](../05_Shipping/01_Carriers.md) and [payment fees](../../03_Development/10_Payment/01_Payment_Provider.md#taxes-on-the-payment-fee) offer the same choice. ### New Price > **Available for**: Specific Product Price, Product Price Set a new price for a product. > **Note**: This is used as the new sale price in the frontend, without special discount labelling. For a highlighted > discount price, use the `Discount Price` action. ##### Options | Name | Description | |:---------|:----------------------| | Price | Set the new price. | | Currency | Specify the currency. | ### Discount Price > **Available for**: Specific Product Price, Product Price Define a discounted price for a product. ##### Options | Name | Description | |:---------|:--------------------------| | Price | Set the discounted price. | | Currency | Specify the currency. | --- ## Price Rules Conditions Get a brief overview of all the available *Price Rule Conditions*. ### Customers > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Target specific customers with the price rule. ##### Options | Name | Description | |:----------|:---------------------------------------------| | Customers | Select one or more Ecommerce Customer Objects | ### Customer Groups > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Target specific customer groups. ##### Options | Name | Description | |:-------|:---------------------------------------------------| | Groups | Select one or more Ecommerce Customer Group Objects | ### Time Span > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Set the validity period for the price rule. ##### Options | Name | Description | |:----------|:----------------| | Date From | Start Date/Time | | Date To | End Date/Time | ### Voucher > **Available for**: Cart Price Rules Configure Voucher conditions. See the [Voucher Section](./05_Vouchers.md) for more details. ##### Options | Name | Description | |:--------------------------------|:------------------------------------------| | Max. Usage per Code | Maximum usage for each voucher code. | | Allow only one Voucher per Code | Limit to one voucher per cart if checked. | ### Amount > **Available for**: Cart Price Rules Define the cart amount range for rule application. ##### Options | Name | Description | |:-----------|:---------------------| | Min Amount | Minimum cart amount. | | Max Amount | Maximum cart amount. | ### Countries > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Link the rule to specific countries. ##### Options | Name | Description | |:----------|:----------------------------------| | Countries | Select one or multiple Countries. | ### Zones > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Associate the rule with specific zones. ##### Options | Name | Description | |:------|:------------------------------| | Zones | Select one or multiple Zones. | ### Stores > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Bind the rule to specific stores. ##### Options | Name | Description | |:-------|:-------------------------------| | Stores | Select one or multiple Stores. | ### Currencies > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Define applicable currencies for the rule. ##### Options | Name | Description | |:-----------|:-----------------------------------| | Currencies | Select one or multiple Currencies. | ### Carriers > **Available for**: Cart Price Rules Set carrier-based conditions for the rule. ##### Options | Name | Description | |:---------|:---------------------------------| | Carriers | Select one or multiple Carriers. | ### Nested Rules > **Available for**: Cart Price Rules, Specific Product Prices, Product Price Create complex conditions with `AND`, `OR`, and `NOT` operators. ##### Options | Name | Description | |:---------|:------------------------------| | Operator | Choose `AND`, `OR`, or `NOT`. | ### Products > **Available for**: Cart Price Rules, Product Price Apply the rule to specific products. ##### Options | Name | Description | |:---------|:--------------------------------------------| | Products | Select one or more Ecommerce Product Objects | ### Categories > **Available for**: Cart Price Rules, Product Price Target products within specific categories. ##### Options | Name | Description | |:-----------|:---------------------------------------------| | Categories | Select one or more Ecommerce Category Objects | --- ## Price Rules The ecommerce bundle Price Rules are powerful tools for price calculation. This section provides a detailed overview of how price calculation works. ### Types of Price Rules There are three types of Price Rules: ##### 1. Cart Price Rules Apply a Price Rule to the customer's cart. ##### 2. Product Price Rules Apply a Price Rule globally to products. ##### 3. Specific Product Prices Apply Price Rules to specific products. ### Global Priority The order of priority for price rules is as follows: 1. **Product Price Rules** are applied first. 2. **Specific Product Prices** are applied second. #### Example 1: - Given: Product A with a price of 100,- - Product Price Rule for Product A: New Price 50,- - Specific Price Rule for Product A: New Price 20,- - Resulting Price: 20,- #### Example 2: - Given: Product A with a price of 100,- - Product Price Rule for Product A: Discount Percentage 50% - Specific Price Rule for Product A: New Price 50,- - Resulting Price: 25,- ### Specific Price Priority It's possible to add multiple Specific Price Rules per Product. The priority can be adjusted using the priority number field. ### Automatic Rule Availability Checker Rules with time-span elements included on the root level will be disabled automatically if they're outdated. Read more about automation [here](../10_Automation/index.md). ### More Information - [Cart Price Rules](./01_Cart_Price_Rules.md) - [Product Price Rules](./02_Product_Price_Rules.md) - [Specific Product Prices](./03_Specific_Price_Rules.md) - [Vouchers](./05_Vouchers.md) - [Available Actions](./06_Actions.md) - [Available Conditions](./07_Conditions.md) --- ## Country Configuration Each country is defined by a set of attributes that determine how it interacts with your store. Here's what each attribute represents: - **Name**: The official name of the country. - **ISO-Code**: The standardized international code for the country. - **Active**: This flag determines if customers from this country can make purchases from your store. - **Use Store Default Currency**: When checked, transactions from this country will use your store's default currency. - **Currency**: The specific currency associated with the country. - **Zone**: The geographical or commercial zone to which the country belongs. - **Stores**: Specifies which of your stores the country settings apply to. ![Countries](img/countries.png) --- ## State Configuration A State (or County) is defined by several key attributes essential for regional management within your store. These attributes include: - **Name**: The name of the state or county. - **ISO Code**: A unique code that follows international standards for identifying the state. - **Active**: Indicates whether the state is active for transactions and operations in your store. - **Country**: The country to which the state belongs. ![States](img/states.png) --- ## Zone Configuration A 'Zone' functions as a group of countries and is defined by a set of attributes. Zones are primarily used for configuring Price Rules and Shipping Rules. Here's an overview of the attributes for a Zone: - **Name**: The designated name of the zone. - **Active**: Indicates whether the zone is active and can be used in the store's operational settings. ![Zones](img/zones.png) --- ## Currencies The configuration of a currency involves several key attributes essential for international transactions and currency management. - **Name**: The official name of the currency. - **ISO Code**: The standardized international three-letter code representing the currency. - **Numeric ISO Code**: The numerical code assigned to the currency, as per international standards. - **Symbol**: The graphical symbol or abbreviation used to denote the currency (e.g., $ for USD, € for EUR). ![Currencies](img/currencies.png) ### Exchange Rates The Ecommerce Bundle supports automated calculation of exchange rates, simplifying the process of maintaining current and accurate currency information. This feature is particularly useful for stores that handle transactions in multiple currencies and need to ensure consistent and fair pricing across different regions. > **Important**: Regular updates of exchange rates are necessary for accurate currency conversion. --- ## Taxes Configuration Tax rates are crucial for accurately calculating the applicable taxes on products and services. Each tax rate is defined by the following attributes: - **Localized Name**: The name of the tax rate as it appears in the shopping cart and on invoices. It can be localized to match the language preferences of different regions. - **Rate**: The percentage value of the tax, such as 20%. - **Active**: Indicates whether the tax rate is currently active and applicable. ![Taxes](img/taxes.png) --- ## Tax Rules Tax Rules are instrumental in determining the appropriate Tax Rate based on the customer's country or state. These rules ensure that the correct tax is applied to products during transactions. ### Key Components of a Tax Rule Each Tax Rule is characterized by several important attributes: - **Name**: The identifier for the Tax Rule. - **Active**: Indicates whether the Tax Rule is currently in use. - **Stores**: Specifies which stores can apply this Tax Rule. - **Rules**: Defines the relationship between Countries/States and Tax Rates, and the handling of scenarios where multiple Tax Rates are applicable. ![Tax Rules](img/taxrules.png) --- ## Localization The ecommerce bundle provides comprehensive options for localization, ensuring that your e-commerce store can cater to a global audience with region-specific settings. Below are the key components of the ecommerce localization system, each linked to detailed documentation: - **Countries**: Configure countries. [Learn More](./01_Countries.md) - **States**: Manage state or county settings within each country. [Learn More](./02_States.md) - **Zones**: Group countries or regions for targeted rules and pricing. [Learn More](./03_Zones.md) - **Currencies**: Set up and manage multiple currencies for international transactions. [Learn More](./04_Currencies.md) - **Taxes**: Define tax rates and rules applicable to different regions. [Learn More](./05_Taxes.md) - **Tax Rules**: Determine how taxes are applied based on customer location. [Learn More](./06_TaxRules.md) --- ## Carriers Carriers play a pivotal role in the shipping process, enabling you to integrate various shipping providers like UPS, FedEx, or DHL. This guide outlines the steps for creating and managing carriers within the environment on the OpenDxp platform. ### Creating a Carrier Follow these steps to set up a new carrier: 1. **Access Admin Interface**: Log in to the OpenDxp admin interface. 2. **Navigate to Shipping**: Go to the "Ecommerce" -> "Shipping" tab and select "Carriers." 3. **Add New Carrier**: Click on "Add new" to initiate a new carrier setup. 4. **Configure Carrier**: Enter the carrier's name and adjust the settings as required. ### Carrier Configuration Options Each carrier can be customized with various options: - **Name**: Assign a descriptive name (e.g., UPS, FedEx, or DHL). - **Tracking URL**: Provide a URL for tracking shipments. - **Tax Calculation**: Choose how the shipping costs are taxed. **based on tax rule** uses the tax rule group of the carrier. **based on cart items** splits the shipping costs across the tax rates of the products in the cart. Payment fees use the same setting, see [Taxes on the Payment Fee](../../03_Development/10_Payment/01_Payment_Provider.md#taxes-on-the-payment-fee). - **Tax Rule Group**: Select the tax rule group for the shipping costs when Tax Calculation is **based on tax rule**. This requires the prior setup of an appropriate tax rule group. - **Shipping Rules**: Define shipping costs and conditions. You can link multiple shipping rules with different priorities to determine the final shipping cost. ### Summary Carriers are essential for offering diverse and customized shipping options. Through careful configuration of carriers and their associated shipping rules, you can provide a seamless and efficient shipping experience, catering to various customer preferences and logistics requirements in your e-commerce store. --- ## Shipping Rules Shipping Rules are a key feature, enabling you to define shipping costs through customizable rules. These rules can be based on various conditions such as weight, price, dimensions, and shipping destination. ### Overview Shipping rules are composed of conditions and actions: - **Conditions**: Determine the applicability of a rule. - **Actions**: Define the adjustments to shipping costs when a rule is applied. You can create a variety of rules, each tailored to specific shipping scenarios. ### Creating Shipping Rules 1. **Access Shipping Rules**: Navigate to the "Shipping" tab and select "Shipping Rules." 2. **Add New Rule**: Click "Add new" to start creating a rule. 3. **Configure Rule**: Name the rule and adjust settings according to your requirements. ### Configuring Conditions Conditions are criteria that must be met for a shipping rule to apply. The Ecommerce Bundle supports multiple conditions per rule, including: - **Weight**: Based on the total weight of the order. - **Price**: Based on the total price of the order. - **Dimension**: Based on order dimensions (length, width, height). - **Quantity**: Based on the total quantity of items. - **Countries**: Targeting specific shipping destinations. - **Zones**: Focusing on particular geographic zones. #### Setting Up a Condition - Click "Add Condition" in the rule's "Conditions" section. - Select a condition type and configure its parameters. Example: For orders over 10kg, add a weight condition with a minimum weight of 10kg. ### Configuring Actions Actions determine how shipping costs are modified when a rule is triggered. It allows for multiple actions per rule, such as: - **Discount Amount**: A fixed discount on shipping costs. - **Discount Percentage**: A percentage discount on shipping costs. - **Add Amount**: An additional fixed amount to the shipping costs. - **Add Percentage**: An extra percentage to the shipping costs. #### Setting Up an Action - Click "Add Action" in the rule's "Actions" section. - Choose an action type and set the necessary parameters. Example: For a 20% shipping discount, add a discount percentage action and set it to 20%. ### Summary Shipping Rules provide a versatile and robust mechanism to manage shipping costs in your e-commerce store. By leveraging various conditions and actions, you can tailor shipping costs to meet diverse requirements and offer precise shipping estimates to your customers. --- ## Shipping The ecommerce bundle provides a comprehensive shipping management system that allows you to define and configure various aspects of shipping, such as carriers, shipping rules, and carrier services. * [Carriers](./01_Carriers.md) * [Shipping Rules](./02_Shipping_Rules.md) --- ## Cart ### Inventory Check on Cart Addition When a customer adds an item to their cart, the ecommerce bundle verifies product stock availability. In cases where stock is insufficient, the customer is informed through a form error. ### Auto-Removal of Disabled or Deleted Products Should a product be disabled or deleted from the backend, the ecommerce bundle will automatically remove it from all active carts. Customers with modified carts will receive a form error notification in the frontend. ### Handling Abandoned Carts By default, carts are not deleted. This approach allows for: - Analysis of abandoned cart statistics. - Development of customized follow-up strategies, such as email notifications to customers. For managing abandoned carts, including their removal, refer to the [expire cart command](../../03_Development/06_Order/20_Commands.md) in the development section. --- ## Orders ### Utilizing Grid View for Order Management The order management leverages OpenDxp's grid view, providing a robust and customizable interface. #### Default Column Configuration To access the default column setup: 1. Click on "Column configuration" located on the right side. 2. Select "Order Overview" from the options. 3. To set this as your preferred view, click the "Column configuration" button again and choose "Set as favorite". ### Customizing Filters in Grid View For project-specific needs, the Ecommerce Bundle allows the addition of custom filter definitions: - These customizations require configuration through a PHP service. - Detailed instructions and guidelines can be found [here](../../03_Development/06_Order/14_Backend_Management/01_OrderList_Filter.md). ### Implementing Bulk Actions in Grid View The ecommerce bundle supports the application of custom bulk actions for selected orders: - Similar to filters, these actions are set up via a PHP service. - For more information on creating and applying these actions, visit [here](../../03_Development/06_Order/14_Backend_Management/02_OrderList_Action.md). --- ## Order Detail The Order Detail section provides comprehensive information about individual orders, including their states, price overview, and other relevant details. ### State and Price Overview For an in-depth understanding of the order workflow process, refer to the [Order Workflow documentation](./03_Order_Workflow.md). #### Key Information - **Order Store**: Indicates the store where the order was placed. - **Total Order Amount**: The complete amount for the order. #### Order States ##### Main State The primary state summarizing the overall status of the order. | Name | Description | |:----------|:----------------------------| | new | Newly placed order. | | confirmed | Order successfully created. | | cancelled | Order has been cancelled. | | complete | Order is complete. | ##### Payment State Reflects the overall payment status of the order. | Name | Description | |:-------------------|:-------------------------------| | new | New payment initiated. | | awaiting_payment | Awaiting payment confirmation. | | partially_paid | Partial payment received. | | paid | Full payment received. | | cancelled | Payment cancelled. | | partially_refunded | Partial refund processed. | | refunded | Full refund processed. | ##### Shipment State Indicates the shipping status of the order. | Name | Description | |:------------------|:----------------------------| | new | New shipment initiated. | | cancelled | Shipment cancelled. | | partially_shipped | Partial shipment completed. | | shipped | Full shipment completed. | ##### Invoice State Summarizes the invoicing status of the order. | Name | Description | |:-------------------|:-----------------------------| | new | New invoice created. | | cancelled | Invoice cancelled. | | partially_invoiced | Partial invoicing completed. | | invoiced | Full invoicing completed. | ### Carrier and Payment Provider Information - **Currency**: The currency used for the order. - **Total Weight**: The cumulative weight of all order items. - **Carrier**: The shipping provider used. - **Total Amount**: The total amount for the order. ### Additional Sections - **Order History**: Tracks changes in order states. - **Payments**: Details about payment transactions. - **Shipments**: Information on shipment progress. - **Invoices**: Records of invoicing. - **Mail Correspondence**: Log of emails related to the order. - **Customer**: Customer details. - **Comments**: Any comments or notes on the order. - **Products**: List of products included in the order. --- ## Order Workflow The ecommerce bundle provides a comprehensive workflow system for managing various states of orders, payments, shipments, and invoices. For a technical overview, refer to the [State Management documentation](../../03_Development/06_Order/16_State_Management/index.md). ### Changing States States can be changed for Orders, Payments, Shipments, and Invoices. If a transition is available, a colored state button will be displayed. Click this button to change the state. ### Order Completion A order is considered complete when the payment state reaches `paid` and the shipment state reaches `shipped`. If you wish to include the invoice state `invoiced` in the order completion criteria, this can be enabled via the config like this: ```yml ## app/config/config.yml parameters: opendxp_ecommerce.workflow.include_invoice_state_to_complete_order: true ``` ##### Order Cancellation Orders are rarely cancelled, except under specific circumstances: - **Front-End Review**: After a customer cancels their payment, they reach a review page where they can restart the payment process or cancel the order and restore their cart. - **Back-End Review**: Similar to the front-end, but the customer cannot restore a cart since the order was created in the back-end. More details on the cancellation process can be found [here](../../03_Development/06_Order/16_State_Management/03_Things_To_Know.md). ### Payment Workflow #### Creating a Payment Create a payment using the green button in the top-right corner. Payment state changes are typically managed by the frontend payment gateway. #### Workflow Rules - Payments enter the `new` state upon creation. - Payments can be cancelled as long as they are in the `new` or `processing` state. - Once a payment reaches the `completed` state, it can only be refunded. > **Attention**: The refund process is not yet implemented! ### Shipment Workflow #### Creating a Shipment Create a shipment using the green button in the top-right corner, provided there are enough shippable items. #### Workflow Rules - Shipments enter the `ready` state after creation. - Shipments can be cancelled as long as they are in the `ready` state. - Once the `ship` state is triggered, a shipment cannot be cancelled anymore. ### Invoice Workflow #### Creating an Invoice Create an invoice using the green button in the top-right corner, if there are enough invoiceable items. #### Workflow Rules - Invoices enter the `ready` state after creation. - Invoices can be cancelled as long as they are in the `ready` state. **Note**: Cancelling an invoice is not a refund action. You are allowed to create another invoice after cancelling the previous one. - Once the `complete` state is triggered, an invoice cannot be cancelled anymore, which means the invoice has been finally captured. After that, a refund process must be initiated. > **Attention**: The refund process is not yet implemented! --- ## Order Comments The ecommerce bundle features a straightforward comment interface, enabling you to add notes to any order. This functionality facilitates efficient communication and record-keeping within order management. ![Comment](img/comment2.png) ![Comment](img/comment1.png) ### Adding and Managing Comments You can easily append simple notes or comments to an order through this interface. These comments can serve as internal reminders or clarifications regarding the order's processing or specific customer requests. ### Sharing Comments with Customers For enhanced customer interaction, it allows you to share these comments directly with the customer. To do this: - Check the option "Submit Comment to Customer" when adding a comment. > **Important Note:** Ensure you have a valid Notification Rule set up to successfully send comments to > customers. This rule is necessary for the system to deliver comment notifications appropriately. --- ## Order * [Orders](./01_Orders.md) * [Order Detail](./02_Order_Detail.md) * [Order Workflow](./03_Order_Workflow.md) * [Order Comments](./04_Order_Comments.md) --- ## Attributes & Variants Every product has an "Attributes & Variants" field in its edit view. It lets you assign attribute groups to a product and, for variants, set their concrete attribute values. ### Two Grids The field shows two grids, always visible: - **Variant Attribute Groups**: groups that define variants, like Color or Size. - **Attribute Groups**: groups that only add characteristic information. They do not create variants. Whether a group belongs to the top or the bottom grid depends on the "Variant Attribute" checkbox on the attribute group itself. ### Attribute Set Choosing an attribute set fills the bottom grid (Attribute Groups) with that set's groups. The top grid does not depend on the attribute set. ### Adding Groups Drag an attribute group from the object tree onto a grid to add it. Only groups matching the grid's type can be dropped there. - Variant group cannot be dropped into the bottom grid, and vice versa. - Groups already in a grid cannot be added again. ### Removing Groups Each row has a remove button. On a variant product, the top grid cannot be edited this way, see below. ### Object vs. Variant - On the main product (type "object"), the top grid defines which groups are used to build variants. You can add and remove groups, but you cannot set attribute values here. - On a variant (type "variant"), the top grid is inherited from the main product and fixed. You cannot add or remove groups, but you set the actual attribute value for each group here. The bottom grid works the same way on both object and variant. ### Creating Attributes Use the create button on a row to add a new attribute value to that group. If the group has no attribute yet, you are first asked to choose the attribute kind: - **Value**: a simple text value, like "XL" or "Cotton". - **Color**: a text value plus a color, picked with a color picker. Once a group has an attribute, further attributes created for it use the same kind. --- ## Products At the heart of any e-commerce store built on the OpenDxp platform are its products. The ecommerce bundle offers a robust and versatile system for product management, designed to accommodate the diverse needs of modern e-commerce platforms. ### Key Features of the Product Management The product management system is equipped with a range of features to effectively handle various aspects of your e-commerce products: - **Product Variants**: Manage different variations of a product, such as size, color, or material, providing customers with a range of options. - **Attributes and Specifications**: Define and manage a wide array of product attributes to provide detailed information to your customers. - **Product Images and Media**: Easily upload and manage product images and other media, enhancing the visual appeal and informational value of your products. - **Pricing and Stock Management**: Set up flexible pricing strategies and keep track of inventory levels to ensure efficient stock management. - **Categories and Collections**: Organize products into categories and collections for easier navigation and discovery by customers. #### Streamlined Product Handling The Ecommerce Bundle’s intuitive interface allows for seamless management of products, ensuring that adding, updating, or removing products is straightforward and efficient. #### Customization and Integration With its flexible architecture, the ecommerce bundle enables extensive customization to meet specific business requirements and seamless integration with other modules and third-party systems. Embracing these powerful features and capabilities will enhance your e-commerce store’s functionality, providing an enriched shopping experience for your customers and streamlined operations for your business. ### Variants The ecommerce bundle incorporates the Variant Bundle to effectively manage product variants. This bundle offers the tools and features needed to handle different versions of a product, such as size, color, or material variations. For detailed information on using the Variant Bundle, refer to the [Variant Bundle documentation](./../../03_Bundles/Variant_Bundle.md). For how to assign attribute groups and manage variants on a product, see [Attributes & Variants](./01_Attributes_And_Variants.md). ### Categories Categories play a crucial role by helping you organize and structure the products in your e-commerce store on the OpenDxp platform. They enable the creation of a hierarchical navigation system, enhancing the shopping experience by making it easy for customers to browse and find products. #### Key Benefits of Using Categories - **Improved Navigation**: Categories facilitate a user-friendly and intuitive way for customers to navigate through different sections of your store. - **Better Organization**: They help in systematically categorizing products, making it easier for both store managers and customers to locate specific items. - **Enhanced User Experience**: A well-structured category system contributes to a seamless and enjoyable shopping experience, encouraging customers to explore more products. --- ## Inventory Managing inventory is a critical aspect that involves understanding several key business logics to ensure accurate stock tracking and order fulfillment. ### Product Inventory Configuration Each product includes a "Stock" tab for inventory management. Here's a breakdown of the available configurations: #### Configuration Options | Name | Description | |:-----------|:-------------------------------------------------------------------------------------| | Is Tracked | Indicates whether the product's stock is tracked. | | On Hand | The current available quantity of the product. | | On Hold | The quantity currently reserved (locked) for orders. Do not modify unless necessary. | ##### Is Tracked To activate inventory tracking for a product, enable the "Is Tracked" setting. With this enabled, the product becomes unorderable in the frontend if the stock is insufficient. > **Note**: Inventory tracking is active only when "Is Tracked" is enabled. Without it, the product is considered always > available, regardless of stock levels. ##### On Hand This setting determines the available stock for each product. The stock decreases automatically with each successful order. ##### On Hold This setting requires further explanation: - After checkout completion, ordered items shift from "On Hand" to "On Hold" until payment is complete. - If an unpaid order is cancelled, the "On Hold" quantity returns to "On Hand". - If the order payment status changes to `paid`, the "On Hold" quantity is permanently deducted. ### Cart and Checkout Process During the checkout process, if a product becomes out of stock, it will be removed from the customer's cart, and a form error will be displayed. This ensures that customers are only able to purchase items that are available in stock. --- ## Sales Report Overview The Sales Report provides a comprehensive analysis of sales data, enabling you to track and understand sales trends over different time periods. ![Sales Report](img/sales.png) ### Report Format The Sales Report is presented in a Cartesian Chart format. | Type | Has Pagination | |:----------------|:---------------| | Cartesian Chart | No | ### Filters for Tailored Analysis Customize your sales data view using a variety of filters: | Name | Description | |:---------|:--------------------------------------------------------------------| | Store | Filter sales by specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the sales filter period. | | To | End date for the sales filter period. | | Group By | Group sales data by `Day`, `Month`, `Year`. | ### Chart Data Fields The sales chart includes the following data fields: | Name | Description | |:-----|:--------------------| | Y | Total Sales Amount. | | X | Date of Sales. | --- ## Sales Report Overview(Reports) The Sales Report provides a comprehensive analysis of sales data, enabling you to track and understand sales trends over different time periods. ![Sales Report](img/sales.png) ### Report Format The Sales Report is presented in a Cartesian Chart format. | Type | Has Pagination | |:----------------|:---------------| | Cartesian Chart | No | ### Filters for Tailored Analysis Customize your sales data view using a variety of filters: | Name | Description | |:---------|:--------------------------------------------------------------------| | Store | Filter sales by specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the sales filter period. | | To | End date for the sales filter period. | | Group By | Group sales data by `Day`, `Month`, `Year`. | ### Chart Data Fields The sales chart includes the following data fields: | Name | Description | |:-----|:--------------------| | Y | Total Sales Amount. | | X | Date of Sales. | --- ## Abandoned Carts Report The ecommerce bundle Abandoned Carts Report is an essential tool for analyzing carts that were not converted into orders. This report helps identify potential issues in the sales process and opportunities for re-engaging customers. ### Report Format The report is presented in a list format with pagination enabled. | Type | Has Pagination | |:-----|:---------------| | List | Yes | ### Applying Filters for Targeted Insights Customize the report using various filters to focus on specific data: | Name | Description | |:-------|:--------------------------------------------------------------------| | Store | Filter carts by Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | ### Filter the Columns A column with a filter offers **Filter** in the menu of its header. The filter applies to every page of the report and to the CSV export. | Column | Filter | |:------------------|:---------------------------| | Customer Name | Contains the text. | | Email | Contains the text. | | Selected Payment | Contains the text. | | Creation Date | Before, after or on a day. | | Modification Date | Before, after or on a day. | ### Key Grid Fields The report includes several crucial fields for detailed analysis: | Name | Description | |:------------------|:---------------------------------------------------| | Customer Name | Name of the customer (if available). | | Email | Customer's email address (if available). | | Selected Payment | Name of the payment method chosen. | | Creation Date | Date when the cart was created. | | Modification Date | Date when the cart was last modified. | | Items in Cart | Total number of items in the cart. | | Action | Option to open the cart object for further review. | --- ## Products Report The ecommerce bundle Products Report provides a comprehensive view of product performance, including sales, quantities, and profits. This report is instrumental for analyzing product trends and making informed inventory decisions. ![Products Report](img/products.png) ### Report Format The Products Report is presented in a list format with pagination. | Type | Has Pagination | |:-----|:---------------| | List | Yes | ### Customizing the Report with Filters Enhance your analysis by applying various filters: | Name | Description | |:--------------|:--------------------------------------------------------------------| | Store | Filter data by specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | | Product Types | Group data by `Main Products`, `Variants`, `Container Products`. | ### Understanding Product Types Differentiate products based on their type for targeted analysis: | Name | Description | |:-------------------|:---------------------------------------------------------------------------------------------------------------| | Main Products | Displays only products without variant inclusion. | | Variants | Shows only variant product types. | | Container Products | Summarizes products and their child-products. Note: Ignored in report if the main opendxp objects are deleted. | ### Filter the Columns A column with a filter offers **Filter** in the menu of its header. The filter applies to every page of the report and to the CSV export. | Column | Filter | |:-------|:-------------------| | Name | Contains the text. | ### Key Grid Fields Analyze key metrics with the following data fields: | Name | Description | |:------------|:----------------------------------------| | Name | Product name. | | Order Count | Total number of orders for the product. | | Quantity | Total quantity sold. | | Sale Price | Average sale price. | | Sales | Total sales amount. | | Profit | Total profit amount. | --- ## Categories Report The ecommerce bundle Categories Report offers valuable insights into the performance of different product categories within your e-commerce store. This data can be instrumental in making informed decisions about inventory and marketing strategies. ![Categories Report](img/categories.png) ### Report Format The Categories Report is displayed in a list format. | Type | Has Pagination | |:-----|:---------------| | List | Yes | ### Applying Filters for Detailed Analysis Customize the report for targeted insights using the following filters: | Name | Description | |:-------|:--------------------------------------------------------------------| | Store | Filter results by a specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | ### Filter the Columns A column with a filter offers **Filter** in the menu of its header. The filter applies to every page of the report and to the CSV export. | Column | Filter | |:-------|:-------------------| | Name | Contains the text. | ### Key Grid Fields The report includes several essential fields for comprehensive category analysis: | Name | Description | |:------------|:-------------------------------------------------| | Name | The name of the product category. | | Order Count | Total number of orders in the category. | | Quantity | Total quantity of products sold in the category. | | Sales | Total sales generated from the category. | | Profit | Total profit from the category. | --- ## Customers Report The ecommerce bundle Customers Report provides an in-depth view of customer interactions within your e-commerce store. It offers valuable insights into customer purchasing patterns, helping to tailor marketing and sales strategies effectively. ![Customers Report](img/customers.png) ### Report Format This report is formatted as a list, providing a detailed breakdown of customer activities. | Type | Has Pagination | |:-----|:---------------| | List | Yes | ### Customizing the Report with Filters Enhance your analysis with various filters to focus on specific customer segments or timeframes: | Name | Description | |:-------|:--------------------------------------------------------------------| | Store | Filter data by specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | ### Filter the Columns A column with a filter offers **Filter** in the menu of its header. The filter applies to every page of the report and to the CSV export. | Column | Filter | |:-------|:-------------------| | Email | Contains the text. | ### Key Grid Fields The report includes critical fields to understand customer engagement: | Name | Description | |:------------|:-----------------------------------------------| | Name | The name of the customer. | | Order Count | Total number of orders placed by the customer. | | Sales | Total sales attributed to the customer. | --- ## Carrier Distribution Report The ecommerce bundle Carrier Distribution Report provides a visual representation of how different carriers are utilized for shipping in your e-commerce store. This report, presented as a pie chart, is crucial for analyzing shipping preferences and efficiency. ![Carrier Distribution](img/carriers.png) ### Report Format The report is displayed as a pie chart, offering a clear visual breakdown of carrier usage. | Type | Has Pagination | |:----------|:---------------| | Pie Chart | No | ### Customizing the Report with Filters Apply various filters to refine your data analysis: | Name | Description | |:-------|:--------------------------------------------------------------------| | Store | Filter by specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | ### Chart Fields The Carrier Distribution Report includes the following field: - **Carrier Distribution**: This field visualizes the proportion of each carrier used for shipping orders, helping you to understand which carriers are most popular or efficient for your store. --- ## Payment Distribution Report The ecommerce bundle Payment Distribution Report offers a detailed analysis of the various payment methods used in your e-commerce store. Presented as a pie chart, this report is essential for understanding customer payment preferences and optimizing your payment options. ![Payment Distribution](img/payments.png) ### Report Format This report utilizes a pie chart format to provide a visual overview of payment distribution. | Type | Has Pagination | |:----------|:---------------| | Pie Chart | No | ### Applying Filters for Detailed Insights Customize your report using the following filters to focus on specific data points: | Name | Description | |:-------|:--------------------------------------------------------------------| | Store | Filter data by specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | ### Chart Field The Payment Distribution Report includes the following field: - **Payment Provider Distribution**: This field visualizes the usage frequency of each payment provider, enabling you to assess which payment methods are most popular among your customers. --- ## Voucher Report The ecommerce bundle Voucher Report provides an analysis of voucher usage within your e-commerce store. This report is particularly useful for tracking the effectiveness of promotional campaigns and understanding customer response to vouchers. The report lists every use of a code in a completed order. It also lists the codes nobody has used yet. Set the filter **Used** to no to see them. A code without a use has no order. The period applies to its creation date, and the code shows in every store. A code in an order that is not completed yet shows in neither list. ### Report Format The Voucher Report is presented in a list format with pagination available. | Type | Has Pagination | |:-----|:---------------| | List | Yes | ### Customizing the Report with Filters Use the following filters to refine and target your analysis: | Name | Description | |:-------|:--------------------------------------------------------------------| | Store | Filter vouchers used in a specific Store. | | Period | Sets From and To to the current or the previous day, month or year. | | From | Start date for the filter period. | | To | End date for the filter period. | ### Filter the Columns A column with a filter offers **Filter** in the menu of its header. The filter applies to every page of the report and to the CSV export. | Column | Filter | |:--------------|:---------------------------------------| | Code | Contains the text. | | Price Rule | Contains the text. | | Used | Yes or no. The report starts with yes. | | Creation Date | Before, after or on a day. | | Applied Date | Before, after or on a day. | ### Key Grid Fields The report includes essential data fields for a comprehensive overview of voucher use: | Name | Description | |:--------------|:---------------------------------------------------| | Code | The voucher code that was applied. | | Discount | The amount of discount provided by the voucher. | | Price Rule | The name of the price rule applied by the voucher. | | Used | The code was used in a completed order. | | Creation Date | The date when the code was created. | | Applied Date | The date when the voucher was applied. | --- ## Reporting Tools Overview The ecommerce bundle provides a comprehensive suite of reporting tools designed to deliver valuable insights into various facets of your e-commerce store. These reports are crucial for understanding sales trends, customer behaviors, and other key metrics, helping you make informed decisions to drive your business forward. ### Explore Our Range of Reports Each report is tailored to offer specific insights: - **Sales Reports**: Delve into your store's sales performance, including revenue and order volumes, to gauge your business's success. [Access Sales Report](./01_Sales.md) - **Cart/Order Conversion**: Analyze the rate at which carts are converted into completed orders, a vital metric for understanding the effectiveness of your sales funnel. [Access Cart/Order Conversion Report](./02_Carts.md) - **Abandoned Carts**: Identify and understand the carts that weren’t converted into orders, providing insights into potential sales recovery strategies. [Access Abandoned Carts Report](./03_Abandoned_Carts.md) - **Product Reports**: Evaluate individual product performances within your catalog, helping you make data-driven inventory decisions. [Access Product Report](./04_Products.md) - **Category Reports**: Gain insights into category performances, essential for strategic product placement and marketing. [Access Category Report](./05_Categories.md) - **Customer Analysis**: Dive deep into customer behaviors and purchasing patterns to tailor your marketing and sales approaches. [Access Customer Analysis Report](./06_Customers.md) - **Carrier Distribution**: Review how different carriers are used for order deliveries, an important aspect of your shipping strategy. [Access Carrier Distribution Report](./07_Carrier_Distribution.md) - **Payment Distribution**: Understand the distribution and popularity of various payment methods among your customers. [Access Payment Distribution Report](./08_Payment_Distribution.md) - **Voucher Usage**: Monitor how vouchers are used and their impact on sales, vital for optimizing promotional strategies. [Access Voucher Report](./09_Vouchers.md) --- ## Automation The ecommerce bundle implements several automated mechanisms to streamline operations and maintain order within the system. These automations are executed daily via maintenance jobs. ### Order Cancellation Automation **Execution Time**: Once per day. #### Default Behavior The ecommerce bundle automatically cancels orders that are older than 20 days. #### Customizing Order Expiration To change the expiration period for orders, modify the configuration as follows: ```yml opendxp_ecommerce_storage_list: list: order: expiration: params: order: days: 30 ``` ### Expired Carts Cleanup **Execution Time**: Once per day. > **Note**: By default, cart cleanup is disabled (set to 0 days). Expired carts are not removed unless you enable and configure this feature. Set a specific timeframe after which inactive carts should be cleaned up to manage cart data effectively. ##### Enabling Cart Cleanup To activate and set a specific time frame for cart cleanup: ```yml opendxp_ecommerce_storage_list: list: order: expiration: params: cart: days: 20 params: anonymous: true customer: false ``` ### Expired Wishlists **Execution Time**: Once per day. > **Note**: Wishlist expiration is disabled by default. Similar to carts, wishlists also do not expire by default. You can enable this feature and set an expiration period for wishlists, helping to maintain a clean and current wishlist database. ##### Setting Wishlist Expiration To enable and configure the expiration for wishlists: ```yml opendxp_ecommerce_storage_list: list: wishlist: expiration: service: ~ # use default service enabled: true days: 14 params: anonymous: true customer: false ``` ### Expired Rules Management **Execution Time**: Once per day. The ecommerce bundle automatically disables rules that are beyond their valid time-span. This feature helps in keeping your rule set relevant and up-to-date. For more complex rule availability logic, the ecommerce bundle provides an event (`opendxp_ecommerce.rule.availability_check`) that allows for custom implementation of rule availability criteria. --- ## User Documentation Welcome to the User Documentation! This section provides a comprehensive guide to get you started, covering various key aspects of the platform. ### Quick Start Topics Explore these topics to familiarize yourself with the platform: 1. **[Stores](./01_Stores.md)**: Understanding the store setup. 2. **[Settings](./02_Settings.md)**: Configuration options for each store and system-wide settings. 3. **Price Rules**: Comprehensive guide to pricing strategies. - [Cart Price Rules](./03_Price_Rules/01_Cart_Price_Rules.md) - [Product Price Rules](./03_Price_Rules/02_Product_Price_Rules.md) - [Specific Product Price](./03_Price_Rules/03_Specific_Price_Rules.md) - [Vouchers](./03_Price_Rules/05_Vouchers.md) - [Available Actions](./03_Price_Rules/06_Actions.md) - [Available Conditions](./03_Price_Rules/07_Conditions.md) 4. **Localization**: Managing geographical aspects. - [Countries](./04_Localization/01_Countries.md) - [States](./04_Localization/02_States.md) - [Zones](./04_Localization/03_Zones.md) - [Currencies](./04_Localization/04_Currencies.md) - [Taxes](./04_Localization/05_Taxes.md) - [Tax Rules](./04_Localization/06_TaxRules.md) 5. **Shipping**: Configuring shipping options and rules. - [Carriers](./05_Shipping/01_Carriers.md) - [Shipping Rules](./05_Shipping/02_Shipping_Rules.md) 6. **[Cart](./06_Cart/index.md)**: Overview of cart functionalities. 7. **Order Management**: Detailed guide on order processing. - [Orders](./06_Order/01_Orders.md) - [Order Detail](./06_Order/02_Order_Detail.md) - [Order Workflow](./06_Order/03_Order_Workflow.md) - [Order Comments](./06_Order/04_Order_Comments.md) 8. **Catalog Management**: Managing your product catalog. - [Products](./07_Catalog/index.md) - [Attributes & Variants](./07_Catalog/01_Attributes_And_Variants.md) - [Categories](./07_Catalog/index.md) 9. **[Inventory](./08_Inventory/index.md)**: Inventory management insights. 10. **Reports**: Understanding reporting tools for data analysis. - [Sales](./09_Reports/01_Sales.md) - [Cart/Order Conversion](./09_Reports/02_Carts.md) - [Abandoned Carts](./09_Reports/03_Abandoned_Carts.md) - [Products](./09_Reports/04_Products.md) - [Categories](./09_Reports/05_Categories.md) - [Customers](./09_Reports/06_Customers.md) - [Carrier Distribution](./09_Reports/07_Carrier_Distribution.md) - [Payment Distribution](./09_Reports/08_Payment_Distribution.md) - [Vouchers](./09_Reports/09_Vouchers.md) 11. **[Automation](./10_Automation/index.md)**: Automated processes. --- ## Class Definition Patch Bundle The Ecommerce Class Definition Patch Bundle provides a convenient way to modify class definitions from other bundles. This is particularly useful for adding new properties to existing classes through a configuration setup. #### Adding required bundles to kernel You need to enable the bundle inside the kernel. ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\ClassDefinitionPatchBundle\EcommerceClassDefinitionPatchBundle(), ]); } ``` ### Usage #### Configuration for Patching To patch a OpenDxp class definition, add a configuration like the following: ```yaml opendxp_ecommerce_class_definition_patch: patches: EcommerceCompany: interface: 'blub' fields: name2: before: 'addresses' definition: fieldtype: input title: opendxp_ecommerce.company.name2 ``` #### Patching Ecommerce Classes For patching Ecommerce classes, leverage the parameters provided by Ecommerce: ```yaml opendxp_ecommerce_class_definition_patch: patches: "%opendxp_ecommerce.model.order.opendxp_class_name%": fields: total2: before: 'total' definition: fieldtype: ecommerceMoney title: Total 2 ``` #### Preview Changes Before applying the changes, preview them using: ```bash bin/console opendxp-ecommerce:patch:classes --dump ``` #### Applying the Patch Once you're satisfied with the preview, apply the patch: ```bash bin/console opendxp-ecommerce:patch:classes --force ``` > **Note** that the patch modifies your local definitions, which should be part of your version control (e.g., git > repository). After applying the patch, commit these changes. There's no need to run the patch command during > deployment. --- ## Index Bundle The Index Bundle integrates the Index Component into Symfony and Doctrine, offering tools for indexing OpenDxp models, managing filters, and creating conditions. It includes ListingServices and FilterServices. #### Integrating with the Kernel Enable the bundle in the kernel by updating the `AppKernel.php` file: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\IndexBundle\EcommerceIndexBundle(), ]); } ``` #### Updating the Database Schema Update the database schema with the following command: ```bash $ php bin/console doctrine:schema:update --force ``` ### Usage Guidelines #### Creating an Indexable Class Define a class that implements the `OpenDxp\Ecommerce\Component\Index\Model\IndexableInterface` interface: ```php getName($language); } } ``` Ensure that `App\Model\MyOpenDxpDataObject` is set as your parent class for your OpenDxp Data-Object. #### Retrieving Listings from an Index Fetch a listing from an index: ```php $filter = $this->get('opendxp_ecommerce.repository.filter')->find(1); // Get Filter by ID 1 $filteredList = $this->get('opendxp_ecommerce.factory.filter.list')->createList($filter, $request->request); $filteredList->setVariantMode(ListingInterface::VARIANT_MODE_HIDE); $filteredList->setCategory($category); $this->get('opendxp_ecommerce.filter.processor')->processConditions($filter, $filteredList, $request->query); $filteredList->load(); ``` This Index Bundle is crucial for managing indexing and filtering of data, ensuring efficient data handling and retrieval. --- ## Menu Bundle The Menu Bundle simplifies the creation of OpenDxp menus based on permissions, enhancing the user interface and navigation experience. #### Integrating with the Kernel Enable the bundle in the kernel by updating the `AppKernel.php` file: ```php addBundles([ new \Ecommerce\Bundle\MenuBundle\EcommerceMenuBundle(), ]); } ``` ### Usage Instructions #### Creating a New Menu 1. **Define a Menu Builder Class**: Create a new class for your menu, such as `MyMenuBuilder`. ```php addChild('my-menu-item') ->setLabel('my-menu-item') ->setAttribute('permission', 'my_menu_item') ->setAttribute('iconCls', 'opendxp_icon_delete'); } } ``` 2. **Register the Menu Builder**: Register your menu builder class in the Symfony container. ```yml App\Ecommerce\Menu\MyMenuBuilder: tags: - { name: opendxp_ecommerce.menu, type: my_menu, menu: my_menu } ``` #### Implementing the ExtJs JavaScript Part 1. **Add a JavaScript File**: In your bundle's `Bundle.php` file, add the JavaScript file to the `jsPaths` array: `/admin/ecommerce/opendxp_ecommerce.my_menu/menu.js` 2. **Instantiate the Menu**: In your `startup.js` file, instantiate the menu: ```javascript new opendxp_ecommerce.menu.opendxp_ecommerce.my_menu(); document.addEventListener(opendxp_ecommerce.events.menu.open, (e) => { var item = e.detail.item; if (item.id === 'my-menu-item') { alert('My Menu Item has been clicked'); } }); ``` --- ## Messenger Bundle The Messenger Bundle provides a user-friendly interface to view queued Messenger tasks across different queues. ![Messenger](img/messenger.png) #### Integrating with the Kernel To enable the bundle, update the `AppKernel.php` file: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\MessengerBundle\EcommerceMessengerBundle(), ]); } ``` --- ## Money Bundle The Money Bundle provides an efficient way to handle and format monetary values. #### Integrating with the Kernel To enable the bundle, update the `AppKernel.php` file: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\MoneyBundle\EcommerceMoneyBundle(), ]); } ``` ### Usage Instructions The Money Bundle introduces a core extension in OpenDxp, allowing you to store currency values as integers. This approach ensures precision and consistency in financial data handling. #### Twig Extension for Money Formatting The bundle includes a Twig extension for formatting money values: ```twig {{ value|opendxp_ecommerce_format_money('€', 'de'); }} ``` This extension allows for easy and flexible formatting of monetary values within your templates, enhancing the display and readability of prices and financial figures. --- ## OpenDxp Bundle #### Activating Bundle You need to enable the bundle inside the kernel or with the OpenDxp Extension Manager. ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\OpenDxpBundle\EcommerceOpenDxpBundle() ]); } ``` ### Usage The EcommerceOpenDxpBundle integrates the OpenDxp Component into Symfony automatically registers a lot of services for you. #### JS/CSS Resource Loading With OpenDxp, every bundle needs to take care about loading static assets themselve. OpenDxpBundle helps you out here, follow these steps to use it: - Create a DependencyInjection Extension class like: ```php processConfiguration($this->getConfiguration([], $container), $config); $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); $this->registerOpenDxpResources('opendxp_ecommerce', $config['opendxp_admin'], $container); } } ``` - Create a DependencyInjection Configuration class like: ```php root('app'); $this->addOpenDxpResourcesSection($rootNode); return $treeBuilder; } /** * @param ArrayNodeDefinition $node */ private function addOpenDxpResourcesSection(ArrayNodeDefinition $node) { $node->children() ->arrayNode('opendxp_admin') ->addDefaultsIfNotSet() ->children() ->arrayNode('js') ->addDefaultsIfNotSet() ->ignoreExtraKeys(false) ->children() ->scalarNode('test')->defaultValue('/bundles/app/opendxp/js/test.js')->end() ->end() ->end() ->arrayNode('css') ->addDefaultsIfNotSet() ->ignoreExtraKeys(false) ->children() ->scalarNode('test')->defaultValue('/bundles/app/opendxp/css/opendxp.css')->end() ->end() ->end() ->end() ->end() ->end(); } } ``` - That's it, OpenDxpBundle now takes care about loading your resources and also bundles them in non DEV-Mode. #### DataObject Extensions ##### Serialized Data This extension allows you to store SerializedData inside a OpenDxp DataObject. #### Slug The bundle ships a slug generator for products and categories. To use it, enter one of these services as the slug generator of the `slug` field and enable *Fill an empty slug* and *Extend duplicate slugs*: | Service | Slug | |----------------------------------------------|-----------------------------| | `@opendxp_ecommerce.slug_generator.product` | `/de_CH/product/green-bike` | | `@opendxp_ecommerce.slug_generator.category` | `/de_CH/category/bikes` | The generator stays inactive until a class uses it. To use another path segment, register a service of `OpenDxp\Ecommerce\Component\OpenDxp\Slug\SlugGenerator` with another `$pathSegment`. To change more, extend the class and override `getPrefix()`, `getDefaultSlug()` or `formatSlug()`. In a project with the I18nBundle, override `getPrefix()` and build the prefix from the language tree and the route translations of the zone, see [Data Object Routes](https://docs.opendxp.io/docs/bundles/i18n/DataObjectRoutes). How slug generators work is described in [Slug Generator](https://docs.opendxp.io/docs/core-framework/Objects/Object_Classes/Data_Types/Others/#slug-generator). ##### Slug Generation of the Bundle This feature is deprecated since 1.2.1 and will be removed in 2.0. Use `SlugGenerator` on the `slug` field instead. The bundle generates the slugs of every class that implements `OpenDxp\Ecommerce\Component\OpenDxp\Slug\SluggableInterface`, unless its `slug` field has a slug generator. Existing slugs are never changed, so removing the feature does not change any published URL. To keep the format of these slugs for new objects, enter `OpenDxp\Ecommerce\Component\OpenDxp\Slug\SlugGenerator` itself as the slug generator. Without a path segment, it builds slugs like `/de_CH/green-bike`, as the bundle does. The bundle appends `-1`, `-2` and so on to a slug that another object already uses. Enable *Extend duplicate slugs* on the `slug` field to keep this behaviour. Without it, the object is not saved. Use `OpenDxp\Ecommerce\Component\OpenDxp\Event\SlugGenerationEvent` to adjust a slug the bundle generates: ```php 'onGenerate', ]; } public function onGenerate(SlugGenerationEvent $event): void { $event->setSlug($event->getSlug() . '-bar'); } } ``` ##### OpenDxp Link Generation OpenDxp includes a versatile Link Generator feature, designed for creating links associated with OpenDxp Objects. The ecommerce bundle enhances this capability by introducing support for generating links for Sluggable entities. To leverage this extended functionality, modify the class definitions `Link Generator` setting to use `@OpenDxp\Ecommerce\Component\OpenDxp\Slug\SluggableLinkGenerator`. #### Data Object Features ##### Class Converter and Data Migrate Class converter is a small utility, which lets you migrate all Data from one class to another. Usage: ```php true, 'parentClass' => 'AppBundle\Model\MyProduct' ]; //Copies $currentClassName Definition to $newClassName //$options can overwrite some properties like parentClass Migrate::migrateClass($currentClassName, $newClassName, $options); //This function migrates all data from $currentClassName to $newClassName //It uses SQL Commands to increase performance of migration Migrate::migrateData($currentClassName, $newClassName); ``` ##### Class Installer Class Installer helps you importing Classes/FieldCollections/ObjectBricks into OpenDxp based of a JSON Definition: ```php use OpenDxp\Ecommerce\Component\OpenDxp\ClassInstaller; $installer = new ClassInstaller(); // For Bricks use $installer->createBrick($pathToJson, $brickName); // For Classes use $installer->createClass($pathToJson, $className, $updateExistingClass); // For FieldCollections use $installer->createFieldCollection($pathToJson, $fcName); ``` ##### Class/Brick/Field Collection Updater Definition Updaters help you in migrating your OpenDxp Class/Bricks or Field Collection Definitions to be properly migrated from Release to Release. To update a OpenDxp class use it like this: ```php use OpenDxp\Ecommerce\Component\OpenDxp\DataObject\ClassUpdate; $classUpdater = new ClassUpdate('Product'); //Your JSON Definition from OpenDxp $payment = [ 'fieldtype' => 'ecommerceSerializedData', 'phpdocType' => 'array', 'allowedTypes' => [ ], 'maxItems' => 1, 'name' => 'paymentSettings', 'title' => 'Payment Settings', 'tooltip' => '', 'mandatory' => false, 'noteditable' => true, 'index' => false, 'locked' => null, 'style' => '', 'permissions' => null, 'datatype' => 'data', 'columnType' => null, 'queryColumnType' => null, 'relationType' => false, 'invisible' => false, 'visibleGridView' => false, 'visibleSearch' => false, ]; //Check if field exists if (!$classUpdater->hasField('paymentSettings')) { //If not insert field after a specific field and save the definition $classUpdater->insertFieldAfter('paymentProvider', $payment); $classUpdater->save(); } ``` Thats it, the same works for FieldCollections with the class `OpenDxp\Ecommerce\Component\OpenDxp\DataObject\FieldCollectionDefinitionUpdate` and for Bricks with the class `OpenDxp\Ecommerce\Component\OpenDxp\DataObject\BrickDefinitionUpdate` ##### Inheritance Helper Inhertiance Helper is a small little but very useful helper class to enable OpenDxp inheritance only with a closure function like this: ```php use OpenDxp\Ecommerce\Component\OpenDxp\DataObject\InheritanceHelper; $inheritedValue = InheritanceHelper::useInheritedValues(function() use($object) { return $object->getValueInherited(); }, true); ``` ##### Version Helper Version Helper is a small little but very useful helper class to disabling or enablind OpenDxp Versioning. ```php use OpenDxp\Ecommerce\Component\OpenDxp\DataObject\VersionHelper; VersionHelper::useVersioning(function() use($object) { //Object will be saved without creating a new Version $object->save(); }, false); ``` ##### Unpublished Helper Unpublsihed Helper is a small little but very useful helper class to get unpublished objects in OpenDxp Frontend. ```php use OpenDxp\Ecommerce\Component\OpenDxp\DataObject\UnpublishedHelper; $allProducts = UnpublishedHelper::hideUnpublished(function() use($object) { //Will return all products, even the unpbulished ones return $object->getProducts(); }, false); ``` #### Expression Language Features The ecommerce bundle adds some features to the Symfony Expression language like: - OpenDxpLanguageProvider: to get OpenDxp Objects, Assets or Documents inside a Expression Language Query #### Migration Features ##### OpenDxp Shared Translations Helps you to install new Shared Translations during Migration: ```php use OpenDxp\Ecommerce\Component\OpenDxp\Migration\SharedTranslation; SharedTranslation::add('key', 'en', 'value'); ``` --- ## Optimistic Entity Lock Bundle The Optimistic Entity Lock bundle is a specialized package, designed for handling optimistic entity locking on the OpenDxp platform. This bundle is crucial for preventing editing conflicts when multiple users attempt to modify the same entity simultaneously. #### Integrating with the Kernel Enable the bundle in the kernel by updating the `AppKernel.php` file: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\OptimisticEntityLockBundle\EcommerceOptimisticEntityLockBundle(), ]); } ``` ### Usage Instructions #### Implementing the Interface Your OpenDxp DataObject Class needs to implement the `OpenDxp\Ecommerce\Bundle\OptimisticEntityLockBundle\Model\OptimisticLockedInterface`. #### Adding the Field to Class Definition Add the field `optimisticLockVersion` to your OpenDxp Class Definition. This field is pivotal for the locking mechanism. #### Functionality Once implemented, every time the DataObject is saved, the bundle checks and increments the version number. If the version differs from the last saved state (indicating another user has saved changes), an exception is thrown, preventing overwrite conflicts. This bundle ensures data integrity and consistency in scenarios where concurrent editing might occur, safeguarding your e-commerce data against inadvertent overwrites. --- ## Adding a New Custom Doctrine Entity ### Step 1: Create Translatable Entity First, create your Entity Class. In this case, we create a Translatable Entity. #### CustomEntityInterface Create `CustomEntityInterface.php` in the `AppBundle/Model` directory. ```php initializeTranslationsCollection(); } // Getters and Setters } ``` #### CustomEntityTranslationInterface Create `CustomEntityTranslationInterface.php` in the `AppBundle/Model` directory. ```php root('your_bundle'); $this->addModelsSection($rootNode); return $treeBuilder; } private function addModelsSection(ArrayNodeDefinition $node) { $node ->children() ->arrayNode('opendxp') ->addDefaultsIfNotSet() ->children() ->arrayNode('opendxp_entity') ->addDefaultsIfNotSet() ->children() ->variableNode('OpenDxpEntity')->end() ->arrayNode('options') ->scalarNode('path')->defaultValue('path/within/opendxp')->end() ->scalarNode('permission')->defaultValue('opendxp_entity')->cannotBeOverwritten()->end() ->addDefaultsIfNotSet() ->children() ->scalarNode('model')->defaultValue('OpenDxp\Model\Object\OpenDxpEntity')->cannotBeEmpty()->end() ->scalarNode('interface')->defaultValue(OpenDxpEntity::class)->cannotBeEmpty()->end() ->scalarNode('factory')->defaultValue(OpenDxpFactory::class)->cannotBeEmpty()->end() ->scalarNode('repository')->cannotBeEmpty()->end() ->scalarNode('admin_controller')->cannotBeEmpty()->end() ->scalarNode('install_file')->defaultValue('@YourBundle/Resources/install/opendxp/classes/OpenDxpEntity.json')->end() ->scalarNode('type')->defaultValue(EcommerceResourceBundle::OPENDXP_MODEL_TYPE_OBJECT)->cannotBeOverwritten(true)->end() ->end() ->end() ->end() ->end() ->end() ->end() ->end() ; } } ``` #### YourBundleExtension.php Create YourBundleExtension.php in the same directory. ```php processConfiguration($this->getConfiguration([], $container), $config); $this->registerOpenDxpModels('app', $config['opendxp'], $container); } } ``` ### Step 4: Use Your OpenDxp Entity You can either use OpenDxp Listing Classes or the automatically generated Factory/Repository Classes. #### Using OpenDxp Listing Classes ```php $list = new OpenDxp\Model\Object\OpenDxpEntity\Listing(); ``` #### Using Factory/Repository Classes ```php $opendxpEntityObject = $container->get('app.repository.opendxp_entity')->findBy($id); $list = $container->get('app.repository.opendxp_entity')->getList(); ``` --- ## OpenDxp for Projects using AsOpenDxpModel Attribute ### Step 1: Add a New OpenDxp Class in OpenDxp 1. Create a new class in OpenDxp. 2. Add a Parent Class to your OpenDxp Entity. ### Step 2: Create Parent Class #### OpenDxpEntity Create OpenDxpEntity.php in the App/Model directory. ```php get('app.repository.opendxp_entity')->findBy($id); $list = $container->get('app.repository.opendxp_entity')->getList(); ``` --- ## OpenDxp for Projects using Resource Config ### Step 1: Add a New OpenDxp Class in OpenDxp 1. Create a new class in OpenDxp. 2. Add a Parent Class to your OpenDxp Entity. ### Step 2: Create Parent Class #### OpenDxpEntity Create OpenDxpEntity.php in the App/Model directory. ```php get('app.repository.opendxp_entity')->findBy($id); $list = $container->get('app.repository.opendxp_entity')->getList(); ``` --- ## Resource Bundle The Resource Bundle is a central component, handling the creation, reading, updating, and deleting (CRUD) of ecommerce models. It manages Doctrine ORM mappings, translations, routing, event dispatching, serialization, and CRUD operations. This bundle also facilitates the installation of various OpenDxp definitions. #### Integrating with the Kernel Enable the bundle in the kernel by updating the `AppKernel.php` file: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\ResourceBundle\EcommerceResourceBundle(), ]); } ``` ### Adding Custom Doctrine Entities To create custom entities or extend existing ecommerce doctrine entities: ##### 1. Enable Doctrine ORM ```yaml # app/config/config.yml doctrine: orm: mappings: App: is_bundle: false dir: '%kernel.project_dir%/src/Entity' prefix: 'App\Entity' alias: App ``` ##### 2. Create Your Entity ```php # src/Entity/CustomEntity.php addBundles([ new \OpenDxp\Ecommerce\Bundle\SequenceBundle\EcommerceSequenceBundle(), ]); } ``` #### Updating the Database Schema After installation, update the database schema with the following command: ```bash $ php bin/console doctrine:schema:update --force ``` ### Usage The Sequence Bundle integrates the Sequence Component into Symfony and Doctrine, providing essential tools for generating sequences within your application. #### Doctrine Entities The primary entity used in the Sequence Bundle is `Sequence`. #### Generating a New Sequence To generate a new sequence, use the sequence generator service: ```php $container->get('opendxp_ecommerce.sequence.generator')->getNextSequenceForType('my_sequence'); ``` --- ## Storage List Bundle The Storage List Bundle assists in managing lists and collections of objects, such as carts, wishlists, or compare lists,. ### Usage The bundle requires three models to function effectively: 1. **Storage List** - Represents the collection. Implement the [`StorageListInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/StorageList/Model/StorageListInterface.php). 2. **Storage Item** - The item within the collection, which can store additional information, such as prices for a cart. Implement the [`StorageListItemInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/StorageList/Model/StorageListItemInterface.php). 3. **Storage Product** - The actual product being stored inside the item. Implement the [`StorageListProductInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/StorageList/Model/StorageListProductInterface.php). The ecommerce bundle provides basic implementations of [`Storage List`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/StorageList/Model/StorageList.php) and [`Storage Item`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/StorageList/Model/StorageItem.php). You will need to implement the StorageListProduct yourself. #### Mutating Lists Use the [`Storage List Modifier`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/StorageList/StorageListModifier.php) to create and persist lists. #### Example: Basic Session-Based Wishlist Let's create a session-based wishlist with the following components: - Factory class for the Wishlist - Factory class for the Wishlist Item - StorageListManager (repository-like) - StoreListModifier The ecommerce bundle provides basic classes for these components: ```php use Symfony\Component\HttpFoundation\Session\Session; use OpenDxp\Ecommerce\Component\StorageList\Model\StorageList; use OpenDxp\Ecommerce\Component\StorageList\Model\StorageListItem; use OpenDxp\Ecommerce\Component\Resource\Factory\Factory; use OpenDxp\Ecommerce\Component\StorageList\SessionStorageManager; use OpenDxp\Ecommerce\Component\StorageList\SessionStorageListModifier; $session = new Session(); $session->start(); $wishlistFactory = new Factory(StorageList::class); $wishlistItemFactory = new Factory(StorageListItem::class); $wishlistManager = new SessionStorageManager($session, 'wishlist', $wishlistFactory); $wishlistModifier = new SessionStorageListModifier($wishlistItemFactory, $wishlistManager); // Adding data to our List $list = $wishlistManager->getStorageList(); $product = $productRepository->find(1); // Assumes StorageListProductInterface implementation $listItem = $wishlistItemFactory->createNew(); $listItem->setProduct($product); $listItem->setQuantity($quantity); // Adding a Product $wishlistModifier->addToList($list, $listItem); // Removing a Product $wishlistModifier->removeFromList($list, $listItem); ``` This bundle simplifies the management of various storage lists, enhancing the functionality and user experience of your e-commerce platform. --- ## Theme Bundle The Theme Bundle offers a flexible and extensible approach to managing multiple themes within a OpenDxp installation. #### Integrating with the Kernel Enable the bundle in the kernel by updating the `AppKernel.php` file: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\ThemeBundle\EcommerceThemeBundle(), ]); } ``` ### Configuration By default, no Theme Resolver is enabled. You can enable one or more resolvers in your configuration: ```yaml opendxp_ecommerce_theme: default_resolvers: opendxp_site: true opendxp_document_property: true ``` #### Theme Resolvers 1. **OpenDxp Site**: Resolves the theme based on the key of the root document of a OpenDxp site. For example, if the site's root document is named "demo," it looks for a theme with the same name. 2. **OpenDxp Document Property**: Resolves the theme based on a document property of the site, specifically the property named "theme." #### Implementing Custom Resolvers You can create custom resolvers: ```php addBundles([ new \OpenDxp\Ecommerce\Bundle\VariantBundle\EcommerceVariantBundle(), ]); } ``` ### Abstract OpenDxp supports variants but does not define the specifics of what a variant is or how it differs from the parent product or other variants. This bundle addresses this by introducing two entities: 1. **Attribute Group** (`OpenDxp\Ecommerce\Component\Variant\Model\AttributeGroupInterface`): Defines types like size or color. 2. **Attribute Value** (`OpenDxp\Ecommerce\Component\Variant\Model\AttributeValueInterface`): Represents values like `XL` or `Red`. The product is an abstract entity specifying the allowed attribute groups, with its variants needing to have these group values filled. #### Example - **AttributeGroup Color**: Contains `AttributeValue Red` and `AttributeValue Blue`. - **Product**: Defines allowed groups for color. - **Variant-Red**: Defines the `AttributeValue Red` in attributes. - **Variant-Blue**: Defines the `AttributeValue Blue` in attributes. #### Variant-Aware Attribute Groups An attribute group has an `isVariantAware` flag (`AttributeGroupInterface::getIsVariantAware()`). Only variant-aware groups define what makes a variant unique, like Color or Size. Non-variant-aware groups only carry extra product characteristic information. Both kinds of groups are stored together in `allowedAttributeGroups`. `ProductVariantAwareInterface` offers two helpers that split them for you: - `getAllowedVariantAttributeGroups()`: only the variant-defining groups. - `getAllowedStandardAttributeGroups()`: only the characteristic groups. Use these instead of filtering `getAllowedAttributeGroups()` by hand. For a single attribute value of a specific group, use `findAttributeForGroup()`; `getAttributes()` itself always returns both kinds mixed. ### Usage #### Class Installation The Variant Bundle does not come with an installer for required resources. You need to install what you need manually. By default, it includes three classes: - `EcommerceAttributeGroup` - `EcommerceAttributeColor` - `EcommerceAttributeValue` The classes `Color` and `Value` represent value types, while `Group` is a group type. Manually import the classes from `variant-bundle/Resources/install/opendxp/classes`. #### Creating a "Product" Class Implement the `OpenDxp\Ecommerce\Component\Variant\Model\ProductVariantAwareInterface` for your "Product" class. It should include these fields: - **attributes**: ManyToManyObjectRelation for `EcommerceAttributeColor`/`EcommerceAttributeValue`. - **allowedAttributeGroups**: ManyToManyObjectRelation for `EcommerceAttributeGroup`. - **mainVariant**: ManyToOneRelation for `Product` (i.e., your class implementing the interface). The Variant Bundle significantly enhances the flexibility of product management, allowing for detailed and diverse product variant configurations. ### Variant Generator The Variant Generator is a tool that automatically generates variants for a VariantAware Class based on the attribute groups defined in the Data Object. The Generator is available in the OpenDxp backend at the Toolbar on your VariantAware Class. #### Installation Variant Generator uses Symfony Messenger for async processing, you can run it with the following command: ```yaml bin/console messenger:consume opendxp_ecommerce_variant --time-limit=300 ``` ### Attribute Builder Field ![Messenger](img/attribute_builder.png) The `ecommerceProductAttributesBuilder` field type (`OpenDxp\Ecommerce\Bundle\VariantBundle\CoreExtension\ProductAttributesBuilder`) is the admin edit-view field for managing a product's attribute groups and, on a variant, its attribute values. For usage from an editor's perspective, see the [Attributes & Variants user documentation](../02_User_Documentation/07_Catalog/01_Attributes_And_Variants.md). It renders two grids, split by `isVariantAware`, and always saves both back into `allowedAttributeGroups` together. `AttributesBuilderController` backs the field: `getSetAction` and `getGroupAction` read attribute group data, `getGroupAttributesAction` reads a group's existing attribute values, and `createAttributeAction` creates a new `EcommerceAttributeValue` or `EcommerceAttributeColor` attribute. --- ## Bundles Overview The ecommerce bundle offers a suite of bundles that address various non-e-commerce specific functionalities. These bundles are versatile and can be utilized in any OpenDxp installation, extending beyond the scope of typical e-commerce solutions. ### Available Bundles Explore the range of bundles provided, each designed to fulfill specific roles within your OpenDxp installation: - **[Class Definition Patch Bundle](./ClassDefinitionPatch_Bundle.md)**: Enables patching of class definitions from other bundles. - **[Index Bundle](./Index_Bundle.md)**: Facilitates advanced indexing capabilities. - **[Money Bundle](./Money_Bundle.md)**: Provides tools for handling monetary values. - **[Messenger Bundle](./Messenger_Bundle.md)**: Enhances message handling and delivery. - **[Optimistic Entity Lock Bundle](./OptimisticEntityLock_Bundle.md)**: Implements optimistic locking for entities. - **[Resource Bundle](./Resource_Bundle/index.md)**: Streamlines repetitive tasks like CRUD operations. - **[SEO Bundle](./SEO_Bundle.md)**: Offers features for search engine optimization. - **[Sequence Bundle](./Sequence_Bundle.md)**: Manages sequential number generation. - **[Storage List Bundle](./StorageList_Bundle.md)**: Handles complex data storage requirements. - **[Theme Bundle](./Theme_Bundle.md)**: Facilitates theme management and customization. - **[Variant Bundle](./Variant_Bundle.md)**: Manages product variants effectively. #### Focus on Resource Bundle One of the primary objectives is to provide a flexible framework. The Resource Bundle is a foundational component that simplifies many common tasks: - Automates the creation of CRUD controllers (`ResourceController`). - Streamlines the generation of factories, repositories, routes, and resource controllers for ecommerce resources. This bundle proves invaluable not only for ecommerce-specific functionalities but also for any OpenDxp bundle, offering extensive utility across various applications. For more details on the Resource Bundle, [click here](./Resource_Bundle). These bundles collectively enhance the capabilities of your OpenDxp installation, providing powerful tools to meet diverse requirements in a streamlined and efficient manner. --- ## Extend Ecommerce Resources All models are placed in the ```OpenDxp\Ecommerce\Component\*ComponentName*\Model``` namespaces alongside with their interfaces. > Many models are extended in the Core component. If the model you are willing to override exists in the Core you should be extending the Core one, not the base model from the component. ### How to Customize a Model #### Doctrine ORM Depending on your Doctrine ORM configuration, you need to place your Models in the right Folder. The Default configuration, places them in the `Entity` directory: ```yaml doctrine: orm: mappings: App: type: attribute dir: '%kernel.project_dir%/src/App/Entity' is_bundle: false prefix: App\Entity alias: App ``` #### Example Model Let’s take the [```OpenDxp\Ecommerce\Component\Currency\Model\Currency```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Currency/Model/Currency.php) as an example. This one is extended in Core. How can you check that? First of all, you need to find the current used class by doing following: ```bash $ php bin/console debug:container --parameter=opendxp_ecommerce.model.currency.class ``` As a result you will get the [```OpenDxp\Ecommerce\Component\Core\Model\Currency```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Model/Currency.php) - this is the class that you need to be extending. Assuming you want to add a field called **flag** **1.** The first thing to do is to write your own class which will extend the base ```Currency``` class ```php flag; } public function setFlag(bool $flag): void { $this->flag = $flag; } } ``` **2**. Finally you’ll need to override the model’s class in the ```config/config.yaml```. Under the opendxp_ecommerce_* where * is the name of the bundle of the model you are customizing, in our case it will be the EcommerceCurrencyBundle -> opendxp_ecommerce_currency. ```yaml opendxp_ecommerce_currency: resources: currency: classes: model: App\Entity\Currency ``` **3**. Update the database. There are two ways to do it. via direct database schema update: ```bash $ php bin/console doctrine:schema:update --force ``` via migrations: Which we strongly recommend over updating the schema. ```bash $ php bin/console doctrine:migrations:diff $ php bin/console doctrine:migrations:migrate ``` **4**. We also need a serializer group for the new field. This is done in the ```config/jms_serializer/Currency.yaml``` file. ```yaml App\Entity\Currency: exclusion_policy: ALL xml_root_name: store properties: flag: expose: true type: bool groups: [Detailed] ``` --- ## Customizing Forms The forms are placed in the `OpenDxp\Ecommerce\Bundle\*BundleName*\Form\Type` namespaces and the extensions will be placed in `App\Ecommerce\Form\Extension`. ### Why would you customize a Form? There are plenty of reasons to modify forms that have already been defined. Your business needs may sometimes slightly differ from our internal assumptions. You can: * add completely **new fields**, * **modify** existing fields, make them required, change their HTML class, change labels etc., * **remove** fields that are not used. ### How to customize a Resource Form? If you want to modify the form for the `Store` in your system there are a few steps that you should take. Assuming that you would like to (for example): * Add a `contactHours` field, These will be the steps that you will have to take to achieve that: **1.** If your are planning to add new fields remember that beforehand they need to be added on the model that the form type is based on. In case of our example if you need to have the `contactHours` on the model and the entity mapping for the `Store` resource. To get to know how to prepare that go [there](./01_Extend_Ecommerce_Resources.md). **2.** Create a **Form Extension**. Your form has to extend a proper base class. How can you check that? For the `StoreType` run: ```bash $ php bin/console debug:container opendxp_ecommerce.form.type.store ``` As a result you will get the [```OpenDxp\Ecommerce\Bundle\StoreBundle\Form\Type\StoreType```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Bundle/StoreBundle/Form/Type/StoreType.php) - this is the class that you need to be extending. ```php add('contactHours', TextType::class, [ 'required' => false ]); } public static function getExtendedTypes(): array { return [StoreType::class]; } } ``` **3.** After creating your class, register this extension as a service in the `config/services.yaml`: ```yaml services: App\Ecommerce\Form\Extension\StoreTypeExtension: tags: - { name: form.type_extension, extended_type: OpenDxp\Ecommerce\Bundle\StoreBundle\Form\Type\StoreType } ``` In our case you will need to extend the ExtJs Form as well: `public/ecommerce/js/store.js`. In **ExtJs** your new store file need to look like this: ```javascript opendxp_ecommerce.store.item = Class.create(opendxp_ecommerce.store.item, { getFormPanel: function ($super) { var panel = $super(); panel.down("fieldset").add( [ { xtype: 'textfield', fieldLabel: 'Contact Hours', name: 'contactHours' } ] ); return this.formPanel; } }); ``` And you need to configure it to be loaded as well: ```yaml opendxp_ecommerce_store: opendxp_admin: js: custom_store: '/ecommerce/js/store.js' ``` --- ## Extending the Ecommerce Bundle Ecommerce Data Objects (like EcommerceProduct or EcommerceOrder) can be changed directly within OpenDxp. ### Replace Ecommerce Object Classes with your own Classes The ecommerce bundle uses OpenDxp Parameters to determine the OpenDxp Object Class. To change it, simply add this to your `config.yml`: ```yaml opendxp_ecommerce_order: opendxp: order: classes: model: 'OpenDxp\Model\DataObject\MyOrderClass' install_file: 'config/Resources/install/opendxp/classes/MyOrderClass.json' repository: App\Repository\OrderRepository factory: App\Factory\OrderFactory ``` --- ## Custom Price-Rule/Shipping-Rule/Notification-Rule Actions Adding Price-, Shipping- or Notification-Rule Actions is the same for all of these types. Their only difference is the tag you use and Interface you need to implement for them. | Action Type | Tag | Interface | |------------------------|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Cart Price Rule | opendxp_ecommerce.cart_price_rule.action | [```OpenDxp\Ecommerce\Component\Order\Cart\Rule\Action\CartPriceRuleActionProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Cart/Rule/Action/CartPriceRuleActionProcessorInterface.php) | | Product Price Rule | opendxp_ecommerce.product_price_rule.action | [```OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductPriceActionProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Product/Rule/Action/ProductPriceActionProcessorInterface.php) | | Product Specific Price | opendxp_ecommerce.product_specific_price_rule.action | [```OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductPriceActionProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Product/Rule/Action/ProductPriceActionProcessorInterface.php) | | Shipping Rule | opendxp_ecommerce.shipping_rule.action | [```OpenDxp\Ecommerce\Component\Shipping\Rule\Action\CarrierPriceActionProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Shipping/Rule/Action/CarrierPriceActionProcessorInterface.php) | | Notification Rule | opendxp_ecommerce.notification_rule.action | [```OpenDxp\Ecommerce\Component\Notification\Rule\Action\NotificationRuleProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Notification/Rule/Action/NotificationRuleProcessorInterface.php) | ### Example Adding a new Action Now, let's add a new Action for Product Price Rules. To do so, we first need to create a new class and implement the interface listed in the table above. For Product Price Rules, we need to use [```OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductPriceActionProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Product/Rule/Action/ProductPriceActionProcessorInterface.php) ```php namespace App\Ecommerce; final class CustomAction implements \OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductPriceActionProcessorInterface { public function getPrice($subject, array $context, array $configuration): int { //If your action gives the product a new Price, put your calculation here return $configuration['some_value']; } } ``` We also need a FormType for the actions configurations: ```php add('some_value', TextType::class) ; } } ``` With configuration, comes a Javascript file as well: ```javascript // public/ecommerce/js/custom_action.js opendxp.registerNS('opendxp_ecommerce.product.pricerule.actions.custom'); opendxp_ecommerce.product.pricerule.actions.custom = Class.create(opendxp_ecommerce.rules.actions.abstract, { type: 'custom', getForm: function () { var some_value = 0; var me = this; if (this.data) { some_value = this.data.some_value / 100; } var some_valueField = new Ext.form.NumberField({ fieldLabel: t('custom'), name: 'some_value', value: some_value, decimalPrecision: 2 }); this.form = new Ext.form.Panel({ items: [ some_valueField ] }); return this.form; } }); ``` Don't forget to run the following command afterwards to deploy it if needed. If you're using the latest symfony structure, omit the web. ``` bin/console assets:install web ``` ### Registering the Custom Action to the Container and load the Javascript File We now need to create our Service Definition for our Custom Action: ```yaml App\Ecommerce\CustomAction: tags: - { name: opendxp_ecommerce.product_price_rule.action, type: custom, form-type: App\Ecommerce\Form\Type\CustomActionType } ``` and add this to your config.yml: ```yaml opendxp_ecommerce_product: opendxp_admin: js: custom_action: '/ecommerce/js/custom_action.js' ``` --- ## Custom Price-Rule/Shipping-Rule/Notification-Rule Conditions Adding Price-, Shipping- or Notification-Rule Conditions is the same for all of these types. They're only difference is the tag you use and Interface you need to implement for them. | Action Type | Tag | Interface/AbstractClass | |------------------------|---------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Cart Price Rule | opendxp_ecommerce.cart_price_rule.condition | [```OpenDxp\Ecommerce\Component\Order\Cart\Rule\Condition\AbstractConditionChecker```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Cart/Rule/Condition/AbstractConditionChecker.php) | | Product Price Rule | opendxp_ecommerce.product_price_rule.condition | [```OpenDxp\Ecommerce\Component\Rule\Condition\ConditionCheckerInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Rule/Condition/ConditionCheckerInterface.php) | | Product Specific Price | opendxp_ecommerce.product_specific_price_rule.condition | [```OpenDxp\Ecommerce\Component\Rule\Condition\ConditionCheckerInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Rule/Condition/ConditionCheckerInterface.php) | | Shipping Rule | opendxp_ecommerce.shipping_rule.condition | [```OpenDxp\Ecommerce\Component\Shipping\Rule\Condition\CategoriesConditionChecker```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Shipping/Rule/Condition/AbstractConditionChecker.php) | | Notification Rule | opendxp_ecommerce.notification_rule.condition | [```OpenDxp\Ecommerce\Component\Notification\Rule\Condition\AbstractConditionChecker```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Notification/Rule/Condition/AbstractConditionChecker.php) | ### Example Adding a new Condition Now, lets add a new Condition for Product Price Rules. To do so, we first need to create a new class and implement the interface listed in the table above. For Product Price Rules, we need to use [```OpenDxp\Ecommerce\Component\Rule\Condition\ConditionCheckerInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Rule/Condition/ConditionCheckerInterface.php) ```php //src/App/Ecommerce/CustomCondition.php namespace App\Ecommerce; use OpenDxp\Ecommerce\Component\Resource\Model\ResourceInterface; use OpenDxp\Ecommerce\Component\Rule\Model\RuleInterface; final class CustomCondition implements \OpenDxp\Ecommerce\Component\Rule\Condition\ConditionCheckerInterface { public function isValid(ResourceInterface $subject, RuleInterface $rule, array $configuration, array $params = []): bool { //return true if valid, false if not return true; } ``` We also need a FormType for the conditions configurations: ```php //src/App/Ecommerce/Form/Type/CustomConditionType.php namespace App\Ecommerce\Form\Type; final class CustomConditionType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->add('some_value', TextType::class); } } ``` With configuration, comes a Javascript file as well: ```javascript //public/ecommerce/js/custom_condition.js opendxp.registerNS('opendxp_ecommerce.product.pricerule.conditions.custom'); opendxp_ecommerce.product.pricerule.conditions.custom = Class.create(opendxp_ecommerce.rules.conditions.abstract, { type: 'custom', getForm: function () { var some_value = 0; var me = this; if (this.data) { some_value = this.data.some_value / 100; } var some_valueField = new Ext.form.NumberField({ fieldLabel: t('custom'), name: 'some_value', value: some_value, decimalPrecision: 2 }); this.form = new Ext.form.Panel({ items: [ some_valueField ] }); return this.form; } }); ``` ### Registering the Custom Condition to the Container and load the Javascript File We now need to create our Service Definition for our Custom Condition: ```yaml App\Ecommerce\CustomCondition: tags: - { name: opendxp_ecommerce.product_price_rule.condition, type: custom, form-type: App\Ecommerce\Form\Type\CustomConditionType } ``` and add this to your config.yml: ```yaml opendxp_ecommerce_product: opendxp_admin: js: custom_condition: '/ecommerce/js/custom_condition.js' --- ## Extending The ecommerce bundle(Development) Welcome to the Extending Guide. This guide is an essential resource for developers looking to tailor the ecommerce bundle to their specific business needs. Its architecture is built with extensibility in mind, allowing for seamless integration and customization of its components. Whether you're extending resources, forms, data objects, or rule actions and conditions, this guide provides you with the knowledge and tools necessary to enhance and adapt functionalities. ### Extending Resources This bundle leverages Doctrine ORM for managing its resources, offering a robust and flexible way to extend these models. Learn how to add new fields, change relationships, or modify resource behaviors to suit your specific requirements. - [Extending Resources](01_Extend_Ecommerce_Resources.md) ### Customizing Forms Forms are a critical part of any eCommerce platform, and this bundle provides the ability to customize them to capture the exact data you need. Discover techniques for adding new form fields, adjusting validations, or altering form layouts to improve user experience and data collection. - [Extending Forms](02_Extend_Ecommerce_Forms.md) ### Extending Data Objects Data objects are central to managing product information, customer data, and more. This section covers how to extend these OpenDxp data objects, enabling you to add custom attributes, change object behaviors, or integrate with external systems. - [Extending DataObjects](03_Extend_Ecommerce_DataObjects.md) ### Rule Actions and Conditions The rule engine is powerful and versatile. Extending rule actions and conditions opens up possibilities for creating complex, tailored rules that align with your unique business logic. Whether it's pricing rules, discount conditions, or shipping calculations, learn how to craft custom rules that fit your business model perfectly. - [Extending Ecommerce Rule Actions](04_Extending_Rule_Actions.md) - [Extending Ecommerce Rule Conditions](05_Extending_Rule_Conditions.md) --- ## Currencies(Currencies) ### Create If you want to create a Currency via API, you can do following: ```php $newCurrency = $container->get('opendxp_ecommerce.factory.currency')->createNew(); ``` Now you have a new Currency, if you want to persist it, you need to do following: ```php $container->get('opendxp_ecommerce.manager.currency')->persist($newCurrency); $container->get('opendxp_ecommerce.manager.currency')->flush(); ``` You now have a new persisted Currency. ### Read If you want to query for Currencies, you can do following: ```php $currencyRepository = $container->get('opendxp_ecommerce.repository.currency'); $queryBuilder = $currencyRepository->createQueryBuilder('c'); // You can now create your query // And get the result $currencies = $queryBuilder->getQuery()->getResult(); ``` ### Update If you want to update an existing Currency, you need to do following: ```php // Fetch Currency $currency = $currencyRepository->findById(1); $currency->setName('Euro'); // And Persist it $container->get('opendxp_ecommerce.manager.currency')->persist($currency); $container->get('opendxp_ecommerce.manager.currency')->flush(); ``` ### Delete If you want to delete an existing Currency, you need to do following: ```php // Fetch Currency $currency = $currencyRepository->findById(1); // And remove it $container->get('opendxp_ecommerce.manager.currency')->remove($currency); $container->get('opendxp_ecommerce.manager.currency')->flush(); ``` --- ## Currency Context The Ecommerce Bundle utilizes a concept known as context and context resolvers to determine the current currency. This section explains the different types of contexts available and how to create a custom resolver. ### Context Types The Ecommerce Bundle defines several contexts to identify the appropriate currency for the current request. Each context is characterized by its name, priority, associated tag, and a specific role. The following table outlines these contexts: | Name | Priority | Tag | Description | |----------------------------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------------------------|-----------------------------------------------------------------------------------| | [FixedCurrencyContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Currency/Context/FixedCurrencyContext.php) | default | `opendxp_ecommerce.context.currency` | Primarily used for testing purposes. | | [StorageBasedCurrencyContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Context/Currency/StorageBasedCurrencyContext.php) | default | `opendxp_ecommerce.context.currency` | Checks if a currency has been changed during a frontend request. | | [CountryAwareCurrencyContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Context/Currency/CountryAwareCurrencyContext.php) | default | `opendxp_ecommerce.context.currency` | Commonly used as it determines the currency based on the current country context. | ### Creating a Custom Currency Resolver To implement a custom Currency Context, follow these steps: 1. **Implement the Interface**: Your custom context should implement the `OpenDxp\Ecommerce\Component\Currency\Context\CurrencyContextInterface`. 2. **Define the Method**: The interface requires the implementation of a method named `getCurrency`. This method should return an instance of `OpenDxp\Ecommerce\Component\Currency\Model\CurrencyInterface` or throw a `OpenDxp\Ecommerce\Component\Currency\Context\CurrencyNotFoundException` if the currency cannot be determined. 3. **Register the Context**: Add your custom context to the system by using the tag `opendxp_ecommerce.context.currency`. You can also assign a `priority` attribute, which is optional but can be used to define the order in which contexts are evaluated. --- ## Currencies(Localization) > This bundle is a multi-currency capable eCommerce Framework. It allows for the creation and utilization of various > currencies. ### Currency Operations 1. **[Create, Update, Read, Delete](./01_CRUD.md)**: Detailed instructions on how to manage currencies, including creating, updating, reading, and deleting currency data. 2. **[Currency Context](./03_Context.md)**: An overview of how this bundle determines the current currency using the concept of context and context resolvers, along with guidelines for implementing custom currency contexts. --- ## 01_CRUD a# Countries In the Ecommerce Bundle, managing countries through the API involves several operations including create, read, update, and delete. Below are the guidelines for each of these operations. ### Create To create a new country via API: ```php $newCountry = $container->get('opendxp_ecommerce.factory.country')->createNew(); ``` After creating a new Country instance, persist it using: ```php $container->get('opendxp_ecommerce.manager.country')->persist($newCountry); $container->get('opendxp_ecommerce.manager.country')->flush(); ``` You now have a new persisted country. ### Read To query for countries: ```php $countryRepository = $container->get('opendxp_ecommerce.repository.country'); $queryBuilder = $countryRepository->createQueryBuilder('c'); // You can now create your query // And get the result $countries = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing country: ```php // Fetch Country $country = $countryRepository->findById(1); $country->setName('Euro'); // And Persist it $container->get('opendxp_ecommerce.manager.country')->persist($country); $container->get('opendxp_ecommerce.manager.country')->flush(); ``` ### Delete To delete an existing country: ```php // Fetch Country $country = $countryRepository->findById(1); // And Remove it $container->get('opendxp_ecommerce.manager.country')->remove($country); $container->get('opendxp_ecommerce.manager.country')->flush(); ``` --- ## Country Context The Ecommerce Bundle uses a system of contexts and resolvers to determine the current country of a visitor or customer. ### Context Different contexts are used for determining the appropriate country in various scenarios: | Name | Priority | Tag | Description | |---------------------------------------------------------------------------------------------------------------------------------------------------|----------|-------------------------------------|---------------------------------------------------------------| | [FixedCountryContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Address/Context/FixedCountryContext.php) | default | `opendxp_ecommerce.context.country` | For testing purposes. | | [CountryContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Address/Context/RequestBased/CountryContext.php) | default | `opendxp_ecommerce.context.country` | Checks for a country within the country request resolver. | | [StoreAwareCountryContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Context/Country/StoreAwareCountryContext.php) | default | `opendxp_ecommerce.context.country` | Considers the current store context to determine the country. | ### Resolver Resolvers are used to find the correct country based on different criteria: | Name | Priority | Tag | Description | |-----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|------------------------------------------------------------|--------------------------------------------------------| | [GeoLiteBasedRequestResolver](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Address/Context/RequestBased/GeoLiteBasedRequestResolver.php) | 10 | `opendxp_ecommerce.context.country.request_based.resolver` | Uses the Geo Lite Database to determine user location. | ### Create a Custom Resolver To create a custom Country Context: 1. **Implement the Interface**: Your context should implement `OpenDxp\Ecommerce\Component\Address\Context\CountryContextInterface`. 2. **Define the Method**: This interface has a method `getCountry` returning `OpenDxp\Ecommerce\Component\Address\Model\CountryInterface` or throwing `OpenDxp\Ecommerce\Component\Address\Context\CountryNotFoundException`. 3. **Register the Context**: Use the tag `opendxp_ecommerce.context.country` with an optional `priority` attribute for registration. ### Create a Request-Based Resolver The Ecommerce Bundle supports custom request-based country context resolvers: 1. **Implement the Interface**: Create a resolver that implements `OpenDxp\Ecommerce\Component\Address\Context\RequestBased\RequestResolverInterface`. 2. **Define the Method**: Implement the method `findCountry`, which returns a country or null based on the request. 3. **Register the Resolver**: Use the tag `opendxp_ecommerce.context.country.request_based.resolver` with an optional `priority` attribute. ### Example Creating a `DocumentBasedRequestRequestResolver` based on OpenDxp Document: ```php // PHP code for creating DocumentBasedRequestRequestResolver ``` And configure the service: ```yaml services: App\Ecommerce\Address\Context\DocumentBasedRequestRequestResolver: arguments: - '@OpenDxp\Http\Request\Resolver\DocumentResolver' - '@opendxp_ecommerce.repository.country' tags: - { name: opendxp_ecommerce.context.country.request_based.resolver } ``` The Ecommerce Bundle will now resolve the current country based on the OpenDxp site being accessed. --- ## Countries > The Ecommerce Bundle is a multi-country capable eCommerce Framework, enabling the creation and utilization of various countries. ### Managing Countries 1. **[Create, Update, Read, Delete](./01_CRUD.md)**: Comprehensive guidelines for performing basic CRUD (Create, Read, Update, Delete) operations on countries. 2. **[Country Context](./02_Context.md)**: Detailed information on how the Ecommerce Bundle determines the country context for a visitor or customer, including the implementation and customization of country contexts and resolvers. --- ## States Managing states involves various operations, including create, read, update, and delete. Below are the guidelines for each of these operations. ### Create To create a new state via the API: ```php $newState = $container->get('opendxp_ecommerce.factory.state')->createNew(); ``` After creating a new State instance, persist it using: ```php $container->get('opendxp_ecommerce.manager.state')->persist($newState); $container->get('opendxp_ecommerce.manager.state')->flush(); ``` You now have a new persisted state. ### Read To query for states: ```php $stateRepository = $container->get('opendxp_ecommerce.repository.state'); $queryBuilder = $stateRepository->createQueryBuilder('c'); // You can now create your query // And get the result $states = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing state: ```php // Fetch State $state = $stateRepository->findById(1); $state->setName('Euro'); // And Persist it $container->get('opendxp_ecommerce.manager.state')->persist($state); $container->get('opendxp_ecommerce.manager.state')->flush(); ``` ### Delete To delete an existing state: ```php // Fetch State $state = $stateRepository->findById(1); // And Remove it $container->get('opendxp_ecommerce.manager.state')->remove($state); $container->get('opendxp_ecommerce.manager.state')->flush(); ``` --- ## Setup States Command THe Ecommerce bundle provides a CLI command to create states/regions for countries after the initial installation. By default, the ecommerce bundle only creates states for Switzerland (CH) during installation. Use this command to add states for additional countries. ### Usage ```bash # Setup states for a single country php bin/console opendxp-ecommerce:setup:states DE # Setup states for multiple countries php bin/console opendxp-ecommerce:setup:states DE,US,FR # Setup states and activate the country if not already active php bin/console opendxp-ecommerce:setup:states DE --activate-country # Verbose output to see individual states being created php bin/console opendxp-ecommerce:setup:states DE -v ``` ### Arguments | Argument | Description | |-----------|------------------------------------------------------------| | countries | Comma-separated list of country ISO codes (e.g., DE,US,FR) | ### Options | Option | Description | |--------------------|-------------------------------------------------| | --activate-country | Also activate the country if not already active | ### Prerequisites Before running this command, ensure that: 1. The Ecommerce Bundle is installed (`opendxp-ecommerce:install` has been run) 2. The country fixtures have been loaded (countries exist in the database) ### How It Works The command: 1. Looks up each specified country in the database by ISO code 2. Loads the country's divisions (states/regions) from the Rinvex country data library 3. Creates states for each division that doesn't already exist 4. Optionally activates the country if `--activate-country` is specified ### Example Output ``` Ecommerce Bundle States Setup ============================= Setting up states for countries: DE Processing country: DE ----------------------- [OK] Countries processed: 1 States created: 16 States skipped (already exist): 0 Countries activated: 0 ``` --- ## States(Localization) In the Ecommerce Bundle, you can manage states using various operations. These are detailed in the following sections: 1. **[Create, Update, Read, Delete](./01_CRUD.md)**: This section provides comprehensive instructions for performing basic CRUD (Create, Read, Update, Delete) operations on states within Core --- ## Zones Managing zones involves various operations, including create, read, update, and delete. Below are the guidelines for each of these operations. ### Create To create a new zone via the API: ```php $newZone = $container->get('opendxp_ecommerce.factory.zone')->createNew(); ``` After creating a new Zone instance, persist it using: ```php $container->get('opendxp_ecommerce.manager.zone')->persist($newZone); $container->get('opendxp_ecommerce.manager.zone')->flush(); ``` You now have a new persisted zone. ### Read To query for zones: ```php $zoneRepository = $container->get('opendxp_ecommerce.repository.zone'); $queryBuilder = $zoneRepository->createQueryBuilder('c'); // You can now create your query // And get the result $zones = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing zone: ```php // Fetch Zone $zone = $zoneRepository->findById(1); $zone->setName('Euro'); // And Persist it $container->get('opendxp_ecommerce.manager.zone')->persist($zone); $container->get('opendxp_ecommerce.manager.zone')->flush(); ``` ### Delete To delete an existing zone: ```php // Fetch Zone $zone = $zoneRepository->findById(1); // And Remove it $container->get('opendxp_ecommerce.manager.zone')->remove($zone); $container->get('opendxp_ecommerce.manager.zone')->flush(); ``` --- ## Zones(Localization) The Ecommerce Bundle allows for comprehensive management of zones, which is detailed in the following section: 1. **[Create, Update, Read, Delete](./01_CRUD.md)**: This section provides step-by-step instructions for performing basic CRUD (Create, Read, Update, Delete) operations on zones. --- ## Tax Rates Managing tax rates involves various operations, including create, read, update, and delete. Below are the guidelines for each of these operations. ### Create To create a new tax rate via the API: ```php $newTaxRate = $container->get('opendxp_ecommerce.factory.tax_rate')->createNew(); ``` After creating a new Tax Rate instance, persist it using: ```php $container->get('opendxp_ecommerce.manager.tax_rate')->persist($newTaxRate); $container->get('opendxp_ecommerce.manager.tax_rate')->flush(); ``` You now have a new persisted tax rate. ### Read To query for tax rates: ```php $rateRepository = $container->get('opendxp_ecommerce.repository.tax_rate'); $queryBuilder = $rateRepository->createQueryBuilder('c'); // You can now create your query // And get the result $rates = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing tax rate: ```php // Fetch Tax Rate $rate = $rateRepository->findById(1); $rate->setName('Euro'); // And Persist it $container->get('opendxp_ecommerce.manager.tax_rate')->persist($rate); $container->get('opendxp_ecommerce.manager.tax_rate')->flush(); ``` ### Delete To delete an existing tax rate: ```php // Fetch Tax Rate $rate = $rateRepository->findById(1); // And Remove it $container->get('opendxp_ecommerce.manager.tax_rate')->remove($rate); $container->get('opendxp_ecommerce.manager.tax_rate')->flush(); ``` --- ## Tax Rate > The Tax Rate represents a single tax rate percentage, such as 20%. ### Managing Tax Rates 1. **[Create, Update, Read, Delete](./01_CRUD.md)**: This section provides detailed instructions for performing the basic CRUD (Create, Read, Update, Delete) operations on tax rates. --- ## Tax Rules(Tax_Rule) Managing tax rules involves various operations, including create, read, update, and delete. Below are the guidelines for each of these operations. ### Create To create a new tax rule via the API: ```php $newTaxRule = $container->get('opendxp_ecommerce.factory.tax_rule')->createNew(); ``` After creating a new Tax Rule instance, persist it using: ```php $container->get('opendxp_ecommerce.manager.tax_rule')->persist($newTaxRule); $container->get('opendxp_ecommerce.manager.tax_rule')->flush(); ``` You now have a new persisted tax rule. ### Read To query for tax rules: ```php $ruleRepository = $container->get('opendxp_ecommerce.repository.tax_rule'); $queryBuilder = $ruleRepository->createQueryBuilder('c'); // You can now create your query // And get the result $rules = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing tax rule: ```php // Fetch Tax Rule $rule = $ruleRepository->findById(1); $rule->setName('Euro'); // And Persist it $container->get('opendxp_ecommerce.manager.tax_rule')->persist($rule); $container->get('opendxp_ecommerce.manager.tax_rule')->flush(); ``` ### Delete To delete an existing tax rule: ```php // Fetch Tax Rule $rule = $ruleRepository->findById(1); // And Remove it $container->get('opendxp_ecommerce.manager.tax_rule')->remove($rule); $container->get('opendxp_ecommerce.manager.tax_rule')->flush; ``` --- ## Tax Rule > The Tax Rule is designed to manage different tax rates based on Country and State. ### Managing Tax Rules 1. **[Create, Update, Read, Delete](./01_CRUD.md)**: This section provides detailed instructions for performing the basic CRUD (Create, Read, Update, Delete) operations on tax rules. --- ## Taxes > In the Ecommerce Bundle, taxes are categorized into two main types: Tax Rates and Tax Rules. Tax Rates represent specific > percentage rates, while Tax Rules determine the applicable Tax Rate based on Country and State. ### Tax Components 1. **[Tax Rates](./01_Tax_Rate/index.md)**: This section covers the management of individual tax rates, including their creation, updating, reading, and deletion. 2. **[Tax Rules](./02_Tax_Rule/index.md)**: Here, you'll find detailed information on setting up and managing Tax Rules, which are essential for determining the correct Tax Rate based on the geographical location (Country and State). --- ## Localization(Development) The ecommerce bundle offers a comprehensive suite of tools designed for the effective localization of your eCommerce platform. These tools encompass various components essential for adapting to different regional settings: - **[Currencies](./01_Currencies/index.md)**: This section focuses on handling multiple currencies, a crucial aspect of international eCommerce operations. - **[Countries](./02_Countries/index.md)**: Here, you'll find information on managing country-specific settings and preferences. - **[States](./03_States/index.md)**: This part covers the management of states, which is vital for regional customization and shipping logistics. - **[Zones](./04_Zones/index.md)**: Zones are geographical groupings that can be used for shipping and other location-based configurations. - **[Taxes](./05_Taxes/index.md)**: The section on taxes provides details on setting up and managing Tax Rates and Tax Rules, ensuring compliance with local tax regulations. --- ## Product The ecommerce bundle leverages OpenDxp Data Objects for persisting Product Information but adds a layer of dynamism and configurability through a Factory and Repository Pattern. ### Create To create a new product, first obtain the Factory Service: ```php $productFactory = $container->get('opendxp_ecommerce.factory.product'); $product = $productFactory->createNew(); ``` After setting the necessary values on the product, save it: ```php $product->save(); ``` ### Read Use the Repository Service to retrieve products: ```php $repository = $container->get('opendxp_ecommerce.repository.product'); // Query by ID $productWithIdOne = $repository->findById(1); // Get a Listing as in OpenDxp $list = $repository->getList(); $list->setCondition("active = 1"); $products = $list->getObjects(); ``` ### Update Updating a product follows the same pattern as in OpenDxp: ```php $repository = $container->get('opendxp_ecommerce.repository.product'); // Query by ID $productWithIdOne = $repository->findById(1); // Change values $productWithIdOne->setName('test'); $productWithIdOne->save(); ``` ### Delete Deleting a product also follows the familiar OpenDxp process: ```php $repository = $container->get('opendxp_ecommerce.repository.product'); // Query by ID $productWithIdOne = $repository->findById(1); $productWithIdOne->delete(); ``` --- ## Product Price Calculation The ecommerce bundle employs multiple Price Calculators to determine the correct price for a product. By default, the following calculators are used: - [Price Rule Calculator](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Bundle/ProductBundle/Calculator/PriceRuleCalculator.php): Utilizes prices from Catalog Price Rules and Specific Price Rules. - [Store Product Price Calculator](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Product/Calculator/StoreProductPriceCalculator.php): Calculates prices based on store values. For custom calculators, implement the interface [```OpenDxp\Ecommerce\Component\Product\Calculator\ProductPriceCalculatorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Product/Calculator/ProductPriceCalculatorInterface.php) and register your service with the tag ```opendxp_ecommerce.product.price_calculator```, including attributes ```type``` and ```priority```. ### Price Calculation Components The price calculation encompasses three distinct prices: - **Retail Price**: The base price without any discounts. - **Discount Price**: A special price for promotions, which should be lower than the retail price. - **Discount**: Monetary value of discounts from promotions. - **Price**: Calculated as the Retail Price or Discount Price (whichever is applicable) minus any discount rules. ### Calculator Service Usage To calculate the price for a product, use one of the following services: 1. ```opendxp_ecommerce.product.price_calculator```: Calculates prices without tax considerations. 2. ```opendxp_ecommerce.product.taxed_price_calculator```: Calculates prices with or without tax considerations (recommended). #### Templating For price calculation within a template, use the ```opendxp_ecommerce_product_price``` filter: ```twig {{ (product|opendxp_ecommerce_product_price(true)) }} ``` Custom Price Calculator Example This example demonstrates how to add a new calculator, using the property "price" - 1 as the Product Price, and -1 as the Discount. Note that this example is a demonstration and not a practical implementation. ```php add('textField', InputType::class); } } ``` Create a corresponding OpenDxp Backend UI JavaScript file: ```javascript opendxp.registerNS('opendxp_ecommerce.product.pricerules.conditions.custom'); opendxp_ecommerce.product.pricerule.conditions.custom = Class.create(opendxp_ecommerce.rules.conditions.abstract, { type: 'custom', getForm: function () { var textFieldValue = this.data && this.data.textField ? this.data.textField : null; this.textField = new Ext.create({ xtype: 'textfield', name: 'text-field', value: textFieldValue }); this.form = new Ext.form.Panel({ items: [this.textField] }); return this.form; } }); ``` Extend the service definition to include your form type: ```yaml # config/services.yaml services: App\Ecommerce\Product\PriceRules\Condition\CustomCondition: tags: - { name: opendxp_ecommerce.product_price_rule.condition, type: custom, form-type: App\Ecommerce\Form\Type\PriceRules\Condition\CustomCondition\CustomConditionType } ``` ### Resolving Autowiring Issues with Custom Conditions When autowiring is enabled in your project, you may encounter a scenario where your custom condition appears twice in the system: once with configuration options and once without. This duplication can be resolved by modifying your service definition to explicitly disable autoconfiguration for your custom condition. Here’s how you can achieve this: In your `services.yaml`, update the service definition for your custom condition as follows: ```yaml # config/services.yaml services: App\Ecommerce\Product\PriceRules\Condition\CustomCondition: autoconfigure: false tags: - { name: opendxp_ecommerce.product_price_rule.condition, type: custom, form-type: App\Ecommerce\Form\Type\PriceRules\Condition\CustomCondition\CustomConditionType } ``` This modification tells Symfony not to autoconfigure the custom condition service, thus preventing the duplication issue. With this change, your custom condition will appear only once in the system with the intended configuration. --- ## Custom Action ## Creating Custom Product Price Rule Action The Ecommerce Bundle offers a variety of default actions for product price rules. However, there may be instances where you need to implement custom actions. This guide will walk you through the process of creating a custom action for product price rules. ### Step 1: Create the Action Class Depending on the type of discount, you can choose between different options (see [Pricing](../02_Price_Calculation.md) for more details) - **Price Action**: To define a new fixed price (`OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductPriceActionProcessorInterface`) - **Price Discount Action**: To define a new discounted price (`OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductDiscountPriceActionProcessorInterface`) - **Discount Action**: To define a Discount on a given Price (`OpenDxp\Ecommerce\Component\Product\Rule\Action\ProductDiscountActionProcessorInterface`) Each one is responsible for a different type of discount. The following example shows how to create a new fixed price discount. ```php Find detailed information on product price > rules [here](../../../02_User_Documentation/03_Price_Rules/02_Product_Price_Rules.md). > Product price rules are applicable to multiple products and are based on conditions like category or manufacturer. #### Specific Price Rules > Explore specific price rules [here](../../../02_User_Documentation/03_Price_Rules/03_Specific_Price_Rules.md). > Specific price rules target a single product, with conditions based on factors like customer or customer group. #### Quantity Price Rules > For quantity price rules, click [here](../../../02_User_Documentation/03_Price_Rules/04_Quantity_Price_Rules.md). > These rules apply to a single product and are based on the quantity of a cart item. They only affect cart item prices, > and the default price calculation will return zero outside the cart context if only quantity rules are > configured. ### Extending Conditions and Actions - To add custom Actions, [click here](../../01_Extending_Guide/04_Extending_Rule_Actions.md). - To add custom Conditions, [click here](../../01_Extending_Guide/05_Extending_Rule_Conditions.md). ### Template Helper #### Get Formatted Price with all applied Rules ```twig {% import '@EcommerceFrontend/Common/Macro/currency.html.twig' as currency %} {% import '@EcommerceFrontend/Common/Macro/product_price.html.twig' as product_price %}
{{ 'opendxp_ecommerce.ui.price'|trans }}: {{ product_price.display_product_price(product) }}
{{ 'opendxp_ecommerce_product_tax_inc'|trans|format(product|opendxp_ecommerce_product_tax_rate) }} ({{ currency.convertAndFormat(product|opendxp_ecommerce_product_tax_amount) }})
``` #### Get Active Price Rules ```twig {{ dump(product|opendxp_ecommerce_product_price_rules) }} ``` --- ## Product Configuration ```yaml opendxp_ecommerce_product: opendxp: product: path: ecommerce/products classes: repository: OpenDxp\Ecommerce\Bundle\CoreBundle\OpenDxp\Repository\ProductRepository install_file: '@EcommerceCoreBundle/Resources/install/opendxp/classes/EcommerceProductBundle/EcommerceProduct.json' model: OpenDxp\Model\DataObject\EcommerceProduct interface: OpenDxp\Ecommerce\Component\Product\Model\ProductInterface factory: OpenDxp\Ecommerce\Component\Resource\Factory\OpenDxpFactory type: object ``` --- ## Create a new Product Type The ecommerce bundle allows you to create a new custom Product Type. The most single interface implementation that can be added to the cart is the `OpenDxp\Ecommerce\Component\Order\Model\PurchasableInterface`. You therefore have to at least implement this interface if you want to add a new Product Type and allow it to be added to the cart. If you need Product Price Rules, Product Specific Price Rules and Quantity Price Rules, you have to go for the `OpenDxp\Ecommerce\Component\Core\Model\ProductInterface`. In that case, it is easier to just copy the `EcommerceProduct` Class Definition and add it as a new Class. ### Registering your Product Type In Order to know that there is a new `Purchasable`, you have to register your class. The easiest way to do this is, to add this config: ```yaml opendxp_ecommerce_resource: opendxp: app.my_product: classes: model: OpenDxp\Model\DataObject\MyProduct interface: OpenDxp\Ecommerce\Component\Core\Model\ProductInterface ``` Or if it's just a `Purchasable`: ```yaml opendxp_ecommerce_resource: opendxp: app.my_product: classes: model: OpenDxp\Model\DataObject\MyProduct interface: OpenDxp\Ecommerce\Component\Order\Model\PurchasableInterface ``` The ecommerce bundle will then create separate Services for you, the mains one are the Factory and the Repository (`app.repository.my_product`, `app.factory.my_product`). You don't need to use them in your Project, but they are quite important internally. #### Alternative using Attributes It is also possible to use PHP Attributes to register new Product Types. You can do this by adding the following Attribute to your Product Class: ```php If you just added a Purchasable, you have to create a new Price Calculator. To create a new Price Calculator, you need to implement the interfaces `OpenDxp\Ecommerce\Component\Order\Calculator\PurchasablePriceCalculatorInterface` and `OpenDxp\Ecommerce\Component\Order\Calculator\PurchasableRetailPriceCalculatorInterface`. For how Pricing works in detail, see this: [Pricing](./02_Price_Calculation.md) ```php getRetailPrice($purchasable, $context); } public function getRetailPrice(PurchasableInterface $purchasable, array $context): int { if (!$purchasable instanceof \OpenDxp\Model\DataObject\MyProduct) { throw new NoPurchasableRetailPriceFoundException(__CLASS__); } return 100; } } ``` You then also need to register your new Calculator as a Service: ```yaml App\Ecommerce\MyProductPriceCalculator: tags: - { name: opendxp_ecommerce.order.purchasable.price_calculator, type: my_product } - { name: opendxp_ecommerce.order.purchasable.retail_price_calculator, type: my_product } ``` --- ## Product Units Units for Products can be defined globally in the OpenDxp Backend on Ecommerce > Product > Product Units. Each Product can have different units. Also each product/unit relation can have an own precision that differs to other relations. To archive that, the relation between products and units consists of three objects: - ProductUnit - ProductUnitDefinition - ProductUnitDefinitions As already said, the ProductUnit can be created in OpenDxp Backend and consists mainly of the key for unit like PCS, CNT etc. and some localized fields for rendering in frontend. To connect a ProductUnit to a EcommerceProduct in Backend you need to get the ProductUnit via repository and create a ProductUnitDefinition. ```php use OpenDxp\Ecommerce\Component\Product\Model\Product; use OpenDxp\Ecommerce\Component\Product\Model\ProductUnitInterface; use OpenDxp\Ecommerce\Component\Product\Model\ProductUnitDefinition; $product = Product::getById(1); /** @var ProductUnitInterface $unit */ $unit = $this->unitRepository->findOneBy(['name' => '']); $unitDefinition = new ProductUnitDefinition(); $unitDefinition->setConversionRate(1.0); // optional $unitDefinition->setPrecision(0); // optional $unitDefinition->setUnit($unit); $product->getUnitDefinitions()->setDefaultUnitDefinition($unitDefinition); $product->save(); ``` To add multiple units for a product use `$product->addUnitDefinition($unitDefinition)`. To change a unit override the default one `$product->getUnitDefinitions()->getDefaultUnitDefinition()->setUnit($otherUnit)`. --- ## Product Unit Definitions The ecommerce bundle has a great new feature for product units. E.g. you can sell items "per meter" etc. First, add some product units in OpenDxp > Ecommerce > Product > Product Units. Click "Add" and fill all the fields. Then you can add product-units directly in the product-objects inside OpenDxp (take a look at the "Price"-tab). There, you can also add multiple product units (eg: 1 box contains of 12 items - The ecommerce bundle will show you different order-possibilities in the add-to-cart section in the webshop) Using the API for product units: ### Create Default UnitDefinition If you want to create a new Product, we need to get our Factory Service for that: ```php /** @var DataObject\EcommerceProduct $product */ $product = DataObject::getById(1); $unitRepository = $container->get('opendxp_ecommerce.repository.product_unit'); /** @var ProductUnitDefinitionInterface $defaultUnitDefinition */ $defaultUnitDefinition = $container->get('opendxp_ecommerce.factory.product_unit_definition')->createNew(); $defaultUnitDefinition->setUnit($unitRepository->findByName('Kubikmeter')); /** @var ProductUnitDefinitionsInterface $unitDefinitions */ $unitDefinitions = $container->get('opendxp_ecommerce.factory.product_unit_definitions')->createNew(); $unitDefinitions->setDefaultUnitDefinition($defaultUnitDefinition); $unitDefinitions->setProduct($product); $product->setUnitDefinitions($unitDefinitions); $product->save(); ``` ### Update Default UnitDefinition ```php /** @var DataObject\EcommerceProduct $product */ $product = DataObject::getById(1); $unitRepository = $container->get('opendxp_ecommerce.repository.product_unit'); $defaultUnitDefinition = $product->getUnitDefinitions()->getDefaultUnitDefinition(); $defaultUnitDefinition->setUnit($unitRepository->findByName('Liter')); $unitDefinitionsRepository = $container->get('opendxp_ecommerce.repository.product_unit_definitions'); /** @var ProductUnitDefinitions $unitDefinitions */ $unitDefinitions = $unitDefinitionsRepository->findOneForProduct($product); $unitDefinitions->setDefaultUnitDefinition($defaultUnitDefinition); $product->setUnitDefinitions($unitDefinitions); $product->save(); ``` ### Delete UnitDefinition Deleting a UnitDefiniton from a product is done by finding the UnitDefinitions for the product in the product_unit_definitions repository and then deleting it. ```php /** @var DataObject\EcommerceProduct $product */ $product = DataObject::getById(1); $unitDefinitionsRepository = $container->get('opendxp_ecommerce.repository.product_unit_definitions'); $item = $unitDefinitionsRepository->findOneForProduct($product); $unitDefinitionsRepository->remove($item); ``` --- ## Money Values The ecommerce bundle adopts an integer-based approach for storing money and currency values. This methodology is crucial for ensuring accuracy and avoiding common issues associated with floating-point values, particularly when it comes to financial calculations. ### Why Integer Values? 1. **Precision and Accuracy**: Floating-point arithmetic can introduce rounding errors, which are unacceptable in financial calculations. By using integers to represent monetary values, the ecommerce bundle ensures precise calculations without rounding discrepancies. 2. **Standard Practices**: Many financial systems and databases prefer integer representation for money to maintain consistency and precision. This approach aligns the ecommerce bundle with standard practices in financial data handling. 3. **Avoiding Floating-Point Pitfalls**: Floating points can cause unexpected behavior due to how computers handle decimal fractions. For example, the result of adding 0.1 and 0.2 may not precisely equal 0.3 in floating-point arithmetic. Such inaccuracies are eliminated with integer representation. ### Working with Money Values When dealing with money values, it's essential to consider that these values are stored as integers. For instance, a value of "€10.50" would be stored as 1050 (assuming a base unit of 100 for the currency). This approach necessitates careful handling of these values in calculations, display formatting, and database operations. #### Example Usage When displaying a price or performing calculations, you should convert these integer values back to their decimal form. This conversion is typically handled by internal functions and utilities. #### Further Reading For a deeper understanding of how the ecommerce bundle handles fractional currency values and the implications for your eCommerce application, refer to the following documentation: - [Currency Fractions](../20_Currency_Fractions/index.md) --- ## Store Values A product has values for each store: a price and a tax rule group. The field `storeValues` of the product class holds them, and the object editor shows a tab for each store. ### Store Values in the Object Grid Drop the field "Store Values" into the selected columns of the grid configuration. A dialog asks for a store and a type. The column then shows this value of this store, for example "Standard: Store Price". Drop the field again for another store or type. - The price shows in the currency of the store. The tax rule shows the name of its tax rule group. - Editing a cell or a batch changes only this value of this store. - A variant that inherits the store values gets a copy of the values of every store. Its parent keeps its values. - Filter and sorting work on the column. A filter finds only the values a product has of its own. Each form field of the store values is a type, except a collection like the unit prices. A project that adds its own form field to the store values gets a type for it as well. Add a translation `opendxp_ecommerce_store_values_store_` with the name of the field in snake case, for example `opendxp_ecommerce_store_values_store_tax_rule`. ### Store Price Operator The grid operator "Store Price" shows the formatted price of a store. It cannot be edited. Use it inside a chain of operators, and use the column above to see and edit a store value. --- ## Products(Development) This guide should lead you through how the ecommerce bundle handles Product information and how it does price calculations. 1. [Create, Read, Update, Delete](./01_CRUD.md) 2. [Price Calculation](./02_Price_Calculation.md) 3. [Price Rules](./03_Price_Rules/index.md) 4. [Configuration](./04_Configuration.md) 5. [Multiple Product DataObjects](./05_Multiple_Product_DataObjects.md) 6. [Product Units](./06_Units.md) 7. [Product Unit Definitions](./07_Unit_Definitions.md) 8. [Store Values](./09_Store_Values.md) --- ## Checkout Manager ## Checkout The Ecommerce Bundle uses a CheckoutManager to handle Checkout steps. The default installation comes with following Steps: - Cart - Customer - Address - Shipping - Payment - Summary ### Create a Custom CheckoutManager If you want to modify the Checkout Manager, you have two options: - Create a total different Checkout Manager configuration - Modify the default configuration #### Create a total different Checkout Manager ```yaml # app/config/config.yml opendxp_ecommerce_core: checkout_manager: my_custom_manager checkout: my_custom_manager: steps: customer: step: opendxp_ecommerce.checkout.step.customer priority: 10 address: step: opendxp_ecommerce.checkout.step.address priority: 20 shipping: step: opendxp_ecommerce.checkout.step.shipping priority: 30 payment: step: opendxp_ecommerce.checkout.step.payment priority: 40 summary: step: opendxp_ecommerce.checkout.step.summary priority: 50 ``` #### Modify the default configuration ```yaml # app/config/config.yml opendxp_ecommerce_core: checkout: default: steps: payment: false # disables the payment step shipping: false # disables the shipping step payment_shipping: # adds a new PaymentShiping Step step: app_bundle.opendxp_ecommerce.checkout.payment_shipping # This is your service-id, the service needs to implement OpenDxp\Ecommerce\Component\Order\Checkout\CheckoutStepInterface priority: 40 # Priority of this step ``` --- ## Checkout Step If you want to implement a custom checkout step, you need to implement the interface ```OpenDxp\Ecommerce\Component\Order\Checkout\CheckoutStepInterface``` and register your step into your Cart Manager: ```yaml # app/config/config.yml opendxp_ecommerce_core: checkout: default: steps: custom: step: app.opendxp_ecommerce.checkout.custom priority: 50 ``` The [Checkout Controller](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Bundle/FrontendBundle/Controller/CheckoutController.php#L44) takes care about handling the Checkout for you then. ### Optional Checkout Step If you have an optional checkout step - depending on the cart, your Checkout Step can implement the interface ```OpenDxp\Ecommerce\Component\Order\Checkout\OptionalCheckoutStepInterface```. You need to implement the function ```isRequired(OrderInterface $cart)``` #### Optional Checkout Step Example ```php formFactory = $formFactory; $this->storeContext = $storeContext; $this->cartManager = $cartManager; } public function getIdentifier(): string { return 'payment'; } public function doAutoForward(OrderInterface $cart): bool { return $cart->getTotal() > 0; } public function doAutoForward(OrderInterface $cart): bool { return false; } public function validate(OrderInterface $cart): bool { return $cart->hasItems() && $cart->getPaymentProvider() instanceof PaymentProviderInterface; } public function commitStep(OrderInterface $cart, Request $request): bool { $form = $this->createForm($request, $cart); if ($form->isSubmitted()) { if ($form->isValid()) { $cart = $form->getData(); $this->cartManager->persistCart($cart); return true; } else { throw new CheckoutException('Payment Form is invalid', 'opendxp_ecommerce.ui.error.opendxp_ecommerce_checkout_payment_form_invalid'); } } return false; } public function prepareStep(OrderInterface $cart, Request $request): array { return [ 'form' => $this->createForm($request, $cart)->createView(), ]; } private function createForm(Request $request, OrderInterface $cart) { $form = $this->formFactory->createNamed('', PaymentType::class, $cart, [ 'payment_subject' => $cart ]); if ($request->isMethod('post')) { $form = $form->handleRequest($request); } return $form; } } ``` --- ## Checkout This guide should lead you through how the Ecommerce Bundle handles the Checkout. - [Checkout Manager](./01_Checkout_Manager.md) - [Checkout Step](./02_Checkout_Step.md) --- ## One Object to Rule Them All The ecommerce bundle utilizes a single DataObject class for managing Orders, Carts, and Quotes. This is the `EcommerceOrder` class. ### From Cart to Order The conversion of a Cart into an Order triggers the `SaleState` Workflow. --- ## Storage List The functionalities of Order, Cart, Quote, and Wishlist are unified, thanks to the abstraction into a dedicated Bundle. ### Configuration The default configuration for the Order StorageList is as follows: ```yaml opendxp_ecommerce_storage_list: list: order: context: interface: OpenDxp\Ecommerce\Component\Order\Context\CartContextInterface composite: OpenDxp\Ecommerce\Component\Order\Context\CompositeCartContext tag: opendxp_ecommerce.context.cart restore_customer_list_only_on_login: false services: manager: OpenDxp\Ecommerce\Bundle\OrderBundle\Manager\CartManager modifier: OpenDxp\Ecommerce\Component\Order\Cart\CartModifier enable_default_store_based_decorator: false session: enabled: true key: opendxp_ecommerce.cart form: type: OpenDxp\Ecommerce\Bundle\OrderBundle\Form\Type\CartType add_type: OpenDxp\Ecommerce\Bundle\OrderBundle\Form\Type\AddToCartType resource: interface: OpenDxp\Ecommerce\Component\Core\Model\OrderInterface product_repository: opendxp_ecommerce.repository.stack.purchasable repository: opendxp_ecommerce.repository.order item_repository: opendxp_ecommerce.repository.order_item factory: opendxp_ecommerce.factory.order item_factory: opendxp_ecommerce.factory.order_item add_to_list_factory: OpenDxp\Ecommerce\Bundle\OrderBundle\Factory\AddToCartFactoryInterface routes: summary: opendxp_ecommerce_cart_summary index: opendxp_ecommerce_index templates: add_to_cart: '@EcommerceFrontend/Product/_addToCart.html.twig' summary: '@EcommerceFrontend/Cart/summary.html.twig' controller: enabled: false class: OpenDxp\Ecommerce\Bundle\StorageListBundle\Controller\StorageListController expiration: enabled: true service: OpenDxp\Ecommerce\Bundle\OrderBundle\Expiration\OrderAndCartExpiration days: 0 params: cart: days: 0 params: anonymous: true customer: false order: days: 20 ``` --- ## Caching OpenDxp faces challenges with concurrency and caching, especially when handling DataObjects. The caching of DataObjects in OpenDxp occurs post-request during PHP termination. This can lead to delays if, for instance, complex Order Objects are involved or if there are issues in the cache marshalling process. Subsequently, a new request may access an outdated cached version of the Order Object, potentially causing inconsistencies. To mitigate these issues, this bundle provides a specific configuration option to disable caching for Storage List and Storage List Item Objects: ```yaml opendxp_ecommerce_storage_list: list: order: disable_caching: true wishlist: disable_caching: true ``` --- ## Cart Processor The Cart Processor is responsible for refreshing the state and prices of carts. It is automatically triggered every time the `persistCart` function of the [Cart-Manager](./08_Cart_Manager.md) is called on a cart, ensuring that the cart is re-calculated. The following processors are implemented by default. A processor with a higher priority runs first. | Priority | Processor | Task | |----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------| | 650 | [CartAdjustmentClearer](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartAdjustmentClearer.php) | Removes the adjustments of cart rules, shipping and payment. | | 605 | [CartItemsImmutableProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartItemsImmutableProcessor.php) | Calculates the items of an immutable order from their stored prices. | | 600 | [CartItemsProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartItemsProcessor.php) | Sets the prices and taxes of the items. | | 580 | [CartSubtotalProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartSubtotalProcessor.php) | Adds up the items. | | 575 | [CartItemsWholesaleProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartItemsWholesaleProcessor.php) | Sets the wholesale prices of the items. | | 550 | [CartShippingProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartShippingProcessor.php) | Adds the shipping costs. | | 450 | [CartRuleAutoProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartRuleAutoProcessor.php) | Applies the cart rules without a voucher code. | | 400 | [CartPriceRuleVoucherProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartPriceRuleVoucherProcessor.php) | Applies the cart rules of the voucher codes. | | 380 | [CartTextProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartTextProcessor.php) | Sets the names of the items. | | 350 | [CartTaxProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartTaxProcessor.php) | Adds up the taxes of the cart. | | 300 | [CartPaymentProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartPaymentProcessor.php) | Adds the payment fee. | | 100 | [CartCurrencyConversionProcessor](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Core/Order/Processor/CartCurrencyConversionProcessor.php) | Converts the amounts into the currency of the cart. | These processors handle all necessary price calculations for the cart. To extend cart calculations, a new processor should be created. ### Creating a Cart Processor To create a Cart Processor, implement the interface [```OpenDxp\Ecommerce\Component\Order\Processor\CartProcessorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Processor/CartProcessorInterface.php). Register this in the container with the tag ```opendxp_ecommerce.cart_processor``` and a ```priority``` attribute. #### Example of a Cart Processor Here's an example of a custom Cart Processor that calculates a unique field for the cart: ```php setCustomField(uniqid()); } } ``` Registration of the processor: ```yaml App\Ecommerce\Order\Cart\Processor\CustomCartProcessor: tags: - { name: opendxp_ecommerce.cart_processor, priority: 200 } ``` This custom processor will now assign a new unique ID to the custom field on every cart update. To add an adjustment with taxes to the items, see [Add a Taxed Adjustment to a Cart Item](./05_Adjustment.md#add-a-taxed-adjustment-to-a-cart-item). --- ## Adjustments Adjustments provide a mechanism to add extra costs or discounts to your Order, such as Taxes, Shipping, or Discounts. ### Add a New Adjustment The best practice for adding or removing adjustments is within Cart Processors. More information about Cart Processors can be found [here](./04_Cart_Processor.md). To add a new Adjustment, you should create a new Adjustment Model that implements the interface [`OpenDxp\Ecommerce\Component\Order\Model\AdjustmentInterface`]. Use the Factory [`OpenDxp\Ecommerce\Component\Order\Factory\AdjustmentFactoryInterface`] to create a new Adjustment. ```php /** * @var AdjustmentFactoryInterface $adjustmentFactory */ $adjustmentFactory = $this->container->get('opendxp_ecommerce.factory.adjustment'); $type = "custom-adjustment"; $label = "Label for Frontend"; $amountGross = 10000; //100.00 $amountNet = 8000; //80.00 $neutral = false; //If neutral, it doesn't affect the total amount $adjustment = $this->adjustmentFactory->createWithData( $type, $label, $amountGross, $amountNet, $neutral, ); //Adjustments can be added to the Cart or to a Cart Item $cart->addAdjustment($adjustment); $cartItem->addAdjustment($adjustment); ``` Adjustments can be applied either to the Cart as a whole or to individual Cart Items. ### Add a Taxed Adjustment to a Cart Item An adjustment on a cart item usually needs taxes too, for example a deposit or the price of an engraving. The service `OpenDxp\Ecommerce\Component\Core\Order\OrderItemAdjustmentApplierInterface` takes care of that. You pass one amount and say whether it includes taxes. The service works out the other amount, adds the taxes at the rate of the product to the item and adds the adjustment. ```php namespace App\Ecommerce\Order\Cart\Processor; use OpenDxp\Ecommerce\Component\Core\Model\StoreInterface; use OpenDxp\Ecommerce\Component\Core\Order\OrderItemAdjustmentApplierInterface; use OpenDxp\Ecommerce\Component\Order\Model\OrderInterface; use OpenDxp\Ecommerce\Component\Order\Processor\CartProcessorInterface; final class DepositProcessor implements CartProcessorInterface { public function __construct( private readonly OrderItemAdjustmentApplierInterface $orderItemAdjustmentApplier, ) { } public function process(OrderInterface $cart): void { /** @var StoreInterface $store */ $store = $cart->getStore(); foreach ($cart->getItems() as $item) { $item->removeAdjustments('deposit'); $this->orderItemAdjustmentApplier->addAdjustment( $item, 'deposit', 'Deposit', (int) round(25 * $item->getQuantity()), withTax: $store->getUseGrossPrice(), ); } } } ``` ```yaml App\Ecommerce\Order\Cart\Processor\DepositProcessor: tags: - { name: opendxp_ecommerce.cart_processor, priority: 590 } ``` > [!WARNING] > Give the processor a priority between 600 and 580. CartItemsProcessor sets the taxes of the items at 600, and > CartSubtotalProcessor adds up the items at 580. Outside this range, the adjustment is missing from the totals of the > cart. See the [default processors](./04_Cart_Processor.md). > [!WARNING] > Remove your adjustments before you add them. The cart is calculated again on every change. Without the removal, > every calculation adds the deposit once more. CartAdjustmentClearer does not do this for you. --- ## Taxation The flexible taxation system enables you to configure tax rules based on countries, states, zip codes, and tax categories. This system is designed to handle complex tax scenarios across different regions and products. ### Setting Up Taxation To configure taxation effectively, follow these essential steps: 1. **Create a Tax Rate**: Begin by setting up a tax rate. This rate represents the percentage of tax applied to a product or service. 2. **Create a Tax Rule**: Tax rules define the conditions under which a particular tax rate is applied. These rules can be based on various factors such as country, state, or zip code. 3. **Assign the Tax Rule to a Tax Rate**: Link your tax rule to the appropriate tax rate. This step ensures that the correct rate is applied based on the defined conditions in the tax rule. 4. **Assign the Tax Rule to a Product**: Finally, assign the tax rule to the products it applies to. This step integrates your tax configuration with your product catalog. ### Understanding Gross/Net Product Prices The concept of gross and net prices is pivotal and depends on your store's configuration: - **Gross Product Price**: If the store is configured for gross pricing, the product prices entered are treated as inclusive of tax. This means that the listed price includes the tax amount. - **Net Product Price**: Conversely, if the store is set up for net pricing, the product prices are exclusive of tax. In this case, the tax is calculated and added to the net price at the point of sale. Ecommerce automatically adjusts the final price, adding or subtracting the tax amount based on whether the product price is configured as gross or net. This feature ensures accurate pricing and tax calculation across different store configurations. --- ## Cart Price Rules and Vouchers In the Ecommerce Bundle, Cart Price Rules provide a mechanism to apply discounts to a shopping cart. This is achieved by creating Cart Price Rules and then adding Cart Price Rule Vouchers to the cart. For a detailed understanding of Cart Price Rules, refer to [Cart Price Rules](./../../02_User_Documentation/03_Price_Rules/01_Cart_Price_Rules.md). ### Discount and Surcharge Application Discounts or surcharges from Cart Price Rules are applied as [Adjustments](./05_Adjustment.md) to the order. To ensure correct tax calculations, these discounts or surcharges are applied proportionally to the items in the cart. #### Example Scenario Consider a cart with the following items: | Product | Quantity | Price | |-----------|----------|---------| | Product A | 1 | €50.00 | | Product B | 1 | €200.00 | Product A accounts for 20% of the total price, while Product B accounts for 80%. If a discount of €50 is applied, it will be distributed as follows: | Product | Quantity | Price | Discount | Discounted Price | |-----------|----------|---------|----------|------------------| | Product A | 1 | €50.00 | €10.00 | €40.00 | | Product B | 1 | €200.00 | €40.00 | €160.00 | This example demonstrates how the discount is proportionally divided among the products based on their contribution to the total cart value. This proportional allocation ensures that the discount is fairly distributed and that tax calculations remain accurate. --- ## Cart Manager The Cart Manager is designed to facilitate the management of Carts. It primarily handles: - Persisting a Cart The Cart Manager adheres to the interface [`OpenDxp\Ecommerce\Component\Order\Manager\CartManagerInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Manager/CartManagerInterface.php) and is implemented as the service `opendxp_ecommerce.cart.manager`. --- ## Cart Modifier The Ecommerce Bundle includes a helper service, known as the Cart Modifier, to facilitate modifications to the cart. This service simplifies tasks such as: - Adding items to the cart - Removing items from the cart - Changing the quantity of items in the cart The Cart Modifier adheres to the interface [`OpenDxp\Ecommerce\Component\Order\Cart\CartModifierInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Cart/CartModifierInterface.php) and is implemented by the service `opendxp_ecommerce.cart.modifier`. --- ## Cart Context The Ecommerce Bundle uses a system of context and context resolvers to determine the current cart. The Cart Context adheres to the interface [```OpenDxp\Ecommerce\Component\Order\Context\CartContextInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Context/CartContextInterface.php) and is implemented in the service `opendxp_ecommerce.context.cart`. ### Getting the Current Cart To obtain the current cart, use the `opendxp_ecommerce.context.cart` service: ```php $cartContext = $container->get('opendxp_ecommerce.context.cart'); // Get current cart, if none exists, a new one is created $cart = $cartContext->getCart(); ``` ### Context Types The table below outlines the various contexts used for cart determination: | Name | Priority | Description | |---------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|--------------------------------------------------------------------------------------------------| | [FixedCartContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Context/FixedCartContext.php) | -100 | For testing or backend order creation. | | [SessionAndStoreBasedCartContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Bundle/OrderBundle/Context/SessionAndStoreBasedCartContext.php) | -555 | Searches for a valid session cart in the given store context. | | [CustomerAndStoreBasedCartContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Bundle/OrderBundle/Context/CustomerAndStoreBasedCartContext.php) | -777 | Searches for a cart based on a customer, activates post-login to find the last cart a user left. | | [CartContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Context/CartContext.php) | -999 | Creates a new cart if other contexts fail. | ### Create a Custom Resolver To register a custom context, use the tag `opendxp_ecommerce.context.cart` with an optional `priority` attribute. --- ## Order Number Generator The Ecommerce Bundle generates a unique number for each completed order. This generation is handled by the `OpenDxp\Ecommerce\Component\Core\Order\Committer\OrderCommitter`, utilizing a `NumberGeneratorInterface` service. If the CoreBundle is installed, the `opendxp_ecommerce.order.number_generator.prefix_suffix` service is used. This service decorates the `opendxp_ecommerce.order.number_generator.default` and adds the capability to manage a prefix and suffix through ecommerce settings. To implement a custom number generator, create a service that decorates the `opendxp_ecommerce.order.number_generator.default`. The `decoration_priority` setting determines the order in which decorators are called. - A `decoration_priority` higher or equal to zero results in this order: `PrefixSuffix Generator > CustomNumberGenerator > DefaultSequenceGenerator`. - A `decoration_priority` below zero changes the order to: `CustomNumberGenerator > PrefixSuffix Generator > DefaultSequenceGenerator`. #### Example: Custom Number Generator with Padding This example shows a custom implementation that adds padding to the number: ```php final class CustomNumberGenerator implements NumberGeneratorInterface { public function __construct( private NumberGeneratorInterface $numberGenerator, // decorated service ) { } public function generate(ResourceInterface $model): string { $number = $this->numberGenerator->generate($model); return str_pad($number, 10, '0', STR_PAD_LEFT); } } ``` Symfony service definition: ```yaml App\Ecommerce\Order\CustomNumberGenerator: decorates: opendxp_ecommerce.order.number_generator.default decoration_priority: 1 arguments: - '@.inner' ``` This format should provide clarity on the customization of the Order Number Generator. If you have more sections to work on or need further adjustments, please let me know! --- ## Order List Filter This comes in handy if you need some special filtered data in your Order List. Your Customer is able to filter orders on specific conditions. ### Register Filter Service ```yml App\Ecommerce\OrderList\Filter\DemoFilter: tags: - { name: opendxp_ecommerce.grid.filter, type: demo } ``` ### Create PHP Class In this example we want to filter orders with available shipments in state "ready". ```php onCreateQuery(function (QueryBuilder $select) use ($list) { $select->join( ['shipment' => 'object_query_4'], 'shipment.order__id = object_' . $list->getClassId() . '.id' ); }); $list->addConditionParam('orderState = ?', 'confirmed'); $list->addConditionParam('shipment.state = ?', 'ready'); return $list; } public function supports(string $listType): bool { return $listType === 'opendxp_ecommerce_order'; } } ``` --- ## Order List Actions Actions allows you to process orders rapidly, right in the order grid view. ### Register Filter Service ```yml App\Ecommerce\OrderList\Action\Demo: arguments: $stateMachineManager: '@opendxp_ecommerce.state_machine_manager' $shipmentRepository: '@opendxp_ecommerce.repository.order_shipment' tags: - { name: opendxp_ecommerce.grid.action, type: demo } ``` ### Create PHP Class In this example we want to apply the shipment transition "ship" to selected orders. ```php stateMachineManager = $stateMachineManager; $this->shipmentRepository = $shipmentRepository; } public function getName(): string { return 'opendxp_ecommerce.order.demo'; } public function apply(array $processIds): string { $message = ''; $transition = 'ship'; $shipmentIds = []; foreach ($processIds as $id) { $m = []; $order = EcommerceOrder::getById($id); $shipments = $this->shipmentRepository->getDocuments($order); if (count($shipments) === 0) { $m[] = sprintf('- no shipments for order %s found. skipping....', $order->getId()); } else { foreach ($shipments as $shipment) { if ($shipment->getState() === 'shipped') { $m[] = sprintf('- transition "%s" for shipment %s already applied. skipping...', $transition, $shipment->getId()); continue; } $workflow = $this->stateMachineManager->get($shipment, 'opendxp_ecommerce_shipment'); if (!$workflow->can($shipment, $transition)) { $m[] = sprintf('- transition "%s" for shipment %s not allowed.', $transition, $shipment->getId()); } else { try { $workflow->apply($shipment, $transition); $shipmentIds[] = $shipment->getId(); $m[] = sprintf('- transition "%s" for shipment id %s successfully applied.', $transition, $shipment->getId()); } catch (\Exception $e) { $m[] = sprintf('- error while applying transition "%s" to shipment with id %s: %s.', $transition, $shipment->getId(), $e->getMessage()); } } } } $message .= sprintf('Order %s:
%s
', $id, join('
', $m)); } if (count($shipmentIds) > 0) { $packingListUrl = '/admin/your-packing-list-generator-url?ids=' . join(',', $shipmentIds); $message .= sprintf('
%s
', $packingListUrl, 'packing list'); } return $message; } public function supports(string $listType): bool { return $listType === 'opendxp_ecommerce_order'; } } ``` --- ## Extending Order Detail The Ecommerce Bundle's Order Detail Page is a custom-designed interface built with ExtJs, offering straightforward ways to extend and customize it according to your specific needs. ### UI Overview The Order Detail UI consists of various blocks strategically positioned for optimal user experience. There are four main positions for these blocks: - **Top**: At the top of the page. - **Left**: On the left side of the page. - **Right**: On the right side of the page. - **Bottom**: At the bottom of the page. ![Order Detail Positions](img/order_detail_positions.jpg) ### Default Blocks The following are the default blocks provided by the Ecommerce Bundle: - **Top** - Header - **Left** - Payments - Invoices - Shipments - Correspondence - **Right** - Customer Details - Comments - **Bottom** - Details ### Creating a New Block To introduce a new block, you'll need to create a new OpenDxp Backend Javascript File, following the namespace `opendxp_ecommerce.order.order.detail.blocks`. #### Example Below is a sample JavaScript code to demonstrate how to add a custom block: ```javascript opendxp.registerNS('opendxp_ecommerce.order.order.detail.blocks.custom'); opendxp_ecommerce.order.order.detail.blocks.custom = Class.create(opendxp_ecommerce.order.order.detail.abstractBlock, { saleInfo: null, initBlock: function () { var me = this; me.deliveryPhone = Ext.create({ xtype: 'panel', style: 'display:block' }); me.purchaseOrderNumber = Ext.create({ xtype: 'panel', style: 'display:block' }); me.trackingMail = Ext.create({ xtype: 'panel', style: 'display:block' }); me.packagingType = Ext.create({ xtype: 'panel', style: 'display:block' }); me.packagingAmount = Ext.create({ xtype: 'panel', style: 'display:block' }); var items = []; items.push({ xtype: 'panel', layout: 'hbox', items: [ { xtype: 'panel', flex: 1, items: [ me.purchaseOrderNumber, me.deliveryPhone, me.trackingMail ] }, { xtype: 'panel', flex: 1, items: [ me.packagingType, me.packagingAmount ] } ] }); this.details = Ext.create('Ext.panel.Panel', { title: t('opendxp_order_information'), margin: '0 20 20 0', border: true, flex: 6, iconCls: 'opendxp_ecommerce_icon_order', items: items }); }, getPriority: function () { return 1; }, getPosition: function () { return 'left'; }, getPanel: function () { return this.details; }, updateSale: function () { var me = this; me.deliveryPhone.setHtml('' + t('zeroridge_delivery_phone') + ': ' + me.sale.deliveryPhone); me.purchaseOrderNumber.setHtml('' + t('zeroridge_purchase_order_number') + ': ' + me.sale.purchaseOrderNumber); me.trackingMail.setHtml('' + t('zeroridge_tracking_mail') + ': ' + me.sale.trackingEmail); if (me.sale.packagingType) { me.packagingType.setHtml('' + t('zeroridge_packaging_type') + ': ' + me.sale.packagingType.localizedfields.data.en.name); } else { me.packagingType.setHtml('' + t('zeroridge_packaging_type') + ': Unknown'); } me.packagingAmount.setHtml('' + t('zeroridge_packaging_amount') + ': ' + me.sale.packagingAmount); } }); ``` In this custom block, the following methods must be implemented: - **initBlock**: Initializes the block upon creation. - **getPriority**: Determines the display priority of the block. Higher values mean higher placement. - **getPosition**: Specifies the position of the block (top, left, right, or bottom). - **getPanel**: Returns the ExtJs Panel representing the content of the block. - **updateSale**: Updates the block's content when the sale is refreshed ### Customizing Order Serialization The Ecommerce Bundle uses JMS Serializer for order serialization. You can extend its serialization logic either through JMS Configuration or by registering an event handler for the `OpenDxp\Ecommerce\Bundle\OrderBundle\Events::SALE_DETAIL_PREPARE` event. If that isn't enough, you can create a Custom Controller and query that with Ext.Ajax and your own parameters. --- ## Backend Management The backend management is tailored to handle the complete lifecycle of orders efficiently. This comprehensive system offers a range of features designed to manage orders from inception to completion, streamlining the entire process for administrators and staff. ### Key Features of Order Management The backend management system includes several critical functionalities that enhance the order processing experience: - **Order List**: The Order List is a centralized area where you can view and manage all orders. It provides a clear overview of order statuses, customer details, and other essential information. - **Order List Filters**: Customize your order list view with specific filters to sort and find orders based on various criteria such as date, status, customer, etc. This feature allows for efficient order tracking and management. - [Learn more about Order List Filters](./01_OrderList_Filter.md) - **Order List Actions**: Execute actions directly from the order list, such as updating order statuses, printing invoices, or initiating customer communication. This feature enhances the efficiency of managing orders in bulk or individually. - [Learn more about Order List Actions](02_OrderList_Action.md) - **Order Detail**: The Order Detail section provides an in-depth view of each order. It includes detailed information about the customer, ordered items, pricing, shipping, and billing. This comprehensive view is crucial for managing individual orders, processing returns, or addressing customer inquiries. - [Learn more about Extending the Order Detail Page](03_Extend_OrderDetail.md) The backend management system is designed to be intuitive and user-friendly, ensuring that managing your online store's orders is a seamless and efficient process. Whether you are processing a new order, updating order statuses, or handling customer inquiries, the backend management equips you with the tools you need to manage your store effectively. --- ## Order Workflow(Order) The Ecommerce Bundle leverages the Symfony Workflow component to manage and apply various states to orders. For detailed information about how this is implemented, including the state machine configuration and management, refer to the section on [State Management](./16_State_Management/index.md). --- ## State Machine - Available Workflows ### Order Sale Workflow Cart, Order and Quote are the same DataObject. To differentiate between them, we use states with workflows. State Machine: `opendxp_ecommerce_order_sales_type` #### Available Places | Name | Description | |:--------|:--------------------------------------------------------------------------| | `cart` | Initial State - Cart | | `order` | Once the customer finishes the checkout, pre-payment, it becomes an order | | `quote` | Once the customer finishes the checkout and requests a quote | #### Available Transition | Name | Allowed from Places | |:--------|:--------------------| | `order` | `cart` | | `cart` | `cart` | | `quote` | `cart` | ### Order Workflow State Machine: `opendxp_ecommerce_order` Description: The Order Workflow is the most simplest and also the most important one. #### Available Places | Name | Description | |:--------------|:------------------------------------------------------------------------------------| | `initialized` | Initial State. Just before a order gets saved for the very first time. | | `new` | a new order has been created | | `confirmed` | customer has successfully placed an order | | `cancelled` | order has been cancelled | | `complete` | the order is complete (all payments and shipments have been successfully processed) | #### Available Transition | Name | Allowed from Places | |:-----------|:--------------------| | `create` | `initialized` | | `confirm` | `new` | | `cancel` | `new`, `confirmed` | | `complete` | `confirmed` | #### Visualization ![ecommerce_order Workflow Visualization](img/ecommerce_order.png) ### Order Payment Workflow State Machine: `opendxp_ecommerce_order_payment` Description: Defines the summary payment state #### Available Places | Name | Description | |:---------------------|:--------------------------------------------| | `new` | order has been initial created | | `awaiting_payment` | a payment has been captured | | `partially_paid` | one of the order payments has been paid | | `cancelled` | all payments has been cancelled | | `paid` | all order payments successfully paid | | `partially_refunded` | one of the order payments has been refunded | | `refunded` | all payments has been refunded | #### Available Transition | Name | Allowed from Places | |:-------------------|:-----------------------------------------------| | `request_payment` | `new` | | `partially_pay` | `awaiting_payment`, `partially_paid` | | `cancel` | `awaiting_payment` | | `partially_refund` | `paid`, `partially_paid`, `partially_refunded` | | `refund` | `paid`, `partially_paid`, `partially_refunded` | #### Visualization ![ecommerce_order_payment Workflow Visualization](img/ecommerce_order_payment.png) ### Order Shipment Workflow State Machine: `opendxp_ecommerce_order_shipment` Description: Defines the summary shipment state #### Available Places | Name | Description | |:--------------------|:--------------------------------------------| | `new` | order has been initial created | | `cancelled` | all shipments has been cancelled | | `partially_shipped` | one of the order shipments has been shipped | | `shipped` | all order shipments has been shipped | #### Available Transition | Name | Allowed from Places | |:-----------------|:---------------------------| | `partially_ship` | `new` | | `cancel` | `new` | | `ship` | `new`, `partially_shipped` | #### Visualization ![ecommerce_order_shipment Workflow Visualization](img/ecommerce_order_shipment.png) ### Order Invoice Workflow State Machine: `opendxp_ecommerce_order_invoice` Description: Defines the summary invoice state #### Available Places | Name | Description | |:---------------------|:--------------------------------------------------| | `new` | order has been initial created | | `cancelled` | all invoices has been cancelled | | `partially_invoiced` | one of the order invoices has been invoiced | | `invoiced` | all order invoices has been successfully invoiced | #### Available Transition | Name | Allowed from Places | |:--------------------|:----------------------------| | `cancel` | `new` | | `partially_invoice` | `new` | | `invoice` | `new`, `partially_invoiced` | #### Visualization ![ecommerce_order_invoice Workflow Visualization](img/ecommerce_order_invoice.png) ### Payment Workflow State Machine: `opendxp_ecommerce_payment` Description: Defines the single payment state #### Available Places | Name | Description | |:-------------|:-----------------------------| | `new` | new payment has been created | | `processing` | payment has been captured | | `completed` | payment is complete | | `failed` | payment has failed | | `cancelled` | payment has been canceled | | `refunded` | payment has been refunded | #### Available Transition | Name | Allowed from Places | |:-----------|:--------------------| | `process` | `new` | | `complete` | `new`, `processing` | | `fail` | `new`, `processing` | | `cancel` | `new`, `processing` | | `refund` | `completed` | #### Visualization ![ecommerce_payment Workflow Visualization](img/ecommerce_payment.png) ### Shipment Workflow State Machine: `opendxp_ecommerce_shipment` Description: Defines the single shipment state #### Available Places | Name | Description | |:------------|:------------------------------------| | `new` | new shipment has been created | | `ready` | shipment has been assigned to order | | `cancelled` | shipment has been cancelled | | `shipped` | shipment has been shipped | #### Available Transition | Name | Allowed from Places | |:---------|:--------------------| | `create` | `new` | | `ship` | `ready` | | `cancel` | `ready` | #### Visualization ![ecommerce_shipment Workflow Visualization](img/ecommerce_shipment.png) ### Invoice Workflow State Machine: `opendxp_ecommerce_invoice` Description: Defines the single invoice state #### Available Places | Name | Description | |:------------|:-----------------------------------| | `new` | new invoice has been created | | `ready` | invoice has been assigned to order | | `cancelled` | invoice has been cancelled | | `complete` | invoice has been completed | #### Available Transition | Name | Allowed from Places | |:-----------|:--------------------| | `create` | `new` | | `cancel` | `ready` | | `complete` | `ready` | #### Visualization ![ecommerce_invoice Workflow Visualization](img/ecommerce_invoice.png) --- ## State Machine - Callbacks It's really simple to create a custom state machine callback. ### After Callbacks In this example we want to register a simple listener which gets triggered **after** a customer successfully placed a order: ```yml opendxp_ecommerce_workflow: state_machine: opendxp_ecommerce_order: callbacks: after: do_something_special: on: ['confirm'] do: ['@App\Ecommerce\EventListener\SpecialListener', 'doSomething'] args: ['object'] priority: -10 # fire action early! ``` | Name | Description | |:-----------|:----------------------------------------------------------------| | `on` | transition name | | `do` | service and method to dispatch | | `args` | `object` or `event`. Object type depends on state machine type. | | `priority` | set priority. default is `0` | And your Service: ```php getCustomer(); /** @var string $locale */ $locale = $order->getLocaleCode(); // your very special code. } } ``` ### Before Callbacks In this example we want to register a simple listener which gets triggered **before** a the shipment transaction `ready` gets applied: ```yml opendxp_ecommerce_workflow: state_machine: opendxp_ecommerce_shipment: callbacks: before: check_something: on: ['create'] do: ['@App\Ecommerce\EventListener\SpecialListener', 'checkSomething'] args: ['object'] priority: 0 ``` | Name | Description | |:-----------|:----------------------------------------------------------------| | `on` | transition name | | `do` | service and method to dispatch | | `args` | `object` or `event`. Object type depends on state machine type. | | `priority` | set priority. default is `0` | As you can see in the class below, the `checkSomething()` method throws an exception. This prevents the state machine from switching to the `ready` state. Just remove the exception and the transition gets applied as expected. ```php = 20 days ago - Order State is `initialized` or `new` or `confirmed` - Order Payment State is not `paid` Read more about automation [here](../../../02_User_Documentation/10_Automation/index.md). ##### Expire Orders via Backend There is also a `cancel` button in the order detail section. ##### Expire Orders via Command There is also a command for that: ```bash $ opendxp-ecommerce:order:expire ``` ##### Change Orders Expiration Date ```yml opendxp_ecommerce_storage_list: list: order: expiration: params: order: days: 30 ``` --- ## State Machine - Extend Workflows It's possible to extend all available Ecommerce Bundle Workflows. ### Example A: Extend Shipment Workflow #### Workflow Configuration ```yml opendxp_ecommerce_workflow: state_machine: opendxp_ecommerce_shipment: # define a new place "reviewed" places: - reviewed # define a new transition "review" transitions: review: from: [new, ready] to: reviewed # add some colors for better ux place_colors: reviewed: '#2f819e' transition_colors: review: '#2f819e' ``` #### Add translations Just use the OpenDxp Backend/Frontend translation or just add it via default symfony translation context: ```yml # app/Resources/translations/admin.en.yml opendxp_ecommerce_workflow_transition_opendxp_ecommerce_shipment_review: 'Review' opendxp_ecommerce_workflow_state_opendxp_ecommerce_shipment_reviewed: 'Reviewed' # app/Resources/translations/messages.en.yml opendxp_ecommerce.ui.workflow.state.opendxp_ecommerce_shipment.reviewed: 'Shipment under Review' ``` #### Inform the Ecommerce Bundle about new Transition of Shipment Workflow Not all transitions should be available in backend. To allow the transition to show up, you need to implement a simple event listener: ```yml # app/config/services App\Ecommerce\EventListener\WorkflowListener: autowire: true tags: - { name: kernel.event_listener, event: opendxp_ecommerce.workflow.valid_transitions, method: parseTransitions} ``` ```php getWorkflowName(); if($workflowName === 'opendxp_ecommerce_shipment') { $event->addAllowedTransitions(['review']); } } } ``` ### Example B: Change default Transition Behaviour of Shipment Workflow > **Note:** Be careful while changing transitions. Test your application if a workflow still runs smoothly after > changing it! In this example we want to change the default shipping behavior. #### Workflow before: `ready` -> `shipped` -> `cancelled` #### Workflow after: `ready` -> `reviewed` -> `shipped` -> `cancelled` #### Workflow Configuration ```yml opendxp_ecommerce_workflow: state_machine: opendxp_ecommerce_shipment: # define a new place "reviewed" places: - reviewed # define a new transition "review" transitions: review: from: [ready] to: reviewed # override the default "ship" transition # which only allows [ready] as valid "from" dispatcher ship: from: [reviewed] to: shipped # add some colors for better ux place_colors: reviewed: '#2f819e' transition_colors: review: '#2f819e' ``` #### Example C: Callback Listener If you need to implement some further business logic after the `opendxp_ecommerce_shipment` state has changed to `reviewed` you need to define a callback: > **Note:** Please make sure your service is public available! ```yml opendxp_ecommerce_workflow: state_machine: opendxp_ecommerce_shipment: callbacks: after: do_something_after_review: on: ['review'] do: ['@your_service', 'yourAction'] # in this context, "object" is the shipment item args: ['object'] priority: -10 # fire action early! ``` --- ## State Management The Ecommerce Bundle employs a sophisticated [State Machine](https://symfony.com/doc/current/workflow/state-machines.html) as a core feature, enabling the management of complex workflows in a secure and modern manner. Unlike many eCommerce frameworks that use a cumbersome and rigid "state/status" concept, the Ecommerce Bundle's approach offers a more dynamic and extendable state workflow. ### Places In the context of a State Machine, the traditional "Status" is referred to as "Places". Each workflow comes with its predefined set of Places. ### Transition Transitions are used to change the Place of a workflow. A transition is considered valid if it successfully updates the workflow to a new place. ### Callbacks Several events can be triggered for each transition, and these can be extended for specific project needs. **Example**: When all order payments reach the `completed` place, the `opendxp_ecommerce_order_payment` workflow automatically transitions to `paid`. ### Workflows The Ecommerce Bundle includes seven implemented workflows: - `opendxp_ecommerce_order` - `opendxp_ecommerce_order_payment` - `opendxp_ecommerce_order_shipment` - `opendxp_ecommerce_order_invoice` - `opendxp_ecommerce_payment` - `opendxp_ecommerce_shipment` - `opendxp_ecommerce_invoice` These workflows are interconnected, so any transition in one can trigger transitions in others. Once a transition is dispatched, it cannot be reversed unless such an option is defined in the available transitions. #### Explore Further: - [Available Workflows](./01_Available_Workflows.md) - [Create Callbacks](./02_Create_Callbacks.md) - [Things to Know (!)](./03_Things_To_Know.md) - [Extend Workflows](./04_Extend_Workflows.md) --- ## Order Purchasable For items to be added to a Cart, Order, or Quote, they must implement the interface [```OpenDxp\Ecommerce\Component\Order\Model\PurchasableInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Model/PurchasableInterface.php). This concept of Purchasable decouples the Ecommerce Bundle's Order Component from the Product Component, offering flexibility in the types of objects that can be used in the Cart, Quote, or Order. > **Note**: A Purchasable item does not have a direct price. Instead, create a class that > implements [```OpenDxp\Ecommerce\Component\Order\Calculator\PurchasablePriceCalculatorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Calculator/PurchasablePriceCalculatorInterface.php) > to calculate its price. ### Implementation of a New Purchasable Price Calculator To implement a new custom Purchasable Price Calculator, adhere to the interface [```OpenDxp\Ecommerce\Component\Order\Calculator\PurchasablePriceCalculatorInterface```](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Order/Calculator/PurchasablePriceCalculatorInterface.php). #### Example: ProductSetCalculator This example creates a `ProductSetCalculator`, which calculates prices for each product in a set: ```php getStateMachineManager()->get($order, 'opendxp_ecommerce_order_invoice'); $workflow->apply($order, OrderInvoiceTransitions::TRANSITION_REQUEST_INVOICE); $order = ''; /** @var InvoiceInterface $invoice */ $invoice = $this->container->get('opendxp_ecommerce.factory.order_invoice')->createNew(); $invoice->setState(InvoiceStates::STATE_NEW); $items = []; $invoice = $this->get('opendxp_ecommerce.order.transformer.order_to_invoice')->transform($order, $invoice, $items); ``` --- ## Invoice The Ecommerce Bundle comes with an Invoice creation feature. This means, it can create Invoices for Orders based on Workflow States. --- ## Shipment Creation ### Add a Shipment to an Order ```php /** * Note: * * The TRANSITION_REQUEST_SHIPMENT transition can only be applied once. * Only dispatch it with the creation of the first shipment. * This transition will inform the order shipment workflow that it's ready to initiate the shipment processing. */ $workflow = $this->getStateMachineManager()->get($order, 'opendxp_ecommerce_order_shipment'); $workflow->apply($order, OrderShipmentTransitions::TRANSITION_REQUEST_SHIPMENT); $order = ''; /** @var ShipmentInterface $shipment */ $shipment = $this->container->get('opendxp_ecommerce.factory.order_shipment')->createNew(); $shipment->setState(ShipmentStates::STATE_NEW); $items = []; $shipment = $this->get('opendxp_ecommerce.order.transformer.order_to_shipment')->transform($order, $shipment, $items); ``` --- ## Shipment The Ecommerce Bundle comes with a Shipment (Delivery Slip) creation feature. This means, it can create Shipments for Orders based on Workflow States. --- ## Cart Commands The Ecommerce Bundle provides command line utilities to manage and expire abandoned carts. ### Expire Abandoned Carts To manage cart expiration via the command line, use the following commands: ???bash ## Delete only anonymous carts $ bin/console opendxp-ecommerce:cart:expire --anonymous ## Delete only user carts $ bin/console opendxp-ecommerce:cart:expire --user ## Delete carts older than 20 days $ bin/console opendxp-ecommerce:cart:expire --days=20 ??? ### Expire Abandoned Carts via Maintenance Job By default, the automatic expiration of abandoned carts is disabled. To enable this feature, set an expiration date in the configuration: ```yml opendxp_ecommerce_storage_list: list: order: expiration: params: cart: days: 20 params: anonymous: true customer: false ``` For more information on automation, refer to the [Automation Documentation](../../02_User_Documentation/10_Automation/index.md). --- ## Order Template/Twig Helper The Ecommerce Bundle provides a Twig filter for obtaining the current state of an order. ### Order State To get the current state of an order, use the following Twig filter: ```twig {{ dump(order|opendxp_ecommerce_order_state) }} ``` --- ## Orders(Development) Managing orders effectively is a cornerstone of successful eCommerce operations. In the Ecommerce Bundle, the order management system is designed to be robust, flexible, and user-friendly, ensuring that every aspect of order processing, from creation to fulfillment, is handled efficiently. This guide aims to provide an in-depth understanding of how the Ecommerce Bundle handles orders, covering the entire lifecycle of an order. You'll learn about the tools and features available for managing orders, customizing workflows, and enhancing the overall efficiency of your eCommerce platform. --- ## Carrier Managing carriers is an essential aspect of eCommerce logistics. This guide details how to create, read, update, and delete carriers via the API. ### Create To create a new carrier via the API: ```php $newCarrier = $container->get('opendxp_ecommerce.factory.carrier')->createNew(); ``` After creating a new Carrier instance, persist it using: ```php $container->get('opendxp_ecommerce.manager.carrier')->persist($newCarrier); $container->get('opendxp_ecommerce.manager.carrier')->flush(); ``` You now have a newly persisted Carrier. ### Read To query for carriers: ```php $carrierRepository = $container->get('opendxp_ecommerce.repository.carrier'); $queryBuilder = $carrierRepository->createQueryBuilder('c'); // Create your query // Get the result $carriers = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing carrier: ```php // Fetch Carrier $carrier = $carrierRepository->findById(1); $carrier->setName('DHL'); // Persist changes $container->get('opendxp_ecommerce.manager.carrier')->persist($carrier); $container->get('opendxp_ecommerce.manager.carrier')->flush(); ``` ### Delete To delete an existing carrier: ```php // Fetch Carrier $carrier = $carrierRepository->findById(1); // Remove Carrier $container->get('opendxp_ecommerce.manager.carrier')->remove($carrier); $container->get('opendxp_ecommerce.manager.carrier')->flush(); ``` --- ## Carrier Discovery In the Ecommerce Bundle, carrier discovery for a given shippable item is facilitated through a specialized service. This service is responsible for identifying the available carriers that can handle the shipping of a specific item. ### Service Implementation The carrier discovery service implements the interface `OpenDxp\Ecommerce\Bundle\ShippingBundle\Discover\ShippableCarriersDiscoveryInterface`. This interface is crucial for determining suitable carriers based on the characteristics and requirements of the shippable item. The service implementing this interface is registered with the service ID `opendxp_ecommerce.carrier.discovery`. It plays a pivotal role in the shipping process, ensuring that each shippable item is matched with appropriate and available shipping options. --- ## Carrier Price Calculation In the Ecommerce Bundle, the calculation of shipping prices for various carriers involves multiple methods. These methods are crucial for determining the appropriate shipping cost for a carrier based on the specifics of a given cart. ### Calculator Implementation To calculate shipping prices, a Calculator must implement the interface `OpenDxp\Ecommerce\Component\Shipping\Calculator\CarrierPriceCalculatorInterface`. This interface defines the necessary functionality for calculating shipping costs. Calculators should be registered in the container with the tag `opendxp_ecommerce.shipping.price_calculator`, and should include a `type` attribute and a `priority`. This registration process ensures that the Ecommerce Bundle recognizes and utilizes the calculator correctly during the shipping price calculation process. ### Default Implementation The default implementation for carrier price calculation is based on [Shipping Rules](../02_Shipping_Rules/index.md). This method takes into account various rules defined for shipping, which can include factors like the weight of the cart, the destination, and other relevant criteria. By using these rules, the ecommerce bundle can accurately calculate the shipping price for different carriers, ensuring a fair and consistent approach to shipping costs. --- ## Carriers(Shipping) Effective management of carriers is a vital component of any eCommerce operation. The Ecommerce Bundle offers a robust and flexible system for handling carriers, encompassing everything from the creation of new carrier records to complex calculations for shipping costs. This guide is designed to walk you through the various functionalities and features related to carriers. ### Key Areas of Carrier Management The following sections provide detailed insights and instructions on different aspects of managing carriers: - **[Create, Read, Update, Delete (CRUD)](./01_CRUD.md)**: This section covers the basic operations for carrier management, including how to create new carriers, read their details, update their information, and delete them when necessary. - **[Carrier Discovery](./02_Carrier_Discovery.md)**: Discover how the Ecommerce Bundle identifies and selects appropriate carriers for different shipping requirements. This process is crucial for ensuring that each order is matched with the most suitable carrier, based on factors like destination, size, and weight. - **[Price Calculation](./03_Price_Calculation.md)**: Learn about the methods and algorithms used to calculate shipping costs for different carriers. This section delves into the complexities of shipping price calculation, ensuring that costs are accurately and fairly determined. --- ## Shipping Rules(Shipping) The Ecommerce Bundle provides a robust set of default conditions and actions for shipping rules, enabling you to tailor the shipping process according to various criteria and actions. Additionally, the Ecommerce Bundle allows for the extension of these rules through custom actions and conditions. ### Default Conditions and Actions #### Default Conditions The Ecommerce Bundle includes a variety of predefined conditions for shipping rules: - **Currencies**: Rules based on currency type. - **Customer Groups**: Rules targeting specific customer groups. - **Customers**: Rules applicable to individual customers. - **Stores**: Rules for specific store locations. - **Zones**: Rules pertaining to geographical zones. - **Amount**: Rules based on the amount in the cart. - **Categories**: Rules for specific product categories. - **Countries**: Rules for shipments to specific countries. - **Dimension**: Rules based on the dimensions of the products. - **Post Codes**: Rules for specific postal code areas. - **Products**: Rules applicable to individual products. - **Shipping Rule**: Rules that trigger based on other shipping rules. - **Weight**: Rules based on the weight of the cart items. - **Nested**: Complex rules combining multiple conditions. #### Default Actions The default actions included are: - **Addition Amount**: Add a fixed amount to the shipping cost. - **Addition Percent**: Add a percentage to the shipping cost. - **Discount Amount**: Apply a discount amount to the shipping cost. - **Discount Percent**: Apply a discount percentage to the shipping cost. - **Price**: Set a fixed price for shipping. - **Shipping Rule**: Trigger other shipping rules. ### Extending Conditions and Actions The Ecommerce Bundle also provides options to extend these default rules with custom conditions and actions: - **Custom Actions **: [Learn how to add custom actions to your shipping rules](../../01_Extending_Guide/04_Extending_Rule_Actions.md). - **Custom Conditions **: [Discover how to create custom conditions for more tailored shipping rules](../../01_Extending_Guide/05_Extending_Rule_Conditions.md). --- ## Shipping(Development) Efficient and accurate shipping management is a critical component of any eCommerce operation. In the Ecommerce Bundle, shipping and shipping calculation are handled through a well-structured and flexible system, designed to cater to a wide range of shipping scenarios and requirements. This guide is intended to walk you through the various aspects of shipping within the Ecommerce Bundle framework, from the management of carriers to the application and customization of shipping rules. Whether you're setting up shipping for the first time or looking to refine your shipping strategies, this guide provides the necessary insights and instructions. ### Key Components of Shipping Management Here are the main areas covered in this guide: - **[Carriers](./01_Carrier/index.md)**: Discover how the Ecommerce Bundle manages carriers, including the creation, configuration, and management of different carriers. Learn about the various features and options available for handling carrier-related aspects of shipping. - **[Shipping Rules](./02_Shipping_Rules/index.md)**: Explore the world of shipping rules. This section delves into how you can define and apply shipping rules, which are essential for calculating shipping costs and determining shipping logistics based on various criteria such as destination, weight, and product type. --- ## Index Interpreter In the Ecommerce Bundle, Index Interpreters are used to prepare and transform data for the product index. You can utilize existing interpreters or create custom ones to fit your specific needs. ### Existing Ecommerce Bundle Interpreters The Ecommerce Bundle comes equipped with several built-in interpreters: - **Object**: Converts an object or an object array to relations and saves the values to the relations index. - **ObjectId**: Transforms an object into its ID. - **ObjectIdSum**: Calculates the sum of all IDs, which can be useful for similar products. - **ObjectProperty**: Calls a getter method on the value. - **Soundex**: Applies the PHP `soundex` function, useful for finding similar products. ### Creating a Custom Interpreter To create a custom interpreter, you'll need to develop two key components: #### 1. FormType for Input Data Create a FormType class to handle the input data for your interpreter: ```php namespace App\Ecommerce\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Type; final class MyInterpreterType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder .add('myInterpreterData', IntegerType::class, [ 'constraints' => [ new NotBlank(groups: ['opendxp_ecommerce']), new Type(type: 'numeric', groups: ['opendxp_ecommerce']), ], ]); } } ``` #### 2. Interpreter Interface Implementation Implement the `InterpreterInterface` to define how your interpreter processes data: ```php namespace App\Ecommerce\Index\Interpreter; use OpenDxp\Ecommerce\Component\Index\Interpreter\InterpreterInterface; class MyInterpreter implements InterpreterInterface { public function interpret($value, IndexableInterface $indexable, IndexColumnInterface $config, array $interpreterConfig = []) { // Interpretation logic goes here return $value; } } ``` #### 3. Registering the Custom Interpreter Register your new interpreter as a service with the tag `opendxp_ecommerce.index.interpreter`, specifying its type and form: ```yaml App\Ecommerce\Index\Interpreter\MyInterpreter: tags: - { name: opendxp_ecommerce.index.interpreter, type: my_interpreter, form-type: App\Ecommerce\Form\Type\MyInterpreterType } ``` With these steps, you can enhance the indexing process with custom logic, tailored to your specific requirements. --- ## Index Extension To enhance the flexibility and functionality of the product index, you can create extensions. These extensions allow for additional customization and optimization of the indexing process. ### Capabilities of Extensions Extensions enable you to: - Add additional "default" columns and their corresponding data to the index. - Apply pre-filters to a MySQL index for more refined data retrieval. ### Implementing Extensions To create an extension, implement one of the following interfaces depending on your needs: - **Column Extensions**: Implement the [`OpenDxp\Ecommerce\Component\Index\Extension\IndexColumnsExtensionInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Index/Extension/IndexColumnsExtensionInterface.php) if you want to add new columns to the index. - **MySQL Query Extensions**: For extending MySQL query capabilities, use the [`OpenDxp\Ecommerce\Bundle\IndexBundle\Extension\MysqlIndexQueryExtensionInterface`](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Bundle/IndexBundle/Extension/MysqlIndexQueryExtensionInterface.php). After implementing the appropriate interface, register your service with the tag `opendxp_ecommerce.index.extension`. #### Example of Creating an Extension Here's a brief example to illustrate how you might implement and register an index extension: ```php productClassName === $index->getClass(); } public function getSystemColumns(): array { return [ (new Column('categoryIds', Type::getType('string')))->setLength(190), (new Column('parentCategoryIds', Type::getType('string')))->setLength(190), (new Column('stores', Type::getType('string')))->setLength(190), ]; } public function getLocalizedSystemColumns(): array { return []; } public function getIndexColumns(IndexableInterface $indexable): array { if ($indexable instanceof ProductInterface) { $categoryIds = []; $parentCategoryIds = []; $categories = $indexable->getCategories(); $categories = is_array($categories) ? $categories : []; foreach ($categories as $c) { if ($c instanceof CategoryInterface) { $categoryIds[$c->getId()] = $c->getId(); $parents = $c->getHierarchy(); foreach ($parents as $p) { $parentCategoryIds[] = $p->getId(); } } } return [ 'categoryIds' => ',' . implode(',', $categoryIds) . ',', 'parentCategoryIds' => ',' . implode(',', $parentCategoryIds) . ',', 'stores' => ',' . @implode(',', $indexable->getStores()) . ',', ]; } return []; } } ``` And then register the extension in your service configuration: ```yaml services: App\Ecommerce\Index\Extension\MyCustomExtension: tags: - { name: opendxp_ecommerce.index.extension } ``` With these extensions, you can significantly enhance the capabilities of your product index, making it more adaptable to your specific eCommerce needs. --- ## Index for Layered Navigation Creating an effective layered navigation (faceted navigation) requires setting up an index of your products. This index plays a crucial role in enhancing search and filter capabilities within your product catalog. ### Create a New Index The Ecommerce Bundle currently supports the following types of indexes: - **MySQL**: Utilizes a MySQL database for indexing. - ~~Elasticsearch~~: Currently not supported. #### Adding Fields to the Index To add new fields to the index: 1. Simply drag and drop the field from the left tree into the right tree. ![Index Fields](img/fields.png) #### Field Properties Each field in the index requires certain properties to be configured: ![Field](img/field.png) | Field | Description | |------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Key | The OpenDxp field name. | | Name | The name of the field in the index. | | Getter Class | Important for field-types like "Localized Fields", "Classification Store", "Object Brick", and "Field Collection". Used to retrieve the correct value for the index. | | [Interpreter](./01_Interpreter.md) | Transforms values before they are stored in the index, e.g., resolving dependencies or creating a similarity index. | | Type | The field type in the index, depending on the index type | | Getter Config | Configuration options for the Getter, such as language for Localized Fields. | ### Re-Indexing Products After modifying the index, it's necessary to re-index your products using a CLI command: ```bash $ php bin/console opendxp-ecommerce:index ``` For selective re-indexing, specify IDs or names of the indices as arguments. For example, to re-index only indices with IDs 1 and 2 and the index named "Products": ```bash php bin/console opendxp-ecommerce:index 1 2 Products ``` ### Messenger Remember to process the queue opendxp_ecommerce_index to automatically index your products when they are saved. This ensures that your product index remains up-to-date with all the latest changes. ```bash bin/console messenger:consume opendxp_ecommerce_index ``` --- ## Filter - Create Custom Filter **1**. We need to create 2 new files: - FormType for processing the Input Data - And a FilterConditionProcessorInterface, which checks if a cart fulfills the condition. ```php namespace App\Ecommerce\Form\Type\Condition; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Type; final class MyFilterCondition extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('myData', IntegerType::class, [ 'constraints' => [ new NotBlank(groups: ['opendxp_ecommerce']), new Type(type: 'numeric', groups: ['opendxp_ecommerce']), ], ]) ; } } ``` ```php namespace App\Ecommerce\Filter; use OpenDxp\Ecommerce\Component\Address\Model\AddressInterface; use OpenDxp\Ecommerce\Component\Core\Model\CarrierInterface; class MyFilterCondition extends FilterConditionProcessorInterface { public function prepareValuesForRendering(FilterConditionInterface $condition, FilterInterface $filter, ListingInterface $list, $currentFilter) { //Prepare values for rendering HTML } public function addCondition(FilterConditionInterface $condition, FilterInterface $filter, ListingInterface $list, $currentFilter, ParameterBag $parameterBag, $isPrecondition = false) { //Add Condition to Listing return $currentFilter; } } ``` **2**. Register MyFilterCondition as service with tag ```opendxp_ecommerce.filter.condition_type```, type and form. We are also adding the ```autoconfigure: false``` to prevent autoconfiguration of the service. (This is only needed if you use autoconfiguration in your project) ```yaml App\Ecommerce\Filter\MyFilterCondition: autoconfigure: false tags: - { name: opendxp_ecommerce.filter.condition_type, type: app-my-filter, form-type: App\Filter\Form\Type\Condition\MyFilterCondition} ``` --- ## Filter Configuration After setting up the product index, the next step is to configure filters. These filters enhance the user experience by enabling customers to easily find products based on various criteria. ### Creating a New Filter Filters can be tailored for different categories in your store. Each filter comprises settings, pre-conditions, specific filters, and options for similar products. Custom filters can also be created as detailed in [Custom Filters](01_Custom_Filter.md). #### Filter Settings Configure the basic settings of your filter: ![Filter Settings](./img/filter-settings.png) | Field | Description | |------------------|----------------------------------------------------------------------------------------------------| | Name | The name of the filter set. | | Index | The index to be used for filtering. | | Order | The default order in which products are displayed. | | Order Key | The index field used for sorting products. | | Results per Page | Number of products displayed per page. This can be set using shop settings or overridden manually. | #### Pre-Conditions Define pre-filters for the index: ![Filter Pre-Conditions](./img/filter-preconditions.png) These pre-filters refine the initial dataset before any user-driven filtering. #### Conditions Set up various filters that will be available to customers: ![Filter Conditions](./img/filter-conditions.png) The Ecommerce Bundle supports four main types of filters: ##### Select Condition - **Description**: A dropdown field allowing the selection of a single option. - **Example**: ![Filter Condition Select](./img/filter-condition-select.png) ##### Multiselect Condition - **Description**: A list where multiple options can be selected. - **Example**: ![Filter Condition Multiselect](./img/filter-condition-multiselect.png) ##### Range Condition - **Description**: A slider representing a range, with automatic calculation of MIN and MAX values. - **Example**: ![Filter Condition Range](./img/filter-condition-range.png) ##### Boolean Condition - **Description**: A set of checkboxes for selecting various boolean (true/false) options. - **Example**: ![Filter Condition Boolean](./img/filter-condition-boolean.png) With these filter configurations, customers can easily navigate and discover products in your store, enhancing their shopping experience. --- ## Index and Filter In the Ecommerce Bundle, managing indices and filters is essential for creating an efficient and user-friendly shopping experience. Indices enable the organization and retrieval of product data effectively, while filters allow customers to navigate through your product catalog seamlessly based on specific criteria. This guide is designed to provide you with a comprehensive understanding of how the Ecommerce Bundle handles indices and filters, from setting them up to customizing them to meet your eCommerce platform's needs. ### Exploring Indices and Filters The guide is divided into two main sections: 1. **[Indices](./01_Index/index.md)**: Learn about the creation and management of product indices. This section covers how indices are structured, how they can be customized, and their role in enhancing the product search and retrieval process. 2. **[Filters](./02_Filter/index.md)**: Dive into the world of filters, which are integral to providing customers with a streamlined shopping experience. This section explains how to set up different types of filters, such as select, multiselect, range, and boolean, and how they can be used to refine product searches on your eCommerce platform. --- ## Notification Rule Custom Actions The Ecommerce Bundle supports the integration of custom actions into its notification system, offering enhanced flexibility and the ability to tailor notifications to specific operational needs. ### Implementing Custom Actions For comprehensive instructions on how to develop and integrate custom actions into the Ecommerce Bundle's notification rules, please refer to the following guide: - **[Adding Custom Actions to Notification Rules](../01_Extending_Guide/04_Extending_Rule_Actions.md)**: This document provides detailed steps and insights on creating custom actions, enabling you to customize how notifications are processed and dispatched. --- ## Notification Rule Custom Conditions The Ecommerce Bundle's notification system is designed to be flexible and extendable, allowing you to introduce custom conditions to tailor the notification rules to your specific business requirements. ### Adding Custom Conditions For detailed guidance on how to add custom conditions to your notification rules, refer to the following resource: - **[Adding Custom Conditions to Notification Rules](../01_Extending_Guide/05_Extending_Rule_Conditions.md)**: This document provides a step-by-step approach to creating and integrating custom conditions into the Ecommerce Bundle notification framework. --- ## Notification Rule Custom Type In the Ecommerce Bundle, creating custom notification types is facilitated by dynamically registering them using tag attributes on conditions and actions. This flexibility allows you to customize and extend the notification system to meet specific requirements. ### Implementing a Custom Notification Type To introduce a custom notification type, you can add a new condition or action and specify your unique type. This is achieved by defining a service in your YAML configuration and assigning the appropriate tags. #### Example: Defining a Custom Notification Condition Service Here's an example of defining a service for a custom notification condition: ```yaml services: App\Ecommerce\Notification\CustomNotificationCondition: tags: - { name: opendxp_ecommerce.notification_rule.condition, type: custom_condition, notification-type: custom, form-type: App\Ecommerce\Form\Type\Ecommerce\CustomConditionType } ``` --- ## Triggering Notification Events Triggering notification events is streamlined through the use of the `OpenDxp\Ecommerce\Component\Notification\Processor\RulesProcessorInterface`, implemented by the service `@opendxp_ecommerce.notification_rule.processor`. This processor is key to activating various notification types based on specific events. ### Example: Triggering an Order Event Consider an example where you need to trigger a notification for an order event. You'll need to provide relevant parameters that align with the notification type. Here’s how to trigger such an event for an order: ```php $this->rulesProcessor->applyRules('order', $event->getProposal(), [ 'fromState' => $event->getMarking()->getPlaces(), 'toState' => $event->getTransition()->getTos(), '_locale' => $order->getLocaleCode(), 'recipient' => $customer->getEmail(), 'firstname' => $customer->getFirstname(), 'lastname' => $customer->getLastname(), 'orderNumber' => $order->getOrderNumber(), 'transition' => $event->getTransition()->getName(), ]); ``` In this code snippet, the `applyRules` method of `RulesProcessorInterface` is called with the order event type and associated parameters like state transitions, locale, customer details, and the order number. #### Ecommerce Bundle Notification Handling Once the event is triggered with these parameters, the Ecommerce Bundle's notification system processes it according to the defined rules. This ensures the appropriate notifications are dispatched, maintaining effective communication and operational efficiency. --- ## Notification Rules In the Ecommerce Bundle, Notification Rules are pivotal for managing various types of notifications triggered within the system. These rules cater to a range of scenarios, ensuring that the right notifications are dispatched under specific conditions. ### Overview of Notification Types The Ecommerce Bundle handles notifications for the following types: - **Order** - **Quote** - **Invoice** - **Shipment** - **User** - **Payment** Let's explore each notification type and their respective conditions and actions: #### Order Notifications ##### Allowed Conditions | Name | Description | |---------------------|------------------------------------------------------------------------------------| | Invoice State | Triggered if a specific Invoice State is active. | | Invoice Transition | Triggered if a specific Invoice Transition has been applied. | | Payment State | Triggered if a specific Payment State is active. | | Payment Transition | Triggered if a specific Payment Transition has been applied. | | Shipping State | Triggered if a specific Shipping State is active. | | Shipping Transition | Triggered if a specific Shipping Transition has been applied. | | Order State | Triggered if a specific Order State is active. | | Order Transition | Triggered if a specific Order Transition has been applied. | | Carriers | Triggered if a specific Carrier has been selected in the Order. | | Comment | Triggered if a Comment Action has been applied. Available Types: `create comment`. | ##### Allowed Actions | Name | Description | |-------------|--------------------------------------------------| | Order Email | Email notification with Order Object. | | Email | General Email notification without Order Object. | ##### Available Placeholder Keys for Email Templates | Key | Value | |-------------|-------------------------------------------| | object | Object of type `OrderInterface`. | | fromState | State identifier transitioning away from. | | toState | State identifier transitioning to. | | transition | Used transition. | | _locale | Used locale. | | recipient | Customer Email Address. | | firstname | Customer Firstname. | | lastname | Customer Lastname. | | orderNumber | Order Number. | #### (And similar sections for Shipment, Invoice, Payment, User, and Quote) ### Custom Implementation For bespoke notification scenarios, custom implementation of notification rules is possible. Learn more about this in [Custom Notification Types](./03_Custom_Types.md). ### Extending Ecommerce Bundle Notification Rules The Ecommerce Bundle also allows for the extension and customization of notification rules: - **[Custom Actions](./01_Custom_Actions.md)**: Learn how to create custom actions for your notifications. - **[Custom Conditions](./02_Custom_Conditions.md)**: Discover how to implement custom conditions for more tailored notifications. - **[Custom Types](./03_Custom_Types.md)**: Explore how to set up custom notification types for specialized scenarios. - **[Triggering Notifications](./04_Triggering.md)**: Understand the mechanisms behind triggering notifications in the Ecommerce Bundle. --- ## Payment Providers A Payment Provider represents a method your customer uses to pay during the checkout process. It links to a specific gateway with custom configurations. Each payment method is configured separately using the payment method form in the admin panel. ### Taxes on the Payment Fee A payment provider rule can add a fee to the cart, for example for cash on delivery. The fee is taxed the same way as the shipping costs of a [carrier](../../02_User_Documentation/05_Shipping/01_Carriers.md), and you set it up the same way too. Each payment provider has a **Tax Calculation** setting with two options: - **based on cart items** is the default. The fee is split across the tax rates of the products in the cart, weighted by their totals. If the cart only holds products with a reduced rate, the whole fee gets the reduced rate. In most countries a payment fee belongs to the goods and shares their tax rate. This option follows that rule. - **based on tax rule** taxes the fee with the tax rule group you select on the payment provider. Use it when the fee is a service of its own with a fixed rate. You enter the fee like a shipping price. A store with gross prices treats it as a gross amount, and a store with net prices treats it as a net amount. #### Add Your Own Tax Calculation A project can add its own option, for example one that taxes the fee at the highest rate in the cart. Write a service that implements `OpenDxp\Ecommerce\Component\Payment\Taxation\TaxCalculationStrategyInterface`: ```php namespace App\Ecommerce\Payment; use OpenDxp\Ecommerce\Component\Address\Model\AddressInterface; use OpenDxp\Ecommerce\Component\Payment\Model\PayableInterface; use OpenDxp\Ecommerce\Component\Payment\Model\PaymentProviderInterface; use OpenDxp\Ecommerce\Component\Payment\Taxation\TaxCalculationStrategyInterface; final class HighestRateTaxCalculationStrategy implements TaxCalculationStrategyInterface { public function calculatePaymentTax( PayableInterface $payable, PaymentProviderInterface $paymentProvider, AddressInterface $address, int $paymentAmount, array $context = [], ): array { // Return the tax items of the fee. } } ``` Then register it with a type: ```yaml services: App\Ecommerce\Payment\HighestRateTaxCalculationStrategy: tags: - { name: opendxp_ecommerce.payment.tax_calculation_strategy, type: highestRate } ``` The admin lists the new option under the translation key `opendxp_ecommerce_payment_tax_strategy_highestRate`. ### Payment Gateway Configuration #### Payment Gateways with Ecommerce Bundle Bridges To configure a payment gateway that already has an Ecommerce Bundle bridge: 1. **Create a Configuration Form Type**: Look at the existing configuration form types for gateways like Paypal and Sofort for reference. 2. **Register the Configuration Form Type**: Use the `opendxp_ecommerce.gateway_configuration_type` tag to make the gateway available in the admin panel's dropdown. > For guidance on configuration form types, refer to the [Payum documentation](https://github.com/Payum/Payum). #### Integrating Other Payment Gateways To learn more about integrating other payment gateways, consult the [Payum docs](https://github.com/Payum/Payum). You may also need to add configuration in `app/config/config.yml` for the gateway’s factory: ```yaml payum: gateways: yourgateway: factory: yourgateway ``` Example: Adding Sofort as a Payment Gateway Factory To add Sofort as a new gateway configuration, create the following files: 1. **Form Type for Configuration Values**: ```php namespace App\Ecommerce\Form\Type; use Symfony\Component\Form\AbstractType; // ... other use statements ... final class SofortGatewayConfigurationType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { // Form build logic... } } ``` Then, register the FormType in the service container: ```yaml services: App\Ecommerce\Form\Type\SofortGatewayConfigurationType: tags: - { name: opendxp_ecommerce.gateway_configuration_type, type: sofort } - { name: form.type } ``` 2. **ExtJs Form for Sofort**: Create a JavaScript file for the ExtJs Form: ```js // public/ecommerce/js/sofort.js opendxp.registerNS('opendxp_ecommerce.provider.gateways.sofort'); opendxp_ecommerce.provider.gateways.sofort = Class.create(opendxp_ecommerce.provider.gateways.abstract, { getLayout: function (config) { // Form layout logic... } }); ``` Register the new JavaScript file: ```yaml opendxp_ecommerce_payment: opendxp_admin: js: sofort_gateway: '/ecommerce/js/sofort.js' ``` After reloading OpenDxp, you should see the new Factory available. --- ## Encrypt Payment Gatway Configuration 1. Create a new file in the root of your project and name it `encrypt.php`. ```php saveToAsciiSafeString()); ``` 2. Store your key in a safe place and add it to your `.env` file. ```env OPENDXP_ECOMMERCE_PAYUM_ENCRYPT_KEY="YOUR KEY" ``` 3. Add the following code to your `config/config.yaml` file. ```yaml payum: dynamic_gateways: encryption: defuse_secret_key: "%env(OPENDXP_ECOMMERCE_PAYUM_ENCRYPT_KEY)%" ``` 4. Existing payment gateway configs will be automatically encrypted when updated. New payment gateway configs will be encrypted by default. --- ## Payum Providers The Ecommerce Bundle utilizes Payum, a versatile payment abstraction library, to support a wide range of payment providers. Payum offers integration with various payment gateways, enhancing the flexibility and options available for payment processing. ### List of Supported Payum Payment Providers You can find a comprehensive list of all the payment providers supported by Payum at the following link: - **[Supported Payum Payment Providers](https://github.com/Payum/Payum/blob/master/docs/supported-gateways.md)**: This resource details each payment provider compatible with Payum, offering a broad selection to meet diverse payment processing needs. --- ## Payment The Ecommerce Bundle features a highly flexible payment management system, supporting a wide range of gateways (payment providers). It utilizes [Payum](https://github.com/payum/payum), a payment abstraction library, to handle various aspects of payment processing, including capturing, refunding, and recurring payments. ### Available Payment Gateways for the Ecommerce Bundle The Ecommerce Bundle supports several payment gateways, each with its own set of features and capabilities: | Name | State | Link | Support | Offsite | Supports Server-Notification | Supports Refund | |-----------------|--------|--------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------|---------|------------------------------|-----------------| | **Heidelpay** | stable | [Github](https://github.com/open-dxp/PayumHeidelpayBundle) | PayPal, Klarna Sofort, Credit Card | No | Yes | No | | **SaferPay** | stable | [Github](https://github.com/open-dxp/PayumSaferpayBundle) | [Supported Payment Methods](https://saferpay.github.io/sndbx/index.html#paymentmethods) | Yes | Yes | Partially | | **PostFinance** | stable | [Github](https://github.com/open-dxp/PayumPostFinanceBundle) | PostFinance Card, PostFinance E-Finance, Visa, MasterCard, Diners Club, American Express, JCB, PayPal, TWINT | Yes | Yes | No | | **PowerPay** | dev | [Github](https://github.com/open-dxp/PayumPowerpayBundle) | invoice, automatic credit check | No | No (not required) | No | | **CuraBill** | dev | [Github](https://github.com/open-dxp/PayumCurabillBundle) | invoice, instalments via iframe | No | No (not required) | No | ### Payment Model Each payment in ecommerce bundle, whether successful or failed, is represented by a payment model. This model contains essential information and a reference to the relevant order. ### Creating a Payment Programmatically To create a new payment method programmatically, use a factory and assign a unique code: ```php $payment = $this->container->get('opendxp_ecommerce.factory.payment')->createNew(); $payment->setOrder($order); $payment->setCurrencyCode('EUR'); $this->container->get('opendxp_ecommerce.repository.payment')->add($payment); ``` ### Additional Resources For more information on payment integration and management: - **[Payment Provider](./01_Payment_Provider.md)** - **[Encrypt Payment Gateway Configuration](./02_Encrypt_Config.md)** - **[Payum Providers](./03_Payum_Providers.md)** --- ## Stores(Stores) The Ecommerce Bundle provides a straightforward API for managing stores, allowing for the creation, reading, updating, and deletion of store entities. ### Create To create a new Store via API: ```php $newStore = $container->get('opendxp_ecommerce.factory.store')->createNew(); ``` Once you have instantiated a new Store, persist it as follows: ```php $container->get('opendxp_ecommerce.manager.store')->persist($newStore); $container->get('opendxp_ecommerce.manager.store')->flush(); ``` You now have a newly persisted Store in your system. ### Read To query for existing Stores: ```php $storeRepository = $container->get('opendxp_ecommerce.repository.store'); $queryBuilder = $storeRepository->createQueryBuilder('c'); // Create your query // Retrieve the result $stores = $queryBuilder->getQuery()->getResult(); ``` ### Update To update an existing Store: ```php // Fetch the Store $store = $storeRepository->findById(1); $store->setName('Euro'); // Persist changes $container->get('opendxp_ecommerce.manager.store')->persist($store); $container->get('opendxp_ecommerce.manager.store')->flush(); ``` ### Delete To delete an existing Store: ```php // Fetch the Store $store = $storeRepository->findById(1); // Remove the Store $container->get('opendxp_ecommerce.manager.store')->remove($store); $container->get('opendxp_ecommerce.manager.store')->flush(); ``` --- ## Store Context For the Ecommerce Bundle to determine the current store the visitor or customer comes from it uses a concept called context and context resolver. ### Context | Name | Priority | Tag | Description | |---------------------------------------------------------------------------------------------------------------------------------|----------|------------------------------------|------------------------------------------| | [FixedStoreContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/FixedStoreContext.php) | 2 | `opendxp_ecommerce.context.store ` | Used for testing purposes | | [StoreContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/RequestBased/StoreContext.php) | 1 | `opendxp_ecommerce.context.store ` | Load a store from given request resolver | ### Resolver | Name | Priority | Tag | Description | |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|----------------------------------------------------------|-----------------------------------------------------| | [SiteBasedRequestResolver](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/RequestBased/SiteBasedRequestResolver.php) | 100 | `opendxp_ecommerce.context.store.request_based.resolver` | Determines a store by a given opendxp frontend site | | [OpenDxpAdminSiteBasedRequestResolver](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/RequestBased/OpenDxpAdminSiteBasedRequestResolver.php) | 200 | `opendxp_ecommerce.context.store.request_based.resolver` | Determines a store by a given document in backend | These resolver take care about finding the correct store for the current request.a# Store Context The Ecommerce Bundle utilizes the concept of context and context resolver to determine the current store based on the visitor or customer's location or preferences. ### Context Contexts are used to identify the appropriate store for the current request: | Name | Priority | Tag | Description | |---------------------------------------------------------------------------------------------------------------------------------|----------|------------------------------------|------------------------------------------| | [FixedStoreContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/FixedStoreContext.php) | 2 | `opendxp_ecommerce.context.store ` | Used for testing purposes | | [StoreContext](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/RequestBased/StoreContext.php) | 1 | `opendxp_ecommerce.context.store ` | Load a store from given request resolver | ### Resolver Resolvers are responsible for finding the correct store based on specific criteria: | Name | Priority | Tag | Description | |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|----------------------------------------------------------|-----------------------------------------------------| | [SiteBasedRequestResolver](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/RequestBased/SiteBasedRequestResolver.php) | 100 | `opendxp_ecommerce.context.store.request_based.resolver` | Determines a store by a given OpenDxp frontend site | | [OpenDxpAdminSiteBasedRequestResolver](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Store/Context/RequestBased/OpenDxpAdminSiteBasedRequestResolver.php) | 200 | `opendxp_ecommerce.context.store.request_based.resolver` | Determines a store by a given document in backend | ### Create a Custom Resolver To create a custom Store Context: 1. Implement the interface `OpenDxp\Ecommerce\Component\Store\Context\StoreContextInterface`. 2. Define the `getStore` method to return a `OpenDxp\Ecommerce\Component\Store\Model\StoreInterface` or throw a `OpenDxp\Ecommerce\Component\Store\Context\StoreNotFoundException`. 3. Register your context using the tag `opendxp_ecommerce.context.store` with an optional `priority` attribute. ### Create a Request-Based Resolver The Ecommerce Bundle supports request-based store context resolvers: 1. Implement the `OpenDxp\Ecommerce\Component\Store\Context\RequestBased\RequestResolverInterface`. 2. Define the `findStore` method to return a store or null. 3. Register this resolver using the tag `opendxp_ecommerce.context.store.request_based.resolver` with an optional `priority` attribute. ### Example: Implementing a Document-Based Store Context To resolve a Store based on a OpenDxp document, such as differentiating between `/de` and `/en` sites: 1. Create the RequestBased Store Context: ```php namespace App\Ecommerce\Store\Context; // ... other use statements ... final class DocumentBasedRequestRequestResolver implements RequestResolverInterface { // Implementation details... } ``` 2. Configure the service in `config/services.yaml`: ```yaml services: App\Ecommerce\Store\Context\DocumentBasedRequestRequestResolver: arguments: - '@opendxp_ecommerce.repository.store' tags: - { name: opendxp_ecommerce.context.store.request_based.resolver, priority: 300 } ``` With this setup, the Ecommerce Bundle will dynamically resolve the current store based on the site being accessed. ### Create a Custom Resolver A Store Context needs to implement the interface `OpenDxp\Ecommerce\Component\Store\Context\StoreContextInterface`. This interface consists of one method called `getStore` which returns a `OpenDxp\Ecommerce\Component\Store\Model\StoreInterface` or throws an `OpenDxp\Ecommerce\Component\Store\Context\StoreNotFoundException`. To register your context, you need to use the tag `opendxp_ecommerce.context.store` with an optional `priority` attribute. ### Create a Request based Resolver The Ecommerce Bundle already implements Request based store context resolver. So if your context depends on the current request, you can create a custom RequestBased resolver. To do that, implement the interface `OpenDxp\Ecommerce\Component\Store\Context\RequestBased\RequestResolverInterface` with the method `findStore`. This method either returns a store or null. To register this resolver, use the tag: `opendxp_ecommerce.context.store.request_based.resolver` with an optional `priority` attribute. ### Example To implement a StoreContext based on the OpenDxp Document — so that being on site `/de` resolves to `Store DE`, if we are on page `/en` we want to resolve to Store `Store EN`: **1**: First of all we need to create our RequestBased Store Context: ```php storeRepository = $storeRepository; } public function findStore(Request $request): ?StoreInterface { if (substr($request->getPathInfo(), 0, 3) === '/en') { return $this->storeRepository->find(1); } if (substr($request->getPathInfo(), 0, 3) === '/de') { return $this->storeRepository->find(2); } return null; } } ``` Now we need to configure the service in `config/services.yaml` ```yaml services: App\Ecommerce\Store\Context\DocumentBasedRequestRequestResolver: arguments: - '@opendxp_ecommerce.repository.store' tags: - { name: opendxp_ecommerce.context.store.request_based.resolver, priority: 300 } ``` The Ecommerce Bundle will now resolve the current Store based on the OpenDxp Site being accessed. --- ## Stores Theming The Ecommerce Bundle's multi-store environment is designed to support different themes for each store, enabling a diverse and unique visual experience across your various storefronts. ### Customizing Themes for Each Store The flexibility to apply distinct themes to different stores allows for: - **Brand Consistency**: Tailor the look and feel of each store to align with specific brand guidelines and aesthetics. - **Targeted Customer Experience**: Create themes that resonate with the particular demographics or preferences of customers in each store. - **Visual Distinction**: Easily differentiate between various stores in a multi-store setup through unique thematic elements. ### Leveraging Sylius Theme Bundle The Ecommerce Bundle utilizes the Sylius Theme Bundle to manage templates, offering a robust and flexible solution for theming: - **Sylius Theme Bundle**: This bundle provides the underlying structure and functionality for theme management in the Ecommerce Bundle. It offers a comprehensive approach to creating and applying themes across different stores. - **Documentation**: For detailed information on how the Sylius Theme Bundle works and how to implement it within the Ecommerce Bundle, refer to the [Sylius Theme Documentation](https://docs.sylius.com/en/1.9/book/themes/themes.html). By incorporating the Sylius Theme Bundle, the Ecommerce Bundle equips you with the tools to craft distinct, immersive, and engaging themes for each of your stores, enhancing the overall shopping experience for your customers. --- ## Stores(Development) The Ecommerce Bundle's Stores functionality is a powerful feature that allows you to create and manage a multi-store eCommerce system within a single installation. This capability is particularly beneficial for businesses looking to cater to diverse market segments, such as a mix of B2C and B2B customers, or to offer different themes and experiences across various storefronts. ### Leveraging Multi-Store Capabilities The multi-store feature leverages OpenDxp's Multi Site functionality, enabling you to set up distinct stores with their own specific configurations, themes, and product selections. This allows for a high degree of customization and flexibility, enabling businesses to: - **Target Different Customer Segments**: Create separate stores for different types of customers, such as retail consumers and wholesale clients, each with tailored products, pricing, and shopping experiences. - **Offer Regional Variations**: Manage stores that cater to different geographical regions, each with localized content, currency, and payment methods. - **Customize Themes and Layouts**: Implement distinct themes and layouts for each store, ensuring a unique and branded experience that resonates with the specific audience of each store. - **Streamline Management**: Despite the diversity of stores, manage them all from a single OpenDxp installation, streamlining operations and maintaining consistency in backend processes. ### Ecommerce Bundle Store Features The Ecommerce Bundle provides various features and tools to effectively manage your multi-store setup: 1. **[Create, Read, Update, Delete (CRUD)](./01_CRUD.md)**: Detailed instructions for setting up new stores, as well as managing and updating existing ones. 2. **[Store Context](./02_Context.md)**: Insights into how the Ecommerce Bundle determines the current store context and how you can customize it for different scenarios. 3. **[Theming](./03_Theme.md)**: Guidance on applying and customizing themes for each store, enhancing the visual and user experience. #### Overview By utilizing the multi-store feature, the Ecommerce Bundle provides a scalable and flexible solution that caters to complex eCommerce requirements. Whether you're managing different brands, customer types, or regional variations, the Ecommerce Bundle's Stores functionality equips you with the tools to create a cohesive yet diverse eCommerce ecosystem. Explore each section to fully harness the power of multi-store capabilities. --- ## Custom Customer Management The Ecommerce Bundle utilizes OpenDxp Data Objects to manage customer information, enhancing it with a wrapper for increased dynamism and configurability. This approach leverages the Factory and Repository patterns for efficient data handling. ### Create To create a new customer, you need to use the Factory Service: ```php $customerFactory = $container->get('opendxp_ecommerce.factory.customer'); $customer = $customerFactory->createNew(); ``` After creating the customer object, you can set the necessary values. To save the new customer: ```php $customer->save(); ``` ### Read For retrieving customers, the Ecommerce Bundle provides a Repository Service: ```php $repository = $container->get('opendxp_ecommerce.repository.customer'); // Query by ID $customerWithIdOne = $repository->findById(1); // Get a Listing as you would in OpenDxp $list = $repository->getList(); $list->setCondition("active = 1"); $customers = $list->getObjects(); ``` ### Update Updating customer information follows the same process as in OpenDxp: ```php $repository = $container->get('opendxp_ecommerce.repository.customer'); // Query by ID $customerWithIdOne = $repository->findById(1); // Modify values $customerWithIdOne->setName('test'); $customerWithIdOne->save(); ``` ### Delete The deletion process is also similar to standard OpenDxp operations: ```php $repository = $container->get('opendxp_ecommerce.repository.customer'); // Query by ID $customerWithIdOne = the repository->findById(1); $customerWithIdOne->delete(); ``` --- ## Customer Context The Ecommerce Bundle's approach to customer security leverages the [Symfony Firewall](https://symfony.com/doc/current/components/security/firewall.html) for authentication purposes. To enhance flexibility, the Ecommerce Bundle has wrapped this functionality in a context-based system. This setup allows for various methods of determining customer context. ### Implemented Contexts for Customer Determination The Ecommerce Bundle includes specific contexts for customer identification, such as: - **Security Token Based**: A method that uses security tokens for customer identification. More details can be found [here](https://github.com/open-dxp/ecommerce-bundle/blob/1.x/src/Component/Customer/Context/RequestBased/TokenBasedRequestResolver.php). ### Creating a Custom Resolver In scenarios where the default customer context determination method does not fit your requirements, the Ecommerce Bundle allows the creation of custom resolvers. #### Implementing the Custom Resolver 1. **Interface Implementation**: Your custom resolver should implement the `OpenDxp\Ecommerce\Component\Customer\Context\CustomerContextInterface`. The interface includes the `getCustomer` function, which should return a `OpenDxp\Ecommerce\Component\Customer\Model\CustomerInterface` or throw a `OpenDxp\Ecommerce\Component\Customer\Context\CustomerNotFoundException`. 2. **Service Registration**: Register your custom context by using the tag `opendxp_ecommerce.context.customer`. You can also specify an optional `priority` attribute for the tag. ```php // Example PHP code for custom resolver implementation ``` #### Use Case for Custom Resolvers While the need for custom customer context resolvers might be rare, having the ability to create one provides additional flexibility for specific use cases or unique business requirements. Implementing a custom resolver allows you to tailor the customer identification process in a way that aligns more closely with your operational needs or security protocols. --- ## Customer Manager The Ecommerce Bundle provides a robust Customer Manager that simplifies the process of creating customers along with their addresses. This feature is an integral part of the Ecommerce Bundle suite, ensuring streamlined customer data management. ### The Ecommerce Bundle's Implementation of Customer Manager The Customer Manager adheres to the `OpenDxp\Ecommerce\Bundle\CoreBundle\Customer\CustomerManagerInterface` interface. The Ecommerce Bundle implements this interface through the service `opendxp_ecommerce.customer.manager`. ### Utilizing the Customer Manager The Customer Manager service can be used in various contexts, such as within a controller paired with a form type. Here’s an example of its usage: ```php $customer = $this->getCustomer(); if ($customer instanceof CustomerInterface && null === $customer->getUser()) { return $this->redirectToRoute('opendxp_ecommerce_customer_profile'); } $form = $this->get('form.factory')->createNamed('customer', CustomerRegistrationType::class, $this->get('opendxp_ecommerce.factory.customer')->createNew()); $redirect = $this->getParameterFromRequest($request, '_redirect', $this->generateUrl('opendxp_ecommerce_customer_profile')); if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)) { $form = $form->handleRequest($request); if ($form->isValid()) { $customer = $form->getData(); $customer->setLocaleCode($this->get('opendxp_ecommerce.context.locale')->getLocaleCode()); $this->get('opendxp_ecommerce.customer.manager')->persistCustomer($customer); return $this->redirect($redirect); } } return $this->render($this->templateConfigurator->findTemplate('Register/register.html'), [ 'form' => $form->createView(), ]); ``` In this example, the Customer Manager service is used to handle customer data obtained from a form. The customer is created or updated based on form submissions, demonstrating the flexibility and ease of use provided by the Ecommerce Bundle's customer management system. --- ## Customer Registration Types In the Ecommerce Bundle, the customer registration process can be configured to suit different requirements. By default, registration requires a unique and valid email address, but you can customize this to use other identifiers like a username. ### Register By Email The default registration method is by using a unique and valid email address. To configure registration by email, set the login identifier as follows: ```yaml opendxp_ecommerce_customer: login_identifier: 'email' ``` ### Register By Username To enable registration via a unique username: 1. **Add a `username` field**: Ensure that your customer data object has a `username` field. By default, the Ecommerce Bundle does not include this field to avoid confusion. You can add a text field named `username` in your class editor. 2. **Change the identifier**: Set the login identifier to `username`: ```yaml opendxp_ecommerce_customer: login_identifier: 'username' ``` ### Security Measures #### Frontend Form Constraints The Ecommerce Bundle includes built-in constraints that inform customers whether the email address or username they enter (depending on your configuration) is valid and unique. #### Backend/API Validation In addition to frontend validation, the Ecommerce Bundle also ensures the uniqueness of customer data when updating customer entities via the API or backend. > **Note**: These uniqueness checks apply only to non-guest entities. --- ## Customer Company Extension The Ecommerce Bundle includes a Company Entity feature, which enhances customer profiles by allowing them to be associated with specific companies. This connection enables sharing of addresses between the company and individual customers. ### Access Types The access type determines how a customer interacts with addresses, both their own and those of the associated company. This feature is activated once a customer is linked to a valid company. #### Own Only - **Default Setting**: Customers can manage their own addresses. - **Capabilities**: Customers can create, edit, and delete their own addresses, and use them during checkout. #### Company Only - **Company-Centric**: Customers manage company addresses. - **Capabilities**: Customers can create, edit, and delete company addresses, choose them in checkout, but cannot add personal addresses. #### Own And Company - **Dual Access**: Customers can manage both personal and company addresses. - **Capabilities**: Creation, editing, and deletion of both personal and company addresses, with the ability to choose either during checkout. Additionally, in the `own_and_company` mode, customers have the flexibility to define and modify the allocation of addresses. The Ecommerce Bundle incorporates a choice type in the address form for this purpose. **Physical Address Movement**: If a customer reallocates an address (e.g., from personal to company), the address is physically moved to the new category. For example, changing an address from `own` to `company` results in the following shift: Before Allocation Change: ```yaml - company A - addresses - customer A - addresses - address A ``` After Allocation Change: ```yaml - company A - addresses - address A - customer A - addresses ``` For further details on this feature, refer to the discussion on [GitHub](https://github.com/open-dxp/ecommerce-bundle/issues/1266). --- ## Customer and User The Ecommerce Bundle distinguishes between two entities when it comes to customer data management: `Customer` and `User`. Understanding the difference between these two is crucial for effectively managing customer information and authentication. ### Distinction Between Customer and User - **User**: The User entity is primarily concerned with authentication. It encompasses login credentials, including the login identifier (such as an email address or username) and the password. - **Customer**: The Customer entity, on the other hand, represents the actual customer profile. This includes details such as contact information, shipping and billing addresses, and order history. ### Guest Customers In scenarios where a Customer does not have an associated User entity, they are considered a 'Guest Customer'. This means they cannot log in to the system. #### Handling Guest Customers in Checkout During the checkout process, the Ecommerce Bundle can identify existing Guest Customers based on their email address. If a match is found, the Ecommerce Bundle uses the existing Customer Object. This approach has several benefits: - **Order Tracking**: Allows for the tracking of orders placed by guest customers. - **Conversion Opportunity**: Provides an opportunity to later convert guest orders into full customer profiles, enhancing customer relationship management. By maintaining separate User and Customer entities, the Ecommerce Bundle offers a flexible framework to cater to both registered and guest customers, while keeping authentication and customer data management distinct yet integrated. --- ## Customer Management In the dynamic and customer-centric world of eCommerce, effectively managing customer information is crucial. The Ecommerce Bundle offers a comprehensive system for handling customer data, ensuring that every aspect of customer interaction and management is streamlined and efficient. ### Overview of Customer Management Features The Ecommerce Bundle's customer management system is designed to handle various aspects of customer data, from basic information handling to more complex processes like customer registration and company extensions. Here’s an overview of the key features and functionalities: 1. **[Create, Read, Update, Delete (CRUD)](./01_CRUD.md)**: This section covers the fundamental operations for customer data management. It provides the necessary guidance on creating new customer profiles, reading existing customer information, updating customer details, and deleting customer records. 2. **[Customer Context](./02_Context.md)**: Understanding the context in which customers interact with your store is vital. This part of the guide delves into how the Ecommerce Bundle determines the current customer context and how you can tailor this to meet specific requirements. 3. **[Registration Service](./03_Customer_Manager.md)**: The registration service is a crucial component of customer management, facilitating the process of customer sign-ups. This section explains how the service operates and how you can utilize it for efficient customer registrations. 4. **[Registration Types](./04_Registration_Types.md)**: The Ecommerce Bundle supports various types of customer registrations, catering to different customer segments and needs. This section explores these types, offering insights into how they can be implemented and managed. 5. **[Company Extension](./05_Company_Extension.md)**: For B2B operations, managing company-related customer data is essential. This part of the guide focuses on how the Ecommerce Bundle handles company extensions within customer profiles. #### Tailoring Customer Management to Your Needs Whether you're managing a B2C or B2B store, or a combination of both, the Ecommerce Bundle's customer management system provides the tools and flexibility needed to ensure that customer data is handled effectively and securely. By exploring each section, you can gain a comprehensive understanding of how to optimize customer management for your Ecommerce Bundle installation. --- ## eCommerce Tracking The Ecommerce Bundle implements tracking for analytics and Google Tag Manager, integrating seamlessly as soon as Tag Manager or Analytics is enabled in OpenDxp. By default, all ecommerce trackers are disabled and need to be manually activated. ### Available Trackers The Ecommerce Bundle supports a variety of trackers, including: - google-analytics-enhanced-ecommerce - google-analytics-universal-ecommerce - google-gtag-enhanced-ecommerce - google-gtm-classic-ecommerce - google-gtm-enhanced-ecommerce - matomo (piwik) ### Enabling Trackers To enable a specific tracker, modify the configuration as follows: ```yml opendxp_ecommerce_tracking: trackers: google-analytics-enhanced-ecommerce: enabled: false google-analytics-4: enabled: false google-gtag-enhanced-ecommerce: enabled: false google-gtm-classic-ecommerce: enabled: false google-gtm-enhanced-ecommerce: enabled: false matomo: enabled: true ``` #### External Resources For more information on these tracking methods: - [Google Enhanced E-Commerce](https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce) - [Google Enhanced E-Commerce with gtag.js](https://developers.google.com/analytics/devguides/collection/gtagjs/enhanced-ecommerce) - [Google Tag Manager Enhanced E-Commerce](https://developers.google.com/tag-manager/enhanced-ecommerce) - [Google Tag Manager Classic E-Commerce](https://support.google.com/tagmanager/answer/6107169?hl=en) - [Matomo (Piwik) E-Commerce](https://matomo.org/docs/ecommerce-analytics/) ##### Actions ###### Product Impression ```php $this->get('opendxp_ecommerce.tracking.manager')->trackProductImpression($product); ``` ###### Product View ```php $this->get('opendxp_ecommerce.tracking.manager')->trackProduct($product); ``` ###### Product Action Add from Cart ```php $this->get('opendxp_ecommerce.tracking.manager')->trackCartAdd($cart, $product); ``` ###### Product Action Remove from Cart ```php $this->get('opendxp_ecommerce.tracking.manager')->trackCartRemove($cart, $product); ``` ###### Checkout Step ```php $this->get('opendxp_ecommerce.tracking.manager')->trackCheckoutStep($cart, $stepIdentifier, $isFirstStep, $checkoutOption) ``` ###### Checkout Complete ```php $this->get('opendxp_ecommerce.tracking.manager')->trackCheckoutComplete($order) ``` ### Adding a Custom Tracker To add a custom tracker: 1. Implement the interface `OpenDxp\Ecommerce\Component\Tracking\Tracker\TrackerInterface`. 2. Register the tracker as a service: ```yaml App\Ecommerce\Tracker\CustomTracker: parent: opendxp_ecommerce.tracking.tracker.ecommerce_tracker tags: - { name: opendxp_ecommerce.tracking.tracker, type: app-custom-tracker } ``` ### Google Tag Manager The Ecommerce Bundle sends data to a `dataLayer` object for Google Tag Manager, which then submits the object to GTM. #### GTM Classic eCommerce In classic mode, only the order gets submitted when the user reaches the "thank-you" page. #### GTM Enhanced eCommerce For Google Tag Manager Enhanced eCommerce, there are six Impressions/Events: - Product Impression - Product Detail View - Checkout Step - Checkout Complete (Purchase) - Remove Item from Cart - Add Item to Cart Each impression/event has specific configurations for GTM tagging, as outlined in the detailed tag config examples provided. --- ## Events The Ecommerce Bundle is equipped with a wide array of built-in events across different functionalities. ### Frontend Controller Events Events triggered during frontend controller operations: | Name | EventType | Description | |:--------------------------------------------|:------------------------|:-------------------------------------------------| | `opendxp_ecommerce.customer.update_post` | ResourceControllerEvent | Fires after customer profile update | | `opendxp_ecommerce.customer.change_password_post` | ResourceControllerEvent | Fires after customer password change | | `opendxp_ecommerce.customer.newsletter_confirm_post` | ResourceControllerEvent | Fires after newsletter subscription confirmation | | `opendxp_ecommerce.address.add_post` | ResourceControllerEvent | Fires after adding a new address | | `opendxp_ecommerce.address.update_post` | ResourceControllerEvent | Fires after updating an address | | `opendxp_ecommerce.address.delete_pre` | ResourceControllerEvent | Fires before deleting an address | ### Cart Events Events related to cart operations: | Name | EventType | Description | |:---------------------------------|:-------------|:----------------------------------------| | `opendxp_ecommerce.cart.update` | GenericEvent | Fires after cart update | | `opendxp_ecommerce.cart.pre_add_item` | GenericEvent | Fires before adding an item to cart | | `opendxp_ecommerce.cart.post_add_item` | GenericEvent | Fires after adding an item to cart | | `opendxp_ecommerce.cart.pre_remove_item` | GenericEvent | Fires before removing an item from cart | | `opendxp_ecommerce.cart.post_remove_item` | GenericEvent | Fires after removing an item from cart | | `opendxp_ecommerce.cart.pre_update_item` | GenericEvent | Fires before updating an item from cart | | `opendxp_ecommerce.cart.post_update_item` | GenericEvent | Fires after updating an item from cart | ### Customer Events Events triggered during customer-related processes: | Name | EventType | Description | |:-------------------------------------------|:---------------------------|:----------------------------------------------| | `opendxp_ecommerce.customer.register` | CustomerRegistrationEvent | Fires after new customer registration | | `opendxp_ecommerce.customer.request_password_reset` | RequestPasswordChangeEvent | Fires after password reset request | | `opendxp_ecommerce.customer.password_reset` | GenericEvent | Fires after applying new password to customer | ### Order Document Events Events for order document operations: | Name | EventType | Description | |:-----------------------------------------|:-------------------|:-------------------------------------------------------| | `opendxp_ecommerce.order.shipment.wkhtml.options` | WkhtmlOptionsEvent | Options Event: Modify wkhtml options for shipment docs | | `opendxp_ecommerce.order.invoice.wkhtml.options` | WkhtmlOptionsEvent | Options Event: Modify wkhtml options for invoice docs | ### Payment Events Events associated with payment processing: | Name | EventType | Description | |:-------------------------------------|:-----------------------------|:--------------------------------------------------| | `opendxp_ecommerce.payment_provider.supports` | PaymentProviderSupportsEvent | Support Event: Modify available Payment Providers | ### Notes Events Events related to note creation and deletion: | Name | EventType | Description | |:------------------------------|:-------------|:----------------------------------------------| | `opendxp_ecommerce.note.*.post_add` | GenericEvent | Fires after creating a note of specified type | | `opendxp_ecommerce.note.*.post_delete` | GenericEvent | Fires after deleting a note of specified type | Replace `*` with a note type (e.g., `payment`, `order_comment`). ### Rules Events Events for rule operations: | Name | EventType | Description | |:-----------------------------------|:---------------------------|:--------------------------------------------------| | `opendxp_ecommerce.rule.availability_check` | RuleAvailabilityCheckEvent | Fires for every active rule in availability check | ### Workflow Events Events for workflow transitions. Read more about it [here](../06_Order/16_State_Management/index.md). ### Backend Controller Events Events triggered in various backend operations: | Name | EventType | Description | |:-------------------------|:------------------------|:-------------------------------------------| | `opendxp_ecommerce.*.pre_create` | ResourceControllerEvent | Fires before creating an object in backend | | `opendxp_ecommerce.*.post_create` | ResourceControllerEvent | Fires after creating an object in backend | | `opendxp_ecommerce.*.pre_save` | ResourceControllerEvent | Fires before saving an object in backend | | `opendxp_ecommerce.*.post_save` | ResourceControllerEvent | Fires after saving an object in backend | | `opendxp_ecommerce.*.pre_delete` | ResourceControllerEvent | Fires before deleting an object in backend | | `opendxp_ecommerce.*.post_delete` | ResourceControllerEvent | Fires after deleting an object in backend | Replace `*` with a controller type (e.g., `configuration`, `payment_provider`). ### Model Events OpenDxp Events can be used for the Ecommerce Bundle's OpenDxp Models. Learn more at [OpenDxp Events](https://opendxp.com/docs/platform/OpenDxp/Extending_OpenDxp/Event_API_and_Event_Manager). --- ## Frontend Bundle Controllers The Ecommerce Bundle's FrontendBundle allows customization of its controllers. You can modify the controllers used by changing the configuration settings in your application. ### Configuring Frontend Controllers To specify which controllers to use, adjust the `opendxp_ecommerce_frontend` configuration in your `yaml` file: ```yaml opendxp_ecommerce_frontend: controllers: index: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\IndexController register: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\RegisterController customer: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\CustomerController currency: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\CurrencyController language: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\LanguageController search: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\SearchController cart: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\CartController checkout: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\CheckoutController category: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\CategoryController product: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\ProductController quote: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\QuoteController security: OpenDxp\Ecommerce\Bundle\FrontendBundle\Controller\SecurityController payment: OpenDxp\Ecommerce\Bundle\PayumBundle\Controller\PaymentController ``` ### Implementing a Custom ProductController #### Step 1: Create a New Controller Create a new controller by inheriting from the Ecommerce Bundle FrontendController: ```php ['all' => true], ]; ``` #### Templates Symfony allows overriding Bundle templates by placing them in the `templates` directory. This is not recommended, as the Ecommerce Bundle's templates may change, be added to, or be renamed between releases — whether intentionally or incidentally. To not run into any issues with Demo Files to be loaded, we recommend to copy the Templates from the Demo Frontend. There is also a new command for that: ```bash php bin/console opendxp-ecommerce:frontend:install ``` This will copy all the templates from OpenDxp Ecommerce into app view storage and it also replaces all the Bundle Prefixes. That way, you can be sure that you are using the correct templates. This command also creates a configuration to change the `TemplateConfigurator` to use your app template paths and not the FrontendBundle paths. ### Headless If you are going headless, you can simply not enable the Frontend Bundle and do whatever need for your Headless API. --- ## Frontend Bundle The ecommerce Store Front, also known as the FrontendBundle, provides a default implementation that serves as a practical guide for working with the Framework. It is designed to showcase how various functionalities can be implemented in a store environment. ### Components of the Frontend Bundle The FrontendBundle includes various components, each focusing on a specific aspect of the store front: - **Controllers**: The bundle includes a set of controllers that manage the interactions between the store front's user interface and the underlying ecommerce functionalities. These controllers can be customized to fit the specific needs of your store. - [Learn more about Controllers](./01_Controllers.md) ### DEMO The ecommerce Frontend is a fully functional store front that can be used as a reference for building your own store. It is meant as a Demo and not as a production-ready store. ### Best Practice We have a separate Guide how we recommend you use the Frontend Bundle: [Best Practices](02_Best_Practices.md) --- ## Inventory(Development) ### Twig Helper The ecommerce bundle provides Twig helpers to assist in checking the inventory of products. #### Inventory Available This helper checks if any inventory is available for a product: ```twig {% if opendxp_ecommerce_inventory_is_available(product) %} {# show cart button since there is at least one item available #} {% endif %} ``` #### Inventory is Sufficient This helper checks if the inventory level meets or exceeds a specified amount: ```twig {% if opendxp_ecommerce_inventory_is_sufficient(product, 10) %} {# do something here since there are at least 10 items available #} {% endif %} ``` --- ## SEO For detailed information on how to utilize the SEO features, refer to the following documentation: - [SEO Bundle Usage](./../../03_Bundles/SEO_Bundle.md) --- ## Fraction Digits The ecommerce bundle allows you to work with more than two digits for currency values. The default configuration looks like this: ```yml opendxp_ecommerce_currency: money_decimal_precision: 2 money_decimal_factor: 100 ``` - `money_decimal_precision: 2`: This setting specifies a global precision of 2. - `money_decimal_factor: 100`: This setting is for displaying currency with a factor of 100 in the OpenDxp Backend. > *WARNING*: If you change these settings in an existing installation with orders, products, etc., you also need to > create a migration to change all the values from a precision of 2 to your new setting. For handling payment values with a precision of, for example, 4, a new order property called `paymentTotal` is introduced. In payments, dealing with a precision greater than 2 isn't feasible since a currency only has, for example, 100 cents. Therefore, the `total` Cart/Order value is rounded to a precision of 2 in the `paymentTotal` value. For example, if your Cart/Order total is "€ 1,000.5498", the payment total would be "€ 1,000.55". To display the payment total in your cart, you can use this template: ```twig {% if currency.convertAndFormat(cart.total) != currency.convertAndFormat(cart.paymentTotal, 2, 100) %} {{ 'opendxp_ecommerce.ui.payment_total'|trans }}: {{ currency.convertAndFormat(cart.paymentTotal, 2, 100) }} {% endif %} ``` --- ## Development This guide is intended for developers who aim to harness the flexibility and robust features. It outlines the key concepts and components used, providing insights into its architecture and how to effectively work with it. ### Introduction The ecommerce bundle offers a rich set of tools and features for building sophisticated eCommerce solutions. Understanding the underlying concepts and models is crucial for leveraging its full potential. ### Resources The ecommerce bundle utilizes Doctrine ORM for its custom resources, offering great flexibility and extendability for managing simple models such as currencies, countries, etc. Here are the primary resources implemented as ORM models: - **Currency**: Handling various currencies. - **Country and State**: Geographical models for location-based functionality. - **Tax Rate and Tax Rules**: For applying taxes in different scenarios. - **Price Rules**: Rules that define pricing under various conditions. - **Carrier**: Shipping carriers and their configurations. - **Shipping Rules**: Rules for handling shipping logic and pricing. - **Index and Filter Configuration**: For product indexing and filtering. - **Notification Rule Configuration**: Setting up rules for notifications. - **Stores**: Representing different stores or sales channels. - **Payments**: Handling payment methods and transactions. The term 'Resource' refers to these ORM Models. ### OpenDxp Models Leveraging OpenDxp's flexible data model, The Ecommerce Bundle uses Data Objects for frequently used and modified entities. The following are the key objects implemented using OpenDxp Data Objects: - **Product**: The core entity in any eCommerce platform. - **Product Category**: Organizing products into categories. - **Manufacturer**: Information about product manufacturers. - **Order**: Managing customer cart/orders. - **Order Invoice**: Generating and handling invoices. - **Order Shipment**: Managing the shipment of orders. - **Quote**: Handling quotes for customers. - **Customer**: Customer data and profiles. - **Customer Group**: Grouping customers for specific functionalities or offers. - **Addresses**: Managing customer addresses. When discussing 'Objects' in the context of the ecommerce bundle, it refers to these OpenDxp Data Objects. --- ## Genius(Ecommerce) The Content Crafter assistant reads and writes shop data through the fields this bundle registers. The integration is loaded only where the Content Crafter bundle is installed. - [What this bundle registers](#what-this-bundle-registers) - [Ask about a price](#ask-about-a-price) - [Calculate a price](#calculate-a-price) - [Money fields on any class](#money-fields-on-any-class) - [Fields that answer with a name](#fields-that-answer-with-a-name) - [Two words for two questions](#two-words-for-two-questions) - [What a group takes](#what-a-group-takes) - [Attributes in a plan](#attributes-in-a-plan) - [Store fields](#store-fields) - [Stock figures are never written](#stock-figures-are-never-written) - [Promotions and settings](#promotions-and-settings) - [Rules and units of a product](#rules-and-units-of-a-product) - [Register the integration](#register-the-integration) - [Test the integration](#test-the-integration) ### What this bundle registers Genius gets five tools from this bundle. | tool | answers | |----------------------------------------|---------------------------------------------| | `query_ecommerce_promotions` | cart rules, voucher codes and catalog rules | | `get_ecommerce_promotion_query_schema` | the fields of a promotion | | `query_ecommerce_settings` | the stores | | `get_ecommerce_setting_query_schema` | the fields of a store | | `get_ecommerce_price` | what a product costs a customer in a cart | [Promotions and settings](#promotions-and-settings) describes the first four tools. [Calculate a price](#calculate-a-price) describes the last one. Everything else is a field on the classes of the shop, such as the price of a product per store or its price rules. Genius reads these fields with `query_objects` and `get_object` and writes them through a plan, under the permissions those tools already need. Which class is the product, the order and the category is a project decision, so every service that needs to know takes the container parameter, `%opendxp_ecommerce.stack.product.fqcns%` and its two siblings. ### Ask about a price `price` is a curated view of a product's per-store values. It replaces the raw `storeValues` relation, so there is no second way to ask the same question in cents. A price row is named by its `store` and holds `price`, `taxRuleId`, `storeName`, `currency` and `taxIncluded`. ```json {"price": {"any": {"store": "default", "price": {"gt": 390}}}} ``` `store` takes `default`, a store name as `query_ecommerce_settings` returns it, or a numeric id. `EcommerceStoreNameTransformer` resolves all three to the id the column holds, and refuses a name no store has. Sorting and aggregating address the column directly, `sortBy` `price.price` or `aggregate` `{"avg": "price.price"}`. Amounts are the ones a person reads and says. The column counts in the smallest currency unit, and `MoneyAmounts` scales between the two by `%opendxp_ecommerce.currency.decimal_factor%`, in a read, an average, a total, a group label and a filter alike. *Over 390* means the price a shop shows as 390. What that 390 counts is the store's, not the row's. The store carries the currency and decides whether its amounts already have tax in them, so every row answers with `currency` and `taxIncluded` beside the amount. Neither is a column: they cannot be filtered or sorted by, they say what the number means. An amount a request names is therefore about one store, the default one where none is named. A request naming a currency no store has is a question back rather than a conversion. `price` carries no write capability. A plan does not write it. The chat and Genius Explorer show the price of a product with its currency, one line per store. ### Calculate a price `get_ecommerce_price` calculates what a product costs a customer in a store. It puts the product into a cart and prices the cart like the shop does. The backend previews an order the same way. The cart is never saved. A call names the product and the quantity. It may name a store, a customer and a voucher code. Without a store it takes the default store. Without a customer it calculates the price for a guest. ```json {"productId": 86, "quantity": 10, "customerId": 120, "voucherCode": "SPRING-2026"} ``` The answer holds the price of one piece and the total of the cart. It names the rules behind them: - `catalogRules` and `productRules` are the price rules that make the price of one piece - `quantityPriceRule` is the quantity price rule that applies - `cartRules` are the cart rules, each with its `discount` or its `surcharge` on the whole cart - `voucherCodeApplies` says whether the rule of the voucher code applies to the cart `total` is the whole cart. It adds the `subtotal` of the pieces, the cart rules and the `shipping` of the `carrier` that the shop picks. Every amount includes tax, except `totalWithoutTax`. The tool needs the permission for objects, and the user must be allowed to view the product and the customer. ### Money fields on any class A class definition field of type `Money` or `MoneyCurrency` is a number, filtered and sorted by the amount alone, and is written the way it is read. | field type | written as | |-----------------|-----------------------------------------| | `Money` | `19.90` | | `MoneyCurrency` | `{"value": 19.90, "currency": "EUR"}` | `ActiveCurrencies` lists the currencies of a country that is switched on, and both the description the model reads and the refusal it gets name that list. A `MoneyCurrency` is read back in the same shape, with the amount already scaled, so two money fields on one class never answer in two scales. ### Fields that answer with a name Reflection cannot know that the stored value of these two is an identifier while the answer is the configured name. Their field types say it. | field type | reads back as | |-------------------|------------------------------| | `Carrier` | `{id, identifier, title}` | | `PaymentProvider` | `{id, identifier, title}` | An order can then be asked about in the words the shop uses rather than by a class name. ### Two words for two questions `EcommerceProductSchemaGuide` tells the model that a product has two status-like fields, and which one an editor usually means. | field | means | |-------------|-----------------------------------------| | `active` | shop availability, listed for sale | | `published` | editorial visibility in the CMS | Asked for *active* products with nothing further, the shop meaning is taken. `published` is used where the question is explicitly about editorial visibility. ### What a group takes A variant attribute exists only as a child of an attribute group. It is created with its `parentId` set to the group, and its `attributeGroup` is worked out from where it sits, so a plan never writes that relation. `EcommerceAttributeSchemaGuide` says both on the attribute classes. Which classes a group takes is the group's own `allowedAttributeClasses`, a field `EcommerceAttributeGroupProvider` adds. It is read off the group's children, because that is what decides it: `ValidAttributesType` turns down an attribute that is not of the same class as the ones already there. | the group | `allowedAttributeClasses` | |------------------|------------------------------------------------------------| | holds attributes | the class of those, and only that one | | is still empty | every configured attribute class, the first one settles it | Reading the group therefore answers what may be created under it, with nothing to work out. ### Attributes in a plan A product carries its attributes in four fields. Which field a value belongs in depends on the group it comes from and on whether the element is a variant. `EcommerceAttributePlanCheck` judges the whole plan, so a step that allows a group and a later step that uses it are judged together. | field | takes | |---------------------------|-----------------------------------------------------------------| | `allowedAttributeGroups` | groups that form variants, on the main product only | | `attributes` | one attribute per allowed group, on a variant only | | `standardAttributeGroups` | groups that form no variants | | `standardAttributes` | attributes of a group listed in `standardAttributeGroups` | A new attribute under a group has to be of the class the group already holds. Every refusal can be corrected by the model, and a plan that settles a group before it uses the group passes. ### Store fields `EcommerceStoreSchemaGuide` tells the model that a plain `store` or `stores` field holds a numeric id, never a name. Where the installation has one store, the guide names its id. Where it has several, it points at `query_ecommerce_settings`. The `price` field is the exception, because its own `store` key takes a name. ### Stock figures are never written `EcommerceStockWriteProtection` returns `onHold`, `onHand` and `isTracked` for every configured product class. They stay readable and filterable and are gone from the schema's write side, from the direct tools and from the plan. `onHold` reads like a flag and is a quantity the shop keeps, which is what makes a wrong value look plausible. A project protects further fields the same way, or in `content_crafter.yaml`, see [Configuration](https://docs.opendxp.io/docs/bundles/content-crafter/Configuration#keeping-fields-away-from-the-model). ### Promotions and settings The promotions and the settings of the shop are Doctrine entities. Content Crafter reads them through their mapping, so every field and every relation can be read and filtered on. Nothing here is written. Each area is one pair of tools. A call names what it searches as `type`, the way an asset query names an asset type. | query tool | `type` | finds | needs the permission | |------------------------------|----------------|---------------------------------------|------------------------| | `query_ecommerce_promotions` | `cart_rule` | cart price rules | cart price rules | | | `voucher_code` | the voucher codes of the cart rules | cart price rules | | | `catalog_rule` | catalog price rules | catalog price rules | | `query_ecommerce_settings` | `store` | the stores | `objects` | Each has a schema tool next to it, `get_ecommerce_promotion_query_schema` and `get_ecommerce_setting_query_schema`. A user is offered only the types they hold the permission for, and sees neither tool where they hold none. The stores take the permission for objects, because the store fields of products and orders hold their ids. The conditions and actions of a rule are rows with a `type`. A filter on the type answers questions such as *which rules are limited in time*: ```json {"type": "catalog_rule", "filters": {"conditions": {"any": {"type": "timespan"}}}} ``` Their `configuration` is read whole and cannot be filtered on. The dates of a timespan condition are read as dates, not as the milliseconds the column holds. An amount in a condition or an action is read as money, like every other amount of the shop. `active` only says whether a rule is switched on. A timespan condition can still keep a switched-on rule from applying today. The credit of a voucher code is read as money, like every other amount of the shop. A filter takes it the same way: ```json {"type": "voucher_code", "filters": {"creditAvailable": {"gt": 20}}} ``` The model sees only the last four characters of a voucher code, such as `***A7K2`. A filter takes the whole code. Genius Explorer shows the whole code to the editor. A store answers with its `currency`, whether its amounts have tax in them (`useGrossPrice`) and whether it is the default (`isDefault`). ### Rules and units of a product The price rules of a single product, its quantity prices and its units belong to the product. They are fields of the product and are reached through `query_objects`. | field | holds | |----------------------|--------------------------------------------------------------------| | `specificPriceRules` | the price rules of this product alone, with conditions and actions | | `quantityPriceRules` | the quantity price rules, each with its `ranges` | | `unitDefinitions` | the units the product is sold in, and the one its prices count in | A filter on them answers questions such as *which products have quantity prices*: ```json {"className": "EcommerceProduct", "filters": {"quantityPriceRules": {"count": {"gt": 0}}}} ``` The price of a quantity step is read and filtered as money, like every other amount of the shop. ### Register the integration The integration loads only when `OpenDxpContentCrafterBundle` is in the bundle list. `EcommerceCoreExtension` then loads `Resources/config/content_crafter/services.yml`. The file registers every class under `src/Bundle/CoreBundle/ContentCrafter/` as a service. Two folders are different: - Content Crafter reads the archetypes in `Archetype/` by reflection. They are no services. - The normalizers have the tag `content_crafter.serializer.tool_result_normalizer` and no autoconfiguration. They stay out of the serializer of the application. Every entity class of a promotion or a store gets an `EntityTable`, also when no tool queries it. The three query domains take the entity classes that the installation configures. `opendxp_content_crafter.field.doctrine_types` declares two Doctrine types as numbers: - `bigintInteger` of the quantity steps - `opendxpObject` of the units #### Check the fields without a model The workbench of Content Crafter shows what the fields of a product class look like, without a model call. Run it in the checkout of Content Crafter: ```bash php workbench/bin/tool.php query_ecommerce_settings --user=admin --arguments='{"type":"store"}' php workbench/bin/explain.php fields --user=admin --arguments='{"domain":"object","type":"EcommerceProduct"}' ``` See [Debugging](https://docs.opendxp.io/docs/bundles/content-crafter/Debugging). ### Test the integration The tests under `tests/Feature/ContentCrafter` call the tools and run plans through the test API of Content Crafter, without a model. A test reads a field the way the assistant does and checks what a plan writes or why it is refused: ```php use OpenDxp\Bundle\ContentCrafterBundle\Test\Plans; use OpenDxp\Ecommerce\Test\Factory\ProductFactory; use OpenDxp\Model\DataObject\EcommerceProduct; it('writes an amount in the smallest unit of the currency', function () { $product = ProductFactory::createOne(); Plans::run([ [ 'ref' => 'product', 'op' => 'object.update', 'selector' => 'EcommerceProduct', 'target' => ['subject' => $product->getId()], 'values' => ['wholesalePrice' => 12.5], ], ]); expect(EcommerceProduct::getById($product->getId(), ['force' => true])->getWholesalePrice())->toBe(1250); }); ``` The test API is described in [Tests](https://docs.opendxp.io/docs/bundles/content-crafter/Tests). --- ## Changelog(Ecommerce) ### 1.2.4 - [BUGFIX] A select or multiselect field whose store does not exist is disabled and logs an error. It no longer breaks the editor of the object ### 1.2.3 - [SECURITY] [OPENDXP-SA-2026-019] The categories, manufacturer and products reports take only the values of the order state filter, never its keys - [SECURITY] [OPENDXP-SA-2026-020] The variant generator takes the ids of attributes as numbers - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.2.2 - [BUGFIX] The bundle no longer turns off the auto save of data objects ### 1.2.1 - [ENHANCEMENT] A product or category whose `slug` field has a slug generator gets its slugs from that generator only - [ENHANCEMENT] `SlugGenerator` builds the slugs of products and categories, for example `/de_CH/product/green-bike`. It is inactive until a class enters it as the slug generator of its `slug` field, see [Slug](docs/03_Bundles/OpenDxp_Bundle.md#slug) - [ENHANCEMENT] `CategoryFactory::namedInEveryLanguage()` names a category in every language, like `ProductFactory` does - [ENHANCEMENT] `ProductFactory::withoutStores()` and `CategoryFactory::withoutStores()` create a product or category without a store - [BUGFIX] The page of a product or category without a store returns 404 instead of an error - [BUGFIX] Products and categories no longer show the empty Store Preview tab - [DEPRECATION] The JavaScript class `opendxp_ecommerce.core.object.store_preview` is deprecated. 2.0 removes it, use the Preview tab instead - [DEPRECATION] The slug generation of the bundle, `SluggableListener` and the classes it uses, is deprecated. 2.0 removes it, use `SlugGenerator` on the `slug` field instead, see [Slug](docs/03_Bundles/OpenDxp_Bundle.md#slug) - [DEPRECATION] `SluggableInterface::getNameForSlug()` is deprecated. 2.0 removes it, use `SlugGenerator::getDefaultSlug()` instead ### 1.2.0 - [ENHANCEMENT] `VouchersReport::getReportData()` also returns the unused codes. Each row has the new keys `used` and `creationDate`. An unused code has the discount `--`. The CSV export has the two new columns too. The report in the backend starts with the filter Used = yes and looks the same as before - [NEW FEATURE] [HIGHLIGHT] Genius support: ask about products, prices, stores, price rules and voucher codes, calculate what a product costs a customer, and let a plan write products and their attributes [Read more](./docs/04_Genius.md) > Ask Genius about products, prices, stores, price rules and voucher codes. Genius calculates what a product costs a customer. A plan writes products and their attributes for you. - [SECURITY] [OPENDXP-SA-2026-003] Listing, creating, generating, exporting and deleting voucher codes requires the permission for cart price rules. A voucher code that was used can no longer be deleted - [BUGFIX] An order adds the credit it uses to the used credit of its voucher code. It replaced the used credit before - [BUGFIX] A default address for invoices no longer becomes the shipping address of the cart. A default address for shipping no longer becomes the invoice address [#9](https://github.com/open-dxp/ecommerce-bundle/issues/9) - [BUGFIX] The failed messages of the messenger show the date and time of their failure. A skipped message no longer breaks the list [#50](https://github.com/open-dxp/ecommerce-bundle/issues/50) - [BUGFIX] Paying or cancelling an order updates the stock of every product, also when a product has too little stock. An oversold product goes below zero and shows up in the history of the order [#10](https://github.com/open-dxp/ecommerce-bundle/issues/10) - [BUGFIX] `WishlistRepository::findNamedStorageLists()` sorts by `creationDate` instead of `o_creationDate` - [NEW FEATURE] A test API for projects under `OpenDxp\Ecommerce\Test`: factories, the story `InstalledShop`, rules, shop flows and page objects for the storefront (requires `open-dxp/opendxp` ^1.5) - [NEW FEATURE] [HIGHLIGHT] Semantic markup in the frontend templates: schema.org microdata for products and offers, accessible names for regions, tables, forms and icon buttons. Copied templates keep working > The storefront templates ship schema.org microdata for products and offers, and accessible names for regions, tables, forms and icon buttons. Copied templates keep working. - [NEW FEATURE] Twig filter `ecommerce_money_decimal` - [NEW FEATURE] Content Crafter Genius: the tool pairs `query_ecommerce_promotions` and `query_ecommerce_settings`, and the rules, tiers and units of a product as relations - [DEPRECATION] `ecommerce_test_html_attribute` and `ecommerce_test_form_attribute` render nothing and go with the next major - [DEPRECATION] `User::eraseCredentials()`. The plain password is no longer serialized - [BUGFIX] A registered user no longer carries the plain password into the session - [BUGFIX] Every cart gets the price rules that apply to it, also when a request prices several carts - [BUGFIX] Labels of the password fields in the registration, of the terms checkbox and of the checkout steps - [BUGFIX] The submit buttons of the registration and the guest checkout say "Register" and "Proceed" - [BUGFIX] Deprecations of Twig: macro arguments without defaults, the filter `spaceless` - [BUGFIX] GraphQL types of the Data Hub integration - [NEW FEATURE] Cart rule discounts can also apply to the shipping costs - [BUGFIX] Combined discount amounts no longer exceed the price of the products - [ENHANCEMENT] Installing the bundle marks its migrations as executed - [NEW FEATURE] [HIGHLIGHT] [MIGRATION] Payment providers have a Tax Calculation setting like carriers. A fee can also use a tax rule group of its own. See [Taxes on the Payment Fee](docs/03_Development/10_Payment/01_Payment_Provider.md#taxes-on-the-payment-fee) > Payment providers get a tax calculation setting, just like carriers. A payment fee optionally uses a tax rule group of its own. - [BUGFIX] Payment fees are taxed at the tax rates of the products in the cart - [BUGFIX] Shipping costs based on cart items use the tax rate of each item - [BUGFIX] A cart with only free products no longer fails when shipping or payment fees are based on cart items - [BUGFIX] Payment rules and manual payments work in shops with more than two decimal places - [NEW FEATURE] Surcharges in cart rules can be taxed with a tax rule group of their own. See [Actions](docs/02_User_Documentation/03_Price_Rules/06_Actions.md#taxes-on-a-surcharge) - [BUGFIX] Surcharge Percent takes the percentage of the gross subtotal in stores with gross prices - [BUGFIX] The tax lines of a cart match its total when a cart rule has a gross amount - [BUGFIX] The tax lines of a cart match its total when a cart item rule gives a discount - [NEW FEATURE] Projects can add taxed adjustments to cart items. See [Adjustments](docs/03_Development/06_Order/05_Adjustment.md#add-a-taxed-adjustment-to-a-cart-item) - [BUGFIX] Gross prices with several tax rules get the right net price and taxes - [BUGFIX] The order view in the backend shows the unit of each item - [BUGFIX] An order keeps the name of the unit of each item - [BUGFIX] The order view in the backend shows "--" instead of "null" for an order without a carrier - [NEW FEATURE] The columns of the report grids have filters. The Voucher Report also lists unused codes. See [Reports](docs/02_User_Documentation/09_Reports/index.md) - [ENHANCEMENT] The reports choose their period from a list instead of six buttons - [BUGFIX] The CSV export of a report holds every row, not only the first page - [BUGFIX] The Products Report lists main products and container products. It failed or stayed empty for both - [BUGFIX] A grid column with the store price no longer fails before a store is chosen for it - [NEW FEATURE] The object grid shows, edits, filters and sorts a store value of a store. See [Store Values](docs/03_Development/03_Products/09_Store_Values.md) - [BUGFIX] A variant that changes an inherited store value in the editor no longer takes the store value away from its parent - [ENHANCEMENT] A money field can be edited in the object grid. Its filter compares amounts in the unit of the currency - [BUGFIX] The revise page no longer shows a cancel button that ended in an error - [NEW FEATURE] The order list of the customer account offers to pay an order that still waits for its payment - [DEPRECATION] The field `cancel` of the revise payment form will be removed in 2.0 ### 1.1.3 - [CHORE] Add a catalog entry for Backstage [#45](https://github.com/open-dxp/ecommerce-bundle/pull/45) - [NEW FEATURE] Add refresh from set functionality for non-variant attribute groups [#46](https://github.com/open-dxp/ecommerce-bundle/pull/46) ### 1.1.2 - [BUGFIX] [MIGRATION] Fix permission category length to comply with database constraint [#42](https://github.com/open-dxp/ecommerce-bundle/pull/42) - [BUGFIX] Fix variant attribute handling and improve attribute store management [#43](https://github.com/open-dxp/ecommerce-bundle/pull/43) - [BUGFIX] Add missing language parameter to `getName` in `OrderItemInterface` [#44](https://github.com/open-dxp/ecommerce-bundle/pull/44) ### 1.1.1 - [NEW FEATURE] [MIGRATION] Add standard attribute / groups [#39](https://github.com/open-dxp/ecommerce-bundle/pull/39) ### 1.1.0 - [NEW FEATURE] [MIGRATION] attribute/variant builder [#37](https://github.com/open-dxp/ecommerce-bundle/pull/37) - [BUGFIX] Fix ClassReflection class-name detection using the tokenizer [#38](https://github.com/open-dxp/ecommerce-bundle/pull/38) ### 1.0.7 - [BUGFIX] Replace `AddressFormatterInterface` service references with `opendxp_ecommerce.address.formatter.admin_address_formatter` [#34](https://github.com/open-dxp/ecommerce-bundle/pull/34) - [BUGFIX] Enforce type casting for `mailDocumentId` in `OrderMailActionProcessor` to ensure proper retrieval of documents [#35](https://github.com/open-dxp/ecommerce-bundle/pull/35) ### 1.0.6 - [CHORE] Remove redundant re-creation of `doNotSendToDesignatedRecipient` in `orderMail` action configuration [#32](https://github.com/open-dxp/ecommerce-bundle/pull/32) - [BUGFIX] Fix cloning logic for `productStoreValue` and `storeValuesEntity` to reset `productUnitDefinitionPrices` and prevent corrupted inheritance [#33](https://github.com/open-dxp/ecommerce-bundle/pull/33) ### 1.0.5 - [BUGFIX] Fix date formatting and enforce type casting for mail document ID [#31](https://github.com/open-dxp/ecommerce-bundle/pull/31) ### 1.0.4 - [BUGFIX] Fix Admin Translations [#29](https://github.com/open-dxp/ecommerce-bundle/pull/29) - [BUGFIX] Refactor schema update logic [#30](https://github.com/open-dxp/ecommerce-bundle/pull/30) ### 1.0.3 - [BUGFIX] Fix schema [#25](https://github.com/open-dxp/ecommerce-bundle/pull/25) - [ENHANCEMENT] Add php 8.5 support [#28](https://github.com/open-dxp/ecommerce-bundle/pull/28) ### 1.0.2 - [CHORE] Expand `sebastian/diff` version constraints in `composer.json` to include ^7.0 and ^8.0 [#22](https://github.com/open-dxp/ecommerce-bundle/pull/22) - [BUGFIX] [MIGRATION] Fix key naming: Rename `ctc_assign_to_existing` to `ctc_assign_existing` across translations, permissions, and menus. Add migration for updated key handling [#23](https://github.com/open-dxp/ecommerce-bundle/pull/23) - [CHORE] Update image thumbnail configuration: Move `image-thumbnails.yml` from FrontendBundle to ResourceBundle and adjust references in Configuration [#23](https://github.com/open-dxp/ecommerce-bundle/pull/23) - [BUGFIX] Add existence check before deleting items from OpenSearch index [#24](https://github.com/open-dxp/ecommerce-bundle/pull/24) ### 1.0.1 - [CHORE] Remove redundant `nullable` attributes from Doctrine mapping files and simplify join-column configurations. [#17](https://github.com/open-dxp/ecommerce-bundle/pull/17) - [CHORE] Fix consistency: Rename "opendxp" references to "openDxp" across classes, JSON definitions, and documentation. [#18](https://github.com/open-dxp/ecommerce-bundle/pull/18) - [ENHANCEMENT] Add locale support to address formatting and remove unused prepareAddress method. Fixes [#5](https://github.com/open-dxp/ecommerce-bundle/issues/5) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Remove SEOBundle and related components [#14](https://github.com/open-dxp/ecommerce-bundle/pull/14) - [CHORE] Remove obsolete OpenDxp app migration commands and their service definitions [#15](https://github.com/open-dxp/ecommerce-bundle/pull/15) --- ## Migrating to OpenDXP(Ecommerce) ### Migrating from `coreshop/core-shop` to `open-dxp/ecommerce-bundle:^1.0.1` #### [BC BREAK] Removed Bundles - `SEOBundle` has been removed. Use the OpenDXP Advanced SEO Bundle which supports Ecommerce Bundle out of the box. - `TestBundle` has been removed. Tests run with Pest and `open-dxp/test-foundation`. Use the OpenDXP Testkit. --- #### Naming Overview | Area | Before | After | |-------------------------|---------------------------|---------------------------------------------| | Database tables | `coreshop_*` | `ecommerce_*` | | Pimcore class IDs | `cs_*` | `ec_*` | | Pimcore class names | `CoreShop*` | `Ecommerce*` | | PHP Component namespace | `CoreShop\Component\` | `OpenDxp\Ecommerce\Component\` | | PHP Bundle namespace | `CoreShop\Bundle\` | `OpenDxp\Ecommerce\Bundle\` | | Area | Before | After | |-------------------------|---------------------------|---------------------------------------------| | Config root keys | `core_shop_*` | `opendxp_ecommerce_*` | | Service IDs | `coreshop.*` | `opendxp_ecommerce.*` | | (Static)Route names | `coreshop_*` | `opendxp_ecommerce_*` | | Translation keys | `coreshop.` | `opendxp_ecommerce.` | | State translation keys | `state.coreshop_order` | `state.opendxp_ecommerce_order` | | Security parameters | `coreshop.*` | `opendxp_ecommerce.*` | | Validation groups | `coreshop` / `coreshop_*` | `opendxp_ecommerce` / `opendxp_ecommerce_*` | | ExtJs namespace | `coreshop.` | `opendxp_ecommerce.` | | Admin grid formatters | `coreShopMoney` | `ecommerceMoney` | | Area | Before | After | |-------------------------|---------------------------|---------------------------------------------| | Image thumbnails | `coreshop_*` | `ecommerce_*` | | Twig functions/filters | `coreshop_*` | `ecommerce_*` | | Twig global variable | `coreshop.` | `ecommerce.` | --- #### PHP Namespaces **Components** — `CoreShop\Component\\` → `OpenDxp\Ecommerce\Component\\` **Bundles** — `CoreShop\Bundle\Bundle\` → `OpenDxp\Ecommerce\Bundle\Bundle\` **DataObject model classes** — `Pimcore\Model\DataObject\CoreShop*` → `OpenDxp\Model\DataObject\Ecommerce*` --- #### Service IDs Service ID prefix: `coreshop.` → `opendxp_ecommerce.` Common examples: ```yaml # Before → After @coreshop.cart_item.quantity_modifier → @opendxp_ecommerce.cart_item.quantity_modifier @coreshop.customer.manager → @opendxp_ecommerce.customer.manager @coreshop.repository.carrier → @opendxp_ecommerce.repository.carrier @coreshop.repository.payment_provider → @opendxp_ecommerce.repository.payment_provider @coreshop.repository.store → @opendxp_ecommerce.repository.store @coreshop.repository.tax_rule_group → @opendxp_ecommerce.repository.tax_rule_group @coreshop.repository.order_item → @opendxp_ecommerce.repository.order_item @coreshop.factory.order_item → @opendxp_ecommerce.factory.order_item @coreshop.object.link_generator.category → @opendxp_ecommerce.object.link_generator.category @coreshop.object.link_generator.product → @opendxp_ecommerce.object.link_generator.product @coreshop.storage_list.controller_multi_list.order → @opendxp_ecommerce.storage_list.controller_multi_list.order @coreshop.storage_list.controller.wishlist → @opendxp_ecommerce.storage_list.controller.wishlist ``` --- #### Symfony Configuration **Config root keys:** ```yaml # Before core_shop_core: core_shop_tracking: core_shop_frontend: # After opendxp_ecommerce_core: opendxp_ecommerce_tracking: opendxp_ecommerce_frontend: ``` **Form type extensions** — update `extended_type`: ```php // Before use CoreShop\Bundle\AddressBundle\Form\Type\AddressType; // extended_type: CoreShop\Bundle\AddressBundle\Form\Type\AddressType // After use OpenDxp\Ecommerce\Bundle\AddressBundle\Form\Type\AddressType; // extended_type: OpenDxp\Ecommerce\Bundle\AddressBundle\Form\Type\AddressType ``` --- #### Security Configuration ```yaml parameters: opendxp_ecommerce.security.frontend_regex: "^/(?!admin)[^/]*" opendxp: security: encoder_factories: OpenDxp\Model\DataObject\EcommerceUser: opendxp_ecommerce.security.user.password_hasher_factories security: providers: opendxp_ecommerce_user: id: OpenDxp\Ecommerce\Bundle\CoreBundle\Security\ObjectUserProvider firewalls: opendxp_ecommerce_frontend: provider: opendxp_ecommerce_user pattern: '%opendxp_ecommerce.security.frontend_regex%' form_login: login_path: opendxp_ecommerce_login check_path: opendxp_ecommerce_login_check failure_path: opendxp_ecommerce_login default_target_path: opendxp_ecommerce_index remember_me: name: APP_OPENDXP_ECOMMERCE_REMEMBER_ME logout: path: opendxp_ecommerce_logout target: opendxp_ecommerce_login ``` --- #### Symfony Events ```yaml # Before → After pimcore.dataobject.preAdd → opendxp.dataobject.preAdd pimcore.dataobject.preUpdate → opendxp.dataobject.preUpdate pimcore.dataobject.postAdd → opendxp.dataobject.postAdd pimcore.dataobject.postUpdate → opendxp.dataobject.postUpdate ``` --- #### Static Routes Route names: `coreshop_*` → `opendxp_ecommerce_*` Controller references in route YAML files: ```yaml # Before → After controller: 'CoreShop\Bundle\FrontendBundle\...' → controller: 'OpenDxp\Ecommerce\Bundle\FrontendBundle\...' controller: 'CoreShop\Bundle\PayumBundle\...' → controller: 'OpenDxp\Ecommerce\Bundle\PayumBundle\...' controller: 'coreshop.storage_list.controller_multi_list.order::...' → controller: 'opendxp_ecommerce.storage_list.controller_multi_list.order::...' controller: 'coreshop.storage_list.controller.wishlist::...' → controller: 'opendxp_ecommerce.storage_list.controller.wishlist::...' ``` --- #### Templates (Twig) ```twig {# Route references #} {{ path('coreshop_cart_summary') }} → {{ path('opendxp_ecommerce_cart_summary') }} {{ path('coreshop_index') }} → {{ path('opendxp_ecommerce_index') }} {# Bundle paths #} {% include '@CoreShopFrontend/...' %} → {% include '@EcommerceFrontend/...' %} {# Twig functions/filters (prefix) #} {{ coreshop_price(...) }} → {{ ecommerce_price(...) }} {{ coreshop_money(...) }} → {{ ecommerce_money(...) }} {# Global variable #} {{ coreshop.cart }} → {{ ecommerce.cart }} {{ coreshop.store }} → {{ ecommerce.store }} ``` --- #### Translation Keys ``` # Frontend translations coreshop.* → opendxp_ecommerce.* coreshop.form.* → opendxp_ecommerce.form.* coreshop.ui.* → opendxp_ecommerce.ui.* # Workflow state labels coreshop.ui.workflow.state.coreshop_order.complete → opendxp_ecommerce.ui.workflow.state.order.complete # DB: translations_messages UPDATE translations_messages SET `key` = REPLACE(`key`, 'coreshop.', 'opendxp_ecommerce.') WHERE `key` LIKE 'coreshop.%'; UPDATE translations_messages SET `key` = REPLACE(`key`, 'state.coreshop_', 'state.opendxp_ecommerce_') WHERE `key` LIKE '%state.coreshop_%'; ``` --- #### Database Migration > **⚠ DATA LOSS RISK — read this before touching any class definition files** > > Several Pimcore DataObject class fields were renamed from `pimcore*` / `Pimcore*` to `opendxp*` / `Opendxp*` (e.g., `pimcoreAdjustmentTotalNet` → `openDxpAdjustmentTotalNet`). These `'name'` values in the class definition PHP files map **directly** to database column names. If you modify a definition file and then trigger a class rebuild before renaming the corresponding DB column, OpenDXP creates a new empty column and the original column — with all its data — is left orphaned. > > **Step 5 (column rename) must be completed before any class definition file is modified and before any class rebuild runs.** The exact set of tables depends on your OpenDXP version and project configuration. Use the generator queries below to produce the correct statements for your database — review the output before executing. **1. Rename core tables** (`coreshop_*` → `ecommerce_*`): ```sql SELECT CONCAT('RENAME TABLE `', TABLE_NAME, '` TO `', REPLACE(TABLE_NAME, 'coreshop_', 'ecommerce_'), '`;') FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'coreshop_%' ORDER BY TABLE_NAME; ``` Execute the generated `RENAME TABLE` statements. **2. Drop DataObject views** (`object_cs_*`, recreated automatically by OpenDXP): ```sql SELECT CONCAT('DROP VIEW IF EXISTS `', TABLE_NAME, '`;') FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'VIEW' AND (TABLE_NAME LIKE 'object_cs_%' OR TABLE_NAME LIKE 'object_localized_cs_%') ORDER BY TABLE_NAME; ``` **3. Rename DataObject tables** (`_cs_` → `_ec_`): ```sql SELECT CONCAT('RENAME TABLE `', TABLE_NAME, '` TO `', REPLACE(TABLE_NAME, '_cs_', '_ec_'), '`;') FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME REGEXP '_cs_' AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME; ``` **4. Rename fieldcollection tables** (`object_collection_CoreShop*` → `object_collection_Ecommerce*`): ```sql SELECT CONCAT('RENAME TABLE `', TABLE_NAME, '` TO `', REPLACE(TABLE_NAME, 'CoreShop', 'Ecommerce'), '`;') FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'object_collection_CoreShop%' ORDER BY TABLE_NAME; ``` **5. Rename `pimcore*` columns in DataObject tables** (⚠ must run before class rebuild): First, inspect what needs to change: ```sql SELECT TABLE_NAME, COLUMN_NAME, REPLACE(REPLACE(COLUMN_NAME, 'Pimcore', 'OpenDxp'), 'pimcore', 'openDxp') AS new_name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND (COLUMN_NAME LIKE 'pimcore%' OR COLUMN_NAME LIKE '%Pimcore%') AND TABLE_NAME LIKE 'object_%' ORDER BY TABLE_NAME; ``` Then generate and execute the rename statements: ```sql SELECT CONCAT( 'ALTER TABLE `', TABLE_NAME, '` RENAME COLUMN `', COLUMN_NAME, '` TO `', REPLACE(REPLACE(COLUMN_NAME, 'Pimcore', 'OpenDxp'), 'pimcore', 'openDxp'), '`;' ) AS stmt FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND (COLUMN_NAME LIKE 'pimcore%' OR COLUMN_NAME LIKE '%Pimcore%') AND TABLE_NAME LIKE 'object_%' ORDER BY TABLE_NAME; ``` **6. Update class metadata:** ```sql UPDATE objects SET className = REPLACE(className, 'CoreShop', 'Ecommerce') WHERE className LIKE 'CoreShop%'; UPDATE classes SET id = CONCAT('ec_', SUBSTRING(id, 4)) WHERE id LIKE 'cs_%'; UPDATE classes SET name = CONCAT('Ecommerce', SUBSTRING(name, 9)) WHERE name LIKE 'CoreShop%'; ``` **7. Update translation keys:** ```sql UPDATE translations_messages SET `key` = REPLACE(`key`, 'coreshop.', 'opendxp_ecommerce.') WHERE `key` LIKE 'coreshop.%'; UPDATE translations_messages SET `key` = REPLACE(`key`, 'state.coreshop_', 'state.opendxp_ecommerce_') WHERE `key` LIKE '%state.coreshop_%'; UPDATE translations_admin SET `key` = REPLACE(`key`, 'coreshop_', 'opendxp_ecommerce_') WHERE `key` LIKE 'coreshop_%'; UPDATE translations_admin SET `key` = REPLACE(`key`, 'coreshop.', 'opendxp_ecommerce.') WHERE `key` LIKE 'coreshop.%'; ``` **8. Fix Doctrine type comments:** ```sql ALTER TABLE `ecommerce_payment` MODIFY COLUMN `order` int NOT NULL COMMENT '(DC2Type:opendxpObject)'; ALTER TABLE `ecommerce_product_store_values` MODIFY COLUMN `product` int NOT NULL COMMENT '(DC2Type:opendxpObject)'; ALTER TABLE `ecommerce_product_unit_definitions` MODIFY COLUMN `product` int NOT NULL COMMENT '(DC2Type:opendxpObject)'; ALTER TABLE `ecommerce_carrier` MODIFY COLUMN `logo` int COMMENT '(DC2Type:opendxpAsset)'; ALTER TABLE `ecommerce_payment_provider` MODIFY COLUMN `logo` int COMMENT '(DC2Type:opendxpAsset)'; ``` **9. Legacy cleanup** (`ecommerce_product_store_values` should be available long-term, but in case the legacy table is still present): ```sql DROP TABLE ecommerce_product_store_price; ``` --- #### Filesystem / Config Files **Rename class definition files:** ```bash for f in var/classes/definition_CoreShop*.php; do mv "$f" "${f/definition_CoreShop/definition_Ecommerce}" done ``` **Rename static route files:** ```bash grep -rl "coreshop_" var/config/staticroutes/ | xargs sed -i 's/coreshop_/opendxp_ecommerce_/g' cd var/config/staticroutes && for f in coreshop_*.yaml; do mv "$f" "${f/coreshop_/opendxp_ecommerce_}" done ``` **Rename image thumbnail configs:** ```bash cd var/config/image_thumbnails && for f in coreshop_*.yaml; do sed -i 's/coreshop_/ecommerce_/g' "$f" mv "$f" "${f/coreshop_/ecommerce_}" done ``` --- #### JavaScript / ExtJS Project-local admin JS files use namespace that must be updated: ```bash # Ecommerce namespace: coreshop. → opendxp_ecommerce. find public/admin/js/coreshop -name "*.js" | xargs sed -i "s/coreshop\./opendxp_ecommerce./g" # Rename directory [ -d public/admin/js/coreshop ] && mv public/admin/js/coreshop public/admin/js/opendxp_ecommerce ``` --- #### Backend (Manual Steps) - Rename the data object folder from `coreshop` → `ecommerce` in the Pimcore/OpenDXP backend. - Remove `pimcoreMetaTitle` and `pimcoreMetaDescription` fields from product and category class definitions (removed from bundle). - Update grid configs: replace `coreshop_order_state` → `opendxp_ecommerce_order_state`, `coreshop_price_formatter` → `opendxp_ecommerce_price_formatter`. - Update class definition icons: `/bundles/pimcoreadmin` → `/bundles/opendxpadmin`. --- ## Ecommerce Bundle Ecommerce-Bundle is built on top of the powerful capabilities of OpenDXP, providing a flexible foundation for modern digital commerce. It combines a robust architecture with developer-friendly tools, enabling teams to build highly customizable online shopping experiences, streamline product and order management, and create scalable commerce solutions that go far beyond simple transactions. *** ### Disclaimer > OpenDXP Ecommerce is a community-driven fork based on the CoreShop Community Edition (GPLv3). > OpenDXP Ecommerce is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by CoreShop GmbH. > Original credits: [CoreShop GmbH](https://www.coreshop.com) **OpenDXP is based on the CoreShop Community Edition and remains licensed under GPLv3.** *** ## Further Information - [Documentation](https://docs.opendxp.io/docs/bundles/ecommerce) - [Ecommerce Bundle on Github](https://github.com/open-dxp/ecommerce-bundle) ## Requirements - OpenDXP `^1.3` ## Installation Read our Documentation for the Installation Guide [here](https://docs.opendxp.io/docs/bundles/ecommerce/docs/Getting_Started/Installation) *** ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### Upstream Origin & Version Transparency This project is a fork of the [CoreShop Community Edition (57b1b74 / v4.1.10)](https://github.com/open-dxp/ecommerce-bundle/tree/57b1b74096e8bd26ce9ce747112425b2e018248f), which is © CoreShop GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © CoreShop GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Any use of the CoreShop mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with CoreShop GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of CoreShop GmbH and does **not** purport to replace or supersede any CoreShop offering. --- ## Setup & Configuration ### I. Add Configurable Options Field to Product Class 1. Open `EcommerceProduct` class 1. Add field in section `price_and_units` and name it `configurableOptions` (Title: `Configurable Options`). Choose type from `"OpenDXP Ecommerce" -> "Configurable Options"` 2. Save Product Class ### II. Extend Product Class 1. Change parent of `EcommerceProduct` class (See code below) to allow configurable options 2. Save `EcommerceProduct` Class ##### Product Class ```php

{{ 'opendxp_ecommerce.available_configurable_options'|trans }}

{{ form_row(form.cartItem.configurableOptions) }} {% endif %} ``` ##### Cart/Summary/_item.html.twig Options: Right after `{% if item.getIsGiftItem %} [...] {% endif %}` add: ```twig {% if item|has_configurable_options %}
{{ get_configurable_options_preview(item, true) }}
{% include '@EcommerceConfigurableOptions/Modal/form.html.twig' with {form: form, item_id: item.id} only %} {% endif %} ``` *** Item Price: Instead of `[...]` use the macro: ```twig {# old: {{ currency.convertAndFormat(price) }} [...] #} {% import '@EcommerceConfigurableOptions/Macro/item_price.html.twig' as custom_options_item_price %} {{ custom_options_item_price.create_item_price_list(item, true) }} ``` ##### Checkout/steps/summary/_item.html.twig Options: Right after `{% if item.getIsGiftItem %} [...] {% endif %}` add: ```twig {% if item|has_configurable_options %}
{{ get_configurable_options_preview(item, true) }}
{% endif %} ``` *** Item Price: Instead of `[...]` use the macro: ```twig {# old: {{ currency.convertAndFormat(price) }} [...] #} {% import '@EcommerceConfigurableOptions/Macro/item_price.html.twig' as custom_options_item_price %} {{ custom_options_item_price.create_item_price_list(item, true) }} ``` ##### Common/order_detail.html.twig Options: Right after `{% if item.getIsGiftItem %} [...] {% endif %}` add: ```twig {% if item|has_configurable_options %}
{{ get_configurable_options_preview(item, true) }}
{% endif %} ``` *** Item Price: Instead of `[...]` use the macro: ```twig {# old: {{ currency.format(price, order.getCurrency.isoCode) }} [...] #} {% import '@EcommerceConfigurableOptions/Macro/item_price.html.twig' as custom_options_item_price %} {{ custom_options_item_price.create_item_price_list(item, true, false, order.getCurrency.isoCode) }} ``` ##### Mail/order-confirmation.html.twig There is no item list in ecommerce default mail layout. However, if you want to add this info: ```twig {% if item|has_configurable_options %} {{ get_configurable_options_email_preview(item, true) }} {% endif %} ``` *** ##### Item Price If you need a single calculated item price + options price, you may want to use our simple twig helper: ```twig {% import '@EcommerceConfigurableOptions/Macro/item_price.html.twig' as custom_options_item_price %} {# old: item.getItemPrice() #} {{ custom_options_item_price.create_item_price(item, true, false, order.getCurrency.isoCode) }} ``` --- ## Creating Custom Definitions TBD --- ## Testing(Ecommerce-configurable-options-bundle) The bundle ships a test API under `OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Test`. This page builds on [Testing of the ecommerce bundle](https://docs.opendxp.io/docs/bundles/ecommerce/Getting_Started/Tests). A test creates the options with factories, puts a product into the cart and chooses the options of its item: ```php use OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Test\Factory\ConfigurableOptionsFactory; use OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Test\Factory\DefinitionFactory; use OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Test\Factory\DefinitionOptionFactory; use OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Test\Shop\Options; use OpenDxp\Ecommerce\Test\Factory\ProductFactory; use OpenDxp\Ecommerce\Test\Factory\TaxRuleGroupFactory; use OpenDxp\Ecommerce\Test\Shop\Cart; use OpenDxp\Ecommerce\Test\Story\InstalledShop; it('charges the gift wrap of a shirt', function () { $giftWrap = DefinitionFactory::new() ->withOptions(DefinitionOptionFactory::new()->withPrice(500)) ->create(); $shirt = ProductFactory::new() ->withPrice(2000) ->withTaxRuleGroup( TaxRuleGroupFactory::new() ->taxing(InstalledShop::austria(), 20) ->create(), ) ->create(['configurableOptions' => ConfigurableOptionsFactory::new()->offering(...$giftWrap->getOptions())]); $item = Cart::add($shirt); Options::choose($item, [$giftWrap->getId() => ['checkbox' => '1']]); expect(Cart::current()->getSubtotalNet())->toBe(2500); }); ``` | Class | What it gives you | |---|---| | `Test\Factory\DefinitionFactory` | A definition of an option. It is a checkbox, `choice()` and `customText()` give the other types. `withOptions()` adds the options of the definition. | | `Test\Factory\DefinitionOptionFactory` | An option of a definition. `withPrice()` sets its price in the default store, `withPriceIn()` in another store. The price is net or gross like the prices of the store. | | `Test\Factory\ConfigurableOptionsFactory` | The options a product offers. `offering()` takes options of definitions. The product saves them, so it takes the factory as its value for `configurableOptions`. | | `Test\Shop\Options` | `choose()` chooses options of a cart item through the form of the cart and saves the cart. The form data of each definition is keyed by the id of the definition. | An option takes the tax rate of its product. A product without a tax rule group gives its options no price. The classes of the project need the fields of [Setup & Configuration](01_Configuration.md). --- ## Changelog(Ecommerce-configurable-options-bundle) ### 1.1.0 - [ENHANCEMENT] The installer creates the tables, the field collection `EcommerceConfigurableOption` and the permission, and marks the migrations as executed. `opendxp:bundle:install` is the only step of a new installation (requires `open-dxp/opendxp` ^1.5) - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [NEW FEATURE] A test API for projects under `OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Test`: factories for definitions and the options of a product, and `Options::choose()` for a cart item. See [Tests](docs/20_Tests.md) - [BUGFIX] Net price plus taxes equals the gross price of an order with options - [BUGFIX] The order view shows the charged amount of each option - [CHORE] Require `open-dxp/ecommerce-bundle` ^1.2 ### 1.0.4 - [BUGFIX] [MIGRATION] Fix user permission key to comply with database length constraint ### 1.0.3 - [BUGFIX] Fix cart item resolver ### 1.0.2 - [BUGFIX] Render blocks using `raw` instead of deprecated `spaceless` filter in wrapper template - [BUGFIX] Fix service configuration ### 1.0.1 - [ENHANCEMENT] PHP 8.5 support added - [BUGFIX] Add inversed-by attribute to DefinitionOption relation in Doctrine mapping ### 1.0.0 - [NEW FEATURE] Initial release --- ## Migrating to OpenDXP(Ecommerce-configurable-options-bundle) ### Migrating from `dachcom/coreshop-configurable-options-bundle` to `open-dxp/ecommerce-configurable-options-bundle:^1.0` WARNING! Database tables changed from `coreshop_configurable_options*` to `ecommerce_configurable_options*` - Rename them BEFORE running migrations -> otherwise the bundle migrations will install new tables without any notice! - Delete old migration entries from your `migration_versions` table, if existing #### Further Changes - Namespace changed: `CoreShop\\Bundle\ConfigurableOptionsBundle\` => `OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\` - Fieldcollection name changed: `CoreShopConfigurableOption` => `EcommerceConfigurableOption` - Message Translation keys changed: `coreshop.` => `opendxp_ecommerce.` - Admin Translation keys changed: `coreshop_` => `opendxp_ecommerce_` - Validation Groups, Parameters: `coreshop` => `opendxp_ecommerce` --- ## Ecommerce Configurable Options Bundle ### Release Plan | Release | Supported Ecommerce Versions | Release Date | Maintained | Branch | |---------|------------------------------|--------------|----------------|--------| | **1.x** | `^1.x` | 2026 | Feature Branch | 1.x | ![image](https://github.com/user-attachments/assets/ed74d246-85b5-4ff1-9a53-3045614baeec) ![image](https://github.com/user-attachments/assets/6f636180-fa79-4e1a-b073-4a767ece9a56) ![image](https://github.com/user-attachments/assets/4609a3e8-0d0e-4225-aeb1-2785e48ba897) ![image](https://github.com/user-attachments/assets/9496b44d-9081-4640-9151-bb5f168c3070) ![image](https://github.com/user-attachments/assets/6f1bb934-1bbc-4ba5-ad83-e24152d50e67) ![image](https://github.com/user-attachments/assets/9b1c2f73-6658-4d65-9405-8203261085e0) *** ### Available Types - Checkbox - Custom Text - Choice (Dropdown) *** ### Installation ```json "require": { "open-dxp/ecommerce-configurable-options-bundle": "^1.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\OpenDxpEcommerceConfigurableOptionsBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpEcommerceConfigurableOptionsBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\EcommerceConfigurableOptionsBundle\Migrations'` - Read the [changelog](CHANGELOG.md) before you update. - Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). *** ### Next Steps - [Setup, Configuration](docs/01_Configuration.md) - [Creating Custom Definitions](docs/10_CustomDefinition.md) - [Testing](docs/20_Tests.md) *** ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Using Emailizr with FormBuilder Get FormBuilder [here](https://github.com/open-dxp/formbuilder-bundle). 1. Copy Templates - copy `OpenDxpFormBuilderBundle/Resources/views/email/email.html.twig` to `templates/bundles/OpenDxpFormBuilderBundle/email/email.html.twig` - add your inky data, for example: ```twig {% apply spaceless %} {{ emailizr_style_collector.add('@YourBundle/public/css/style.css') }} {% emailizr_inline_style %} {% block headStyles %} {% endblock %} {% apply inky_to_html %} {% if editmode %}
Admin: {{ 'form_builder.email.placeholder_list_available'|trans({},'admin')|format('%Text(firstname);') }}
{% if document.getProperty('mail_disable_default_mail_body') != true %}
Admin: {{ 'form_builder.email.form_renders_automatically'|trans({},'admin') }}
{% else %}
Admin: {{ 'form_builder.email.custom_style_activated_use_placeholder'|trans({},'admin')|format('%Text(firstname);') }}
{% endif %} {% endif %} {{ opendxp_wysiwyg('text', {width: '500'}) }} {% if document.getProperty('mail_disable_default_mail_body') != true %} {% if editmode != true %}

%Text(body);

{% else %}

{{ 'form_builder.email.form_will_placed_here'|trans({},'admin') }}

{% endif %}
{% endif %} {% endapply %} {% end_emailizr_inline_style %} {% endapply %} ``` - copy `FormBuilder/Resources/views/email/form-data.html.twig` to `templates/bundles/FormBuilderBundle/email/form-data.html.twig` - add your inky data, for example: ```twig {% apply spaceless %} {{ emailizr_style_collector.add('@YourBundle/public/css/style.css') }} {% emailizr_inline_style %} {% apply inky_to_html %} {% for field in fields|default([]) %} {% set value = field.value %} {% if value is iterable %} {% set value = value|join(', ') %} {% endif %} {% if value is not empty %} {{ field.email_label|default(field.label)|raw }}: {{ value }} {% endif %} {% endfor %} {% endapply %} {% end_emailizr_inline_style %} {% endapply %} ``` 2. **Optional**: Using context service to modifiy mail parameter Since you already have parsed all email templates via twig, everything should be fine. It's possible, however, to modify the formdata via the content service: 2.1. Set an Event Listener ```yaml services: _defaults: autowire: true public: false App\EventListener\FormBuilderMailListener: tags: - { name: kernel.event_subscriber } ``` 2.2 Submit Values to Emailizr Parser ```php ['onMailPreSubmit'], ]; } public function onMailPreSubmit(ChannelSubjectGuardEvent $event) { $mail = $event->getSubject(); if(!$mail instanceof \OpenDxp\Mail) { return; } $cssFile = OPENDXP_WEB_ROOT . '/static/css/email.css'; foreach ($mail->getParams() as $key => $value) { $fragment = $this->contentService->checkContent($value, $cssFile, false, true, true); $mail->setParam($key, $fragment); } $event->setSubject($mail); } } ``` --- ## Changelog(Emailizr) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [BUGFIX] Every Twig placeholder in a link or an image source survives the style inlining. Before, only a placeholder that filled the whole link survived, and two of them in one line broke the markup. A placeholder inside a URL, like `mailto:{{ email }}`, stayed encoded - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.1 - [ENHANCEMENT] Add php 8.5 support [#3](https://github.com/open-dxp/emailizr-bundle/pull/3) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix tests [#1](https://github.com/open-dxp/emailizr-bundle/pull/1) --- ## Migrating to OpenDXP(Emailizr) ### Migrating from `dachcom-digital/emailizr` to `open-dxp/emailizr-bundle` 1. Replace `dachcom-digital/emailizr` with `open-dxp/emailizr-bundle` in your `composer.json`. 2. Replace the namespace `EmailizrBundle\` with `OpenDxp\Bundle\EmailizrBundle\`. 3. Replace `EmailizrBundle\EmailizrBundle` with `OpenDxp\Bundle\EmailizrBundle\OpenDxpEmailizrBundle` in `config/bundles.php`. --- ## Emailizr Bundle #### Requirements - OpenDXP ^1.0 - PHP >= 8.3 - Twig >= 3.14 #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.0** | `1.0` | `^7.3` | 2025 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/emailizr-bundle" : "~1.0.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\EmailizrBundle\OpenDxpEmailizrBundle::class => ['all' => true], ]; ``` - Create valid email markup with inky and inline styles. - Respect editables in opendxp edit mode. ### Usage Just extend the emailizr layout: ```twig {% extends '@OpenDxpEmailizr/layout.html.twig' %} ``` This will include a markup like this. You may want to change it: ```twig {% apply spaceless %} {{ emailizr_style_collector.add('@OpenDxpEmailizrBundle/public/css/foundation-for-emails/foundation.min.css') }} {% emailizr_inline_style %} {% block headStyles %} {% endblock %} {% apply inky_to_html %} {% block body %}
{% block content %} {% endblock %}
                                                           
{% endblock %} {% endapply %} {% end_emailizr_inline_style %} {% endapply %} ``` #### Service If you need to parse values in a custom context, you may use the ContentService. ```php contentService->checkContent($content, $cssFile, FALSE, TRUE, TRUE); } } ``` #### Further Information - [Use Emailizr with FormBuilder](docs/10_FormBuilder.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Backend Administration of Forms ### Form Grouping It's possible to group your forms in order keep your form organized. Just define a group name per form and you'll get a folder-organized tree view. ### Meta Information There are some meta information about each form you've created. Just click the blue "Info"-Button in the `Base` Section. | Name | Description | |-------------------|-----------------------------------------------------| | Creation Date | -- | | Modification Date | -- | | User Owner | -- | | User Modification | -- | | Required By | List all Documents which are using the current form | --- ## Export Form It's possible to export submitted form mails as CSV. ### Options | Name | Description |------|------------| | `All` | Export all mails | | `... Output Workflow Name` | Filter by output workflows related to given form | ### Facts - The header gets defined from the field `display_name` property and does not get translated - If you rename the `display_name` afterwards, the new name gets applied in a separat row, no data will be lost --- ## Spam Protection ### Double-Opt-In Read more about the double-opt-in feature [here](./04_DoubleOptIn.md). ### HoneyPot The Honeypot Field is enabled by default. You can disable it via [configuration flags](100_ConfigurationFlags.md). ```yaml form_builder: spam_protection: honeypot: field_name: 'inputUserName' # this is the default value enable_inline_style: true # this is the default value enable_role_attribute: true # this is the default value and will add the role="presentation" attribute ``` *** ### reCAPTCHA v3 reCAPTCHA v3 returns a score for each request without user friction. The score is based on interactions with your site and enables you to take an appropriate action for your site. Register reCAPTCHA v3 keys [here](https://g.co/recaptcha/v3). > **Important!** It is recommended to load the recaptcha api on every page request. > To hide the badge on documents without forms, read our [frontend tips](./90_FrontendTips.md) 1. Get your keys at https://g.co/recaptcha/v3 2. Add site and secret key to your formbuilder settings: ```yaml form_builder: spam_protection: recaptcha_v3: secret_key: 'YOUR_SECRET_KEY' site_key: 'YOUR_SITE_KEY' ``` 3. Add the reCAPTCHA field to your form 4. Enable the reCAPTCHA [javascript module](./91_Javascript.md) 4. Done ### Friendly Captcha Friendly Captcha is a system for preventing spam on your website. You can add the Friendly Captcha widget to your form to fight spam, with little impact to the user experience. 1. Set your application: https://docs.friendlycaptcha.com/#/installation?id=_1-generating-a-sitekey 2. Add site and secret key to your formbuilder settings: ```yaml form_builder: spam_protection: friendly_captcha: secret_key: 'YOUR_SECRET_KEY' site_key: 'YOUR_SITE_KEY' eu_only: false # see https://docs.friendlycaptcha.com/#/eu_endpoint (enterprise only) ``` 3. Add the "Friendly Captcha" field to your form 4. Enable the FriendlyCaptcha [javascript module](./91_Javascript.md) 4. Done *** ### Cloudflare Turnstile Turnstile delivers frustration-free, CAPTCHA-free web experiences to website visitors - with just a simple snippet of free code. Moreover, Turnstile stops abuse and confirms visitors are real without the data privacy concerns or awful user experience of CAPTCHAs. 1. Set your application: https://dash.cloudflare.com/ 2. Add site and secret key to your formbuilder settings: ```yaml form_builder: spam_protection: cloudflare_turnstile: secret_key: 'YOUR_SECRET_KEY' site_key: 'YOUR_SITE_KEY' ``` 3. Add the "Cloudflare Turnstile" field to your form 4. Enable the CloudFlareTurnstile [javascript module](./91_Javascript.md) 4. Done *** ### Math Captcha This simple math captcha form provides a lightweight and session-free way to prevent automated submissions. It offers three difficulty levels, allowing customization based on security needs. The captcha generates random math problems that users must solve before submitting the form. Since no session storage is required, it can be easily integrated with minimal overhead. > [!CAUTION] > The Math captcha doesn't solve the problem of figuring out that a user has previously solved the captcha. > It only protects individual requests and might help if you're in the middle of a spam attack. > However, it will give you time, to set up stronger spam protection like > recaptcha, turnstile or friendly captcha (which are all supported by this bundle) to get rid of smart bots! #### Encryption Secret > [!IMPORTANT] > Math Captcha requires a valid encryption key! > It uses the `%opendxp.encryption.secret%` as default, but you're able to set a dedicated one: ```yaml form_builder: spam_protection: math_captcha: encryption_secret: 'my-very-long-encryption-secret' ``` #### Math Captcha TTL | Expiration To prevent replay attacks in a long-term view, a math captcha gets invalided after 30 minutes. If you want to change the value, you need to update the configuration ```yaml form_builder: spam_protection: math_captcha: hash_ttl: 30 # 30 minutes (default value) ``` *** ### Email Checker The Email Checker Validator is available, if you've added at least one service. Per default, no service is registered by default. This validator includes all services tagged with `form_builder.validator.email_checker`. If one of those services returns false in `isValid()` method, the validator will fail. #### [BUILT IN] Disposable Email Domain Checker If enabled, this checker will fetch every 24h a database (stored in `%kernel.project_dir%/var/tmp/form-builder-email-checker` via flysystem) with known disposable mail hosts from [disposable/disposable](https://github.com/disposable/disposable). After that, the validator will check the given domain of an email address against the database. This service is not available per default and needs to be enabled if you want to use it: ```yaml form_builder: spam_protection: email_checker: disposable_email_domains: enabled: true include_subdomains: false # Also search host as subdomain. Default: false. Note, that this can be a huge performance impact ``` #### Create custom Email Checker ```yaml services: App\Validator\EmailChecker\MyEmailChecker: tags: - { name: form_builder.validator.email_checker } ``` ```php **Important:** It's possible to use multiple forms per page but **never** render the same form twice on the same page! ### Headless Mode If you want to use FormBuilder in headless mode, please check out the documentation [here](./1_HeadlessMode.md). *** ### Usage I. Area Brick This is the most used one. Just place a form element (Area Brick) somewhere on your document. Configure it via the available edit button. #### Options for Usage II. and III. Before we start, check out the available options. Those are (only) needed for the twig and controller rendering type. | Name | Description | |-------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `form_id` | Can you guess it? It's the Form Id, right. | | `form_template` | Form Template, for example: `bootstrap_4_layout.html.twig` | | `main_layout` | This option is only needed if you render a form via a controller. By default, FormBuilder extends a empty default layout. If you want do extend your custom layout, define it: `layout.html.twig` | | `preset` | Optional: set a custom preset | | `custom_options` | Optional (array): Add some custom options as array here to pass them through the whole submission process (available in SubmissionEvent for example | | `output_workflow` | Define, which output workflow should get dispatched after a form has been successfully submitted. You could use the ID or Name of a output workflow | ### Usage II. Twig Create a Form using the Twig Extension. ```twig

Static Form via Twig

{% set config = { 'form_id': 3, 'form_template': 'bootstrap_4_layout.html.twig', 'output_workflow': 'my_output_workflow' 'custom_options': { foo: bar } } %} {{ form_builder_static(config) }}
``` ### Usage III. Controller Create a Form within a Controller. You may have noticed the `main_layout` parameter. This value is important to render your form within a given main layout. ```php 3, 'form_template' => 'bootstrap_4_layout.html.twig', 'main_layout' => 'layout_form.html.twig', // app/Resources/views/layout.html.twig 'output_workflow' => 'my_workflow', // or ID of output workflow 'preset' => null, 'custom_options' => ['foo' => 'bar'] ]; $optionBuilder = new FormOptionsResolver(); $optionBuilder->setFormId($options['form_id']); $optionBuilder->setMainLayout($options['main_layout']); $optionBuilder->setFormTemplate($options['form_template']); $optionBuilder->setOutputWorkflow($options['output_workflow']); $optionBuilder->setFormPreset($options['preset']); $optionBuilder->setCustomOptions($options['custom_options']); /** @var FormAssembler $assembler */ $assembler = $this->container->get(FormAssembler::class); return $this->renderTemplate( '@OpenDxpFormBuilder/Form/form.html.twig', $assembler->assemble($optionBuilder) ); } } ``` --- ## Configuration Flags | Name | Type | Default |------|------|------------| | `use_custom_radio_checkbox` | bool | true | | `use_honeypot_field` | bool | true | *** ### 🚩 use_custom_radio_checkbox flag Change `use_custom_radio_checkbox` to false, if you don't want to use the bootstrap [custom forms](https://symfony.com/doc/current/form/bootstrap4.html#custom-forms). ```yaml form_builder: flags: use_custom_radio_checkbox: false ``` ### 🚩 use_honeypot_field flag Change `use_honeypot_field` to false, if you don't want a honeypot field added to your forms. ```yaml form_builder: flags: use_honeypot_field: false ``` --- ## Custom form templates You can use your own custom form templates. *** ### Configuration If you don't have a configuration file yet, create one `config/packages/form_builder.yaml` ```yaml form_builder: form: templates: my_custom_layout: value: 'my_custom_layout.html.twig' label: 'form_builder_form_template.my_custom_layout' default: false ``` Then you need to create your own templates in the `templates/bundles/OpenDxpFormBuilderBundle/form/theme/` folder `templates/bundles/OpenDxpFormBuilderBundle/form/theme/macro/my_custom_layout.html.twig` ```html {% macro form_builder_form_head() %}
{% endmacro %} {% macro form_builder_form_foot() %}
{% endmacro %} {% macro form_builder_form_message(flash_messages) %} {% if flash_messages is not empty %}
{% for label, messages in flash_messages %} {% for message in messages %}
{{ message|raw }}
{% endfor %} {% endfor %}
{% endif %} {% endmacro %} ``` `templates/bundles/OpenDxpFormBuilderBundle/form/theme/my_custom_layout.html.twig` ```html {% extends 'bootstrap_5_layout.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/dynamic_multi_file.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/html_tag.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/instructions.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/snippet.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/container.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/friendly_captcha.html.twig' %} {% use '@OpenDxpFormBuilder/form/theme/type/cloudflare_turnstile.html.twig' %} {%- block form_widget_compound -%} {%- if form is not rootform -%}
{% endif %} {%- if form is rootform -%} {{ form_errors(form) }} {%- endif -%} {{ block('form_rows') }} {{ form_rest(form) }} {%- if form is not rootform -%}
{% endif %} {%- endblock form_widget_compound -%} {% block checkbox_radio_label %} {# [...] #} {% endblock checkbox_radio_label %} {% block help_text_label %} {# [...] #} {% endblock help_text_label %} {% block form_widget_simple -%} {# [...] #} {%- endblock form_widget_simple %} {% block textarea_widget -%} {# [...] #} {%- endblock textarea_widget %} {% block choice_widget -%} {# [...] #} {%- endblock choice_widget %} {% block checkbox_widget -%} {# [...] #} {%- endblock checkbox_widget %} {% block form_builder_honeypot_row -%} {# [...] #} {%- endblock form_builder_honeypot_row %} {% block form_row -%}
{{ parent() }}
{%- endblock form_row %} {% block button_row -%}
{{ parent() }}
{%- endblock button_row %} {% block checkbox_row -%}
{{ form_widget(form) }} {{ form_errors(form) }}
{%- endblock checkbox_row %} {% block radio_row -%}
{{ form_widget(form) }} {{ form_errors(form) }}
{%- endblock radio_row %} {% block form_builder_friendly_captcha_type_row %}
{{ form_widget(form) }} {{ form_errors(form) }}
{% endblock form_builder_friendly_captcha_type_row %} {% block form_builder_cloudflare_turnstile_type_row %}
{{ form_widget(form) }} {{ form_errors(form) }}
{% endblock form_builder_cloudflare_turnstile_type_row %} {% block form_builder_container_collection_widget %} {%- set attr = attr|merge({class: (attr.class|default('') ~ ' row')|trim}) -%} {{ parent() }} {% endblock form_builder_container_collection_widget %} ``` ! Do not forget to add translations of `form_builder_form_template.my_custom_layout` --- ## Genius(Formbuilder) What the Content Crafter assistant can read and write about forms, and what this bundle registers to make that so. The integration is loaded only where the Content Crafter bundle is installed. - [What this bundle registers](#what-this-bundle-registers) - [Ask about forms, workflows and channels](#ask-about-forms-workflows-and-channels) - [Read a value that cannot be filtered on](#read-a-value-that-cannot-be-filtered-on) - [Ask about the mails a form sent](#ask-about-the-mails-a-form-sent) - [Build a form and its delivery](#build-a-form-and-its-delivery) - [Hold a mail template against the form](#hold-a-mail-template-against-the-form) - [The form open in the editor](#the-form-open-in-the-editor) - [The procedure Genius follows](#the-procedure-genius-follows) - [Call a tool without the chat](#call-a-tool-without-the-chat) ### What this bundle registers Three query domains, each with a query tool and a schema tool. | domain | rows of | search with | fields from | |--------------------------------|---------------------------------------|----------------------------------|--------------------------------------------| | `form` | `formbuilder_forms` | `query_forms` | `get_form_query_schema` | | `form.output_workflow` | `formbuilder_output_workflow` | `query_output_workflows` | `get_output_workflow_query_schema` | | `form.output_workflow_channel` | `formbuilder_output_workflow_channel` | `query_output_workflow_channels` | `get_output_workflow_channel_query_schema` | Two more tools answer about the installation's configuration rather than about rows. | tool | answers | |-------------------------|--------------------------------------------------------------------------------| | `get_form_field_types` | The field types this installation has enabled, and the settings each one takes | | `get_form_placeholders` | What one form can fill into the email template it sends | All eight need the permission `formbuilder_permission_settings`. The six domain tools do not name it themselves. Each domain names it on its entity type, and each tool passes that answer on. Three plan operations write: `form`, `form.output_workflow` and `form.output_workflow_channel`. Each extends `AbstractTableOperation`, so a change and a creation both wait for a reviewer where jobs are reviewed. A row waiting on one of them is about no element: it is named by the form, the workflow or the channel it would write, and there is nothing to open in the backend. ### Ask about forms, workflows and channels A form has output workflows, a workflow has channels, and both hops are `relations` fields that nest. A question spanning all three is one call. ```json {"outputWorkflows": {"any": {"channels": {"any": {"type": "email"}}}}} ``` A nested filter says how many of the rows have to match. `none` instead of `any` is the form for a *without* question, and `any` wrapped in `not` asks something else, see [Filters](https://docs.opendxp.io/docs/bundles/content-crafter/Query_Filters#a-field-that-holds-rows). Sorting and grouping reach one step down, not two. `outputWorkflows.name` groups forms by workflow, `channels.type` groups workflows by kind of delivery, and `outputWorkflows.channels.type` is refused by name. A workflow names its form in `formDefinition`, and a channel names its workflow in `outputWorkflow`. A form lists its workflows, and each of them names its channels by id. `query_output_workflow_channels` reads the channels with their configuration. A field with many rows shows its first 20 and a lookup for the rest, see [Rules](https://docs.opendxp.io/docs/bundles/content-crafter/Rules). ### Read a value that cannot be filtered on Content Crafter builds the fields of a form, a workflow and a channel from their Doctrine mapping. `FormBuilderFieldDescriber` gives them their labels and descriptions. A column whose Doctrine type holds a serialized structure cannot be compared, and the schema reports that as `"notComparable": true`. | archetype | fields marked so | |------------|-----------------------------------------------| | a form | `fields`, `configuration`, `conditionalLogic` | | a workflow | `successManagement` | | a channel | `configuration`, `funnelActions` | They come back with every result and can be read, but nothing inside them can be filtered, sorted, grouped or aggregated on. Narrow with the fields that do have a column, `type` and `name` among them, and read the blob off the rows that came back. The `fields` of a form come back as a list. Each field has its `name`, its `type` and its `label`. The label is a translation key, and `labelTranslated` holds its wording in the language asked for. A container lists its own `fields`. `FormFieldsProcessor` reads them. ### Ask about the mails a form sent `FormMailRelationProvider` links a form and the mail log in both directions, by the form id the email channel writes into the mail's parameters. Two forms can share one email document, so this is the only exact way to ask. | field | on | offered to a user holding | |-------------|------------------|-----------------------------------| | `sentMails` | a form | `emails` | | `form` | a mail log entry | `formbuilder_permission_settings` | Each side is offered only to a user who holds the permission of the side it reaches into, so no tool answers what the other one would refuse. ### Build a form and its delivery The three levels are three steps of one plan, each pointing at the one before it by its `ref`. | operation | needs to create | may change | |----------------------------------|----------------------------------------------|----------------------------| | `form` | `name`, `fields` | `name`, `group`, `fields` | | `form.output_workflow` | `formId`, `name` | `name` | | `form.output_workflow_channel` | `outputWorkflowId`, `name`, `mailTemplateId` | `name`, `mailTemplateId` | A field carries `type`, `name`, `display_name`, `constraints` and `options`. The `type` and `constraints` enums are built from this installation's own form builder configuration, so a type somebody disabled is never offered. `name` is a technical name, lowercase with underscores. The assembler refuses any other name. It also refuses the names the form builder keeps for itself, `name` and `date` among them, the same way the backend editor does. `display_name` is the plain name shown in the backend field list. The label a visitor reads is `options.label`, and that one is written as a translation key such as `formbuilder.form.label.firstname`. Which keys `options` accepts belongs to the field type. `get_form_field_types` called with a type returns them, and a key it does not list is not a setting the form builder knows: the assembler refuses the field and the whole plan with it. ### Hold a mail template against the form `MailParser` replaces a `%name%` it does not recognise with an empty string, without an error and without a log entry. A recipient placeholder one letter off leaves the mail going nowhere. `EmailChannelPlanCheck` judges every email channel of a plan before anyone sees the plan. It takes the form and the template as the plan leaves them. A form, a workflow or a template that another step makes or changes counts with that change. An existing channel is judged as well when a step changes the fields of its form or its template. `MailHeaderCheck` runs the checks over six parts of the template. | checked | refused when | |-----------------------------------------------------------|------------------------------------------------------| | `recipient` | it is empty | | `sender` | it is empty and the system settings name no sender | | `recipient` and `sender` | they are the same address | | `subject`, `recipient`, `sender`, `reply-to`, `cc`, `bcc` | a `%name%` names a field this form does not have | | the same five without `subject` | a `{{ name }}` stands where `%name%` was meant | An address is never made up. When the model cannot fill a missing recipient or sender from the request, the person who asked is told so in their own language. A plan only fills an empty address of an existing template that a channel sends. Other forms may already send with that template, so a step that changes one of its filled addresses is refused. The last check is about addresses only. `Mail::send()` renders the subject through Twig, so both syntaxes resolve there, while an address is never rendered and a `{{ }}` in one becomes the address itself. `EmailDocumentSchemaGuide` says the rest of what an email document is once a form delivers through it: its text is editables rather than fields, and the workflow renders the submitted values into the body itself, so a template that also lists the fields by hand sends everything twice. ### The form open in the editor `FormContextResolver` answers for the context type `formbuilder_form`. With a form open in the backend the request carries its name and id, and says to use the form tools rather than the document or object tools. The form builder area with nothing open answers as that. ### The procedure Genius follows `src/ContentCrafter/Skill/form-builder/SKILL.md` is the written procedure for building the three levels in order. This bundle adds it to Content Crafter's `skills`, so the assistant reads it before it works on a form, see [Configuration](https://docs.opendxp.io/docs/bundles/content-crafter/Configuration#skills). ### Call a tool without the chat The Content Crafter workbench runs any of the eight tools against this installation, under a named backend user and without a model call. ```bash php workbench/bin/tool.php query_forms --user=admin \ --arguments='{"filters":{"outputWorkflows":{"none":{"channels":{"any":{"type":"email"}}}}}}' ``` The bench offers only what its manifest lists, and the manifest shipped with Content Crafter names no other bundle. Put these eight tools into the untracked `manifest.local.json` beside it, see [Add a tool](https://docs.opendxp.io/docs/bundles/content-crafter/extending/Tools#reach-the-tool-at-the-workbench) and [Debugging](https://docs.opendxp.io/docs/bundles/content-crafter/Debugging). --- ## Headless Mode ### AreaBrick You need to create your own editable, depending on your integration. You may want to use the `FormDialogBuilder` to simplify the area configuration section. ### Form Building This is an example, how you may want to build FormBuilder forms in headless mode: ```php $optionBuilder = new FormOptionsResolver(); $optionBuilder->setFormId($formId); $optionBuilder->setFormTemplate($formTemplate); $optionBuilder->setFormPreset($formPreset); $optionBuilder->setOutputWorkflow($formOutputWorkflow); $form = $this->formAssembler->assembleHeadlessForm($optionBuilder); $form->submit($request->request->all()); if (!$form->isValid()) { // process validation errors here return; } $response = null; $submissionEvent = new SubmissionEvent($request, $formRuntimeData, $form, null, false); $this->eventDispatcher->dispatch($submissionEvent, FormBuilderEvents::FORM_SUBMIT_SUCCESS); $finishResponse = $this->formSubmissionFinisher->finishWithSuccess($request, $submissionEvent); if ($finishResponse instanceof RedirectResponse) { return [ 'success' => true, 'redirect' => $finishResponse->getTargetUrl() ]; } if ($finishResponse instanceof JsonResponse) { $response = json_decode($finishResponse->getContent(), true, 512, JSON_THROW_ON_ERROR); } if ($response === null) { throw new \InvalidArgumentException('empty success response'); } if ($response['success'] === false) { if (!array_key_exists('validation_errors', $response)) { return $response; } $validationErrors = $response['validation_errors'] // process validation errors here return null; } return $response; ``` --- ## Testing(Formbuilder) The bundle ships the classes to create forms in the tests of your project, under `OpenDxp\Bundle\FormBuilderBundle\Test`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Building a form ```php use OpenDxp\Bundle\FormBuilderBundle\Test\Brick\FormBrick; use OpenDxp\Bundle\FormBuilderBundle\Test\ConditionalLogic\Action; use OpenDxp\Bundle\FormBuilderBundle\Test\ConditionalLogic\Condition; use OpenDxp\Bundle\FormBuilderBundle\Test\ConditionalLogic\Rule; use OpenDxp\Bundle\FormBuilderBundle\Test\Factory\FormDefinitionFactory; use OpenDxp\Bundle\FormBuilderBundle\Test\Factory\FormFieldDefinitionFactory; use OpenDxp\Bundle\FormBuilderBundle\Test\Factory\OutputWorkflowFactory; use OpenDxp\Bundle\FormBuilderBundle\Test\OutputWorkflow\SuccessMessage; use OpenDxp\Test\Factory\DocumentPageFactory; $form = FormDefinitionFactory::new() ->withFields( FormFieldDefinitionFactory::new()->text()->required()->named('firstname'), FormFieldDefinitionFactory::new()->choice(['Sales' => 'sales', 'Support' => 'support'])->named('topic'), FormFieldDefinitionFactory::new()->submit()->named('send'), ) ->withConditionalLogic( Rule::when(Condition::elementValue(['topic'], 'is_value', 'support')) ->then(Action::toggleElement(['firstname'], 'hide')), ) ->create(); $workflow = OutputWorkflowFactory::new() ->forForm($form) ->withEmailChannel() ->withSuccessMessage(SuccessMessage::text('Thank you, we call you back.')) ->create(); $page = DocumentPageFactory::new() ->withBricks('content', FormBrick::showing($form)->withOutputWorkflow($workflow)) ->create(['key' => 'contact']); ``` ### The form brick `FormBrick` places the form on a page or a snippet, through the page and snippet factories of OpenDXP. `withOutputWorkflow()`, `withFormTemplate()` and `withPreset()` set what an editor chooses in the dialog of the brick. Without a form template, the form renders with `form_div_layout.html.twig`. ### Conditional logic and success messages `Rule::when(...)->then(...)` builds one block of the conditional logic. `Condition` and `Action` have a constructor for each type of the bundle configuration, like `Condition::elementValue()` or `Action::constraintsAdd()`. `SuccessMessage` describes what a visitor sees after a submission: `text()`, `snippet()`, `redirect()` and `externalRedirect()`. Name localized snippets and documents by their locale, like `SuccessMessage::snippet(en: $english, de: $german)`. ### Sending a form as a visitor [`Page`](https://github.com/open-dxp/test-foundation#a-page-as-a-person-uses-it) of the test foundation fills in a form. `FormPage` adds what only the form builder knows: hidden values, the values behind options, uploads and the success message the frontend script shows. ```php use OpenDxp\Bundle\FormBuilderBundle\Test\Frontend\FormPage; use OpenDxp\TestFoundation\Page; it('thanks the visitor', function () { $page = Page::open('/contact') ->fillIn('Firstname', 'Ada') ->select('Topic', 'Sales') ->press('Send'); expect($page->notifications())->toBe(['Thank you, we call you back.']); }); ``` A page that runs the frontend script opens in a real browser. `(new FormPage($page))->send()->waitForSuccessMessage()` then waits for the answer of an AJAX form. The form layouts of the bundle name a success message with `role="status"` and an error with `role="alert"`. A help text describes its field through `aria-describedby`. A date with several inputs, a group of radios or checkboxes and a container each form a group, and the label of the group names it. ### A contact form for your application `ContactFormStory` creates a form and an output workflow, both named "Contact", with fixed fields: `firstname`, `lastname`, `email`, `message` and `send`. A frontend can rely on these values, for example in a headless project that tests its API against an application with real data. The story creates no page, because the template of your project names the areablock that shows the form. ```php use OpenDxp\Bundle\FormBuilderBundle\Test\Story\ContactFormStory; DocumentPageFactory::new() ->withBricks( 'content', FormBrick::showing(ContactFormStory::form())->withOutputWorkflow(ContactFormStory::outputWorkflow()), ) ->create(['key' => 'contact']); ``` ### Test API | Factory | Creates | |---|---| | `FormDefinitionFactory` | A form. `withFields()`, `withConditionalLogic()`, `ajax()`, `inGroup()`, `withAttributes()`, `withConfiguration()`. | | `FormFieldDefinitionFactory` | A field of a form, saved with the form. One state per field type, like `text()`, `textarea()`, `integer()`, `checkbox()`, `choice()`, `country()`, `dynamicChoice()`, `date()`, `time()`, `dateTime()`, `birthday()`, `hidden()`, `dynamicMultiFile()`, `htmlTag()`, `snippet()` and `submit()`. A date or a time in several selects or inputs has a state of its own, like `dateInSelects()` or `timeInInputs()`. Further states: `named()`, `labelled()`, `displayedAs()`, `expanded()`, `multiple()`, `required()`, `withConstraint()`, `withOptions()` and `withOptional()`. | | `FormFieldContainerDefinitionFactory` | A container with fields, `fieldset()` or `repeater()`, with `named()`, `withConfiguration()` and `withFields()`. | | `OutputWorkflowFactory` | An output workflow of a form. `forForm()`, `withChannels()`, `withEmailChannel()`, `withEmailChannelSending()`, `withSuccessMessage()`. | | `OutputWorkflowChannelFactory` | A channel of an output workflow. `email()`, `emailSending()`, `ignoringFields()`, `withoutAttachments()`, `inPlainText()`, `withoutDefaultMailBody()`, `withMailLayout()`. | A field gets its name with `->named('firstname')`. Without a name, the factory makes one up. `email()` creates a mail document that renders the submitted data. `emailSending($template)` sends a mail document of your own. ### The suite of this bundle - `tests/Unit` needs no application. - `tests/Feature` runs against the application, renders forms and sends them through the page. - `tests/Feature/ContentCrafter` tests the integration with Content Crafter through its test API. - `tests/Browser` drives a browser with Playwright. It covers the frontend script, the conditional logic, the repeater, the uploads and the form editor of the backend. These tests form the group `browser`. The browser tests load `@open-dxp/js-formbuilder` from jsDelivr, so they need a connection to the internet. --- ## Ajax Forms #### Activation First, check 'Ajax Submission' in your form configuration. #### Javascript Plugins If you want to use ajax driven forms you need to load the FormBuilder Js-Library. To enable this feature you need the FormBuilder core extension. Please read [this documentation](91_Javascript.md) to learn how to **enable the required plugins**. --- ## Available Form Types There are several form types available (updated continuously). | Name | Group | Description | |----------------------------------------|----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Text | Text Fields | Default input text field. | | Hidden | Hidden Fields | A hidden input field. | | Text Area | Text Fields | Default textarea field. | | Integer | Text Fields | HTML5 Number field. | | Checkbox | Other Fields | Default (single) checkbox field. | | Submit | Buttons | Submit Button. | | Country | Choice Fields | Create a drop down with a default country selection. | | Choice | Choice Fields | Create a (sortable) drop down, multi drop down, multi-checkboxes, multi-radios, checkout [choice meta](90_FrontendTips.md#choice-meta-attributes) for enhanced choice customization | | [Dynamic Choice](82_DynamicChoice.md) | Choice Fields | Create a drop down, multi drop down, multi-checkboxes, multi-radios. Populate Data from a custom Service. | | Html Tag | Other Fields | Create a label, or headline element (tags can be defined via parameter) | | Snippet | Other Fields | Place a custom (localized) snippet in your form. | | [Dynamic Multi File](80_FileUpload.md) | Other Fields | Multi-File Upload field. | | Date | Date and Time Fields | A field that allows the user to modify date information via a variety of different HTML elements. Now supports usage of text- or html5-datetype | | Date Time | Date and Time Fields | This field type allows the user to modify data that represents a specific date and time (e.g. 1984-06-05 12:15:30). | | Time | Date and Time Fields | This can be rendered as a text field, a series of text fields (e.g. hour, minute, second) or a series of select fields. The underlying data can be stored as a DateTime object, a string, a timestamp or an array. | | Birthday | Date and Time Fields | Can be rendered as a single text box, three text boxes (month, day and year), or three select boxes. | | [reCAPTCHA v3](03_SpamProtection.md) | Security Fields | Add an invisible Spam protection to your form. | ## Available Container Form Types There are several container form types available. Read more about the [Container Type](84_ContainerType.md) here. | Name | Group | Description | |----------|-----------|-------------------------------------| | Repeater | Container | Create repeatable field collections | | Fieldset | Container | Create grouped field blocks | ### Constraints | Name | Description | |-------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | NotBlank | Validates that a value is not blank - meaning not equal to a blank string, a blank array or null | | Email | Validates that a value is a valid email address. The underlying value is cast to a string before being validated. | | Length | Validates that a given string length is between some minimum and maximum value. | | Url | Validates that a value is a valid URL string. | | Regex | Validates that a value matches a regular expression. | | IP-Address | Validates that a value is a valid IP address. | | Range | Validates that a given number is between some minimum and maximum number. | | Card Scheme | This constraint ensures that a credit card number is valid for a given credit card company. | | BIC | This constraint is used to ensure that a value has the proper format of a Business Identifier Code (BIC). | | Iban | This constraint is used to ensure that a bank account number has the proper format of an International Bank Account Number (IBAN). | | Date | Validates that a value is a valid date, meaning either a DateTime object or a string (or an object that can be cast into a string) that follows a valid YYYY-MM-DD format. | | DateTime | Validates that a value is a valid "datetime", meaning either a DateTime object or a string (or an object that can be cast into a string) that follows a specific format. | | Time | Validates that a value is a valid time, meaning an object implementing DateTimeInterface or a string (or an object that can be cast into a string) that follows a valid HH:MM:SS format. | ### Enable / Disable Form Types It's possible to enable or disable specific form types. #### Enable specific Elements Only the `hidden` Element is available. ```yaml form_builder: admin: active_elements: fields: - 'hidden' ``` #### Disable specific Elements All Fields except the `hidden` Element are available. ```yaml form_builder: admin: inactive_elements: fields: - 'hidden' ``` > **Note**: If you're using both config elements at the same time, no field will show up (assuming that you're using the example from above) ### Extended Type Configuration #### Html Tag Type To define your custom html tags, add this to your `config/config.yaml': ```yaml parameters: form_builder_html_tag_elements: - ['h1','h1'] - ['h2','h2'] - ['label','label'] - ['p','p'] ``` ### Data Injection If you want to add data to your text fields, based on a specific condition (a query parameter in request for example) you may want to check out [form data injectors](./86_FormDataInjection.md). --- ## Custom Form Type Creating custom types with formbuilder is crazy simple. For example, you can create custom backend options without any javascript implementation. Let's have a look how the choice field has been configured. Of course, you can adopt these settings for your custom form type - just set your class and your good to go. ```yaml form_builder: types: # name your form type choice: # define the class class: Symfony\Component\Form\Extension\Core\Type\ChoiceType # If you need some custom transformers, uncomment these lines: # #output_transformer: my_custom_output_transformer #input_transformer: my_custom_input_transformer backend: # you either use one of those fields # or your could create a custom type group # # - choice_fields # - datetime_fields # - other_fields # - hidden_fields # - buttons # form_type_group: choice_fields # add a label for the field label: 'form_builder_type.choice_type' # add your custom icon class icon_class: 'form_builder_icon_multi_select' # now define some fields fields: # add expanded options since this an available option for the symfony choice type options.expanded: # display_group_id defines in which display group extjs should render this field # it's possible to create custom display groups # or even new tabs for the backend configuration layout display_group_id: attributes # there are several types available. readmore about the backend types below type: checkbox #again, add a label for the backend field label: 'form_builder_type_field.expanded' # no further configuration for a checkbox config: ~ # add multiple options since this an available option for the symfony choice type options.multiple: display_group_id: attributes type: checkbox label: 'form_builder_type_field.multiple' config: ~ # choices: this is a complex one options.choices: display_group_id: attributes type: key_value_repeater label: 'form_builder_type_field.choices' # we need a options transformer. # it transforms backend values into a valid symfony choice values and back. # create your custom transformer, if you need to. options_transformer: OpenDxp\Bundle\FormBuilderBundle\Transformer\ChoicesTransformer config: ~ ``` #### Backend Field Configuration Learn how to [configure the backend fields](50_CustomFormTypeBackendLayout.md). --- ## Custom Form Type Backend Layout #### Available Backend Types Render different configuration types for ExtJs. | Name | Description | |------|-------| | label | Default Label Field | | tagfield | Create a Tagfield with optional predefined options | | numberfield | Default Number Field. | | textfield | Simple Input Field | | select | Dropdown with predefined options | | key_value_repeater | Key-Value Repeater | | options_repeater | Options Repeater | | href | Href-Element for OPENDXP_ Documents | ##### Label -- ##### Tagfield Example ```yaml options.data: display_group_id: base type: tagfield label: 'your label' config: # optional. add a store for customer store: - ['val1', 'Value1'] - ['val2', 'Value2'] - ['val3', 'Value3'] ``` ##### Numberfield -- ##### Textfield -- ##### Select -- ##### Key-Value Repeater -- ##### Options Repeater -- ##### Href -- #### Custom Form Type Groups Add your form type to one of these group fields (Context-Menu). | Name | Description | |------|-------| | text_fields | -- | | choice_fields | -- | | datetime_fields | -- | | other_fields | -- | | field_groups | -- | | hidden_fields | -- | | buttons | -- | #### Tabs Render your form type to a specific tab. | Name | Description | |------|-------| | default | -- | #### Display Groups Render your form type to a specific display group. | Name | Description | |------|-------| | base | -- | | attributes | -- | *** ### Options Transformer Options Transformer will help you to generate valid options for backend and frontend. For example, the (complex) [choices options](http://symfony.com/doc/current/reference/forms/types/choice.html#grouping-options) need to be transformed for the ExtJs context for backend configuration. #### Choices Transformer This transformer will transform the options array into a valid backend configuration array and back. **Example** ```yaml options.choices: display_group_id: attributes type: key_value_repeater label: 'form_builder_type_field.choices' options_transformer: OpenDxp\Bundle\FormBuilderBundle\Transformer\ChoicesTransformer config: ~ ``` #### Default Value Transformer If you want to define a default value, if the user leaves the field empty, you need the default value transformer. In this example the field `placeholder` needs to be a boolean if left empty. Also it should stay empty, if it's get reopened in backend. **Example** ```yaml options.placeholder: display_group_id: attributes type: textfield label: 'form_builder_type_field.placeholder' options_transformer: OpenDxp\Bundle\FormBuilderBundle\Transformer\DefaultValueTransformer config: default_value: false ``` --- ## Using Presets Presets are here to set some additional data for your custom forms ([custom fields](71_DynamicFields.md) for example). #### Example Your customer want's to add a special value (mostly dynamic data) to one or more but specific forms he has just made. Since all forms are dynamically created, you don't know the specific ids where to add all those values. Presets will help you here: Create a preset and add some description to it. From now on, your customer is able to choose between presets within the dropped area element. #### Things to know - If a preset gets selected, form builder will change the layout view to `form/presets/your_preset_name.html.twig` instead of `form/default.html.twig`. - [Create a EventListener](70_Events.md) and add some specific data depending on the selected preset - regardless of the configured form. #### Configuration ```yaml form_builder: area: presets: jobs: # keep it short and simple :) nice_name: 'Short Name' admin_description: 'Description of your Preset' sites: - 'domain1.com' - 'domain2.com' ``` --- ## Events(Formbuilder) It's possible to add some events to every form submission. ### Form Type Options Event The `FORM_TYPE_OPTIONS` event is dispatched after the form builder options has been defined. It contains the field name, type and the defined options. You're able to modify the options only. @see \FormBuilderBundle\Event\Form\FormTypeOptionsEvent **Example** ```php 'formTypeOptions' ]; ``` ### Pre Set Data Event The `FORM_PRE_SET_DATA` event is dispatched at the beginning of the Form::setData() method. It contains the form event and also some form builder settings. @see \FormBuilderBundle\Event\Form\PreSetDataEvent https://symfony.com/doc/current/form/events.html#a-the-formevents-pre-set-data-event **Example** ```php 'formPreSetData' ]; ``` ### Post Set Data Event The `FORM_POST_SET_DATA` event is dispatched at the end of the Form::setData() method. This event is mostly here for reading data after having pre-populated the form. It contains the form event and also some form builder settings. @see \FormBuilderBundle\Event\Form\PostSetDataEvent http://symfony.com/doc/current/form/events.html#b-the-formevents-post-set-data-event **Example** ```php 'formPostSetData' ]; ``` ### Pre Submit Event The `FORM_PRE_SUBMIT` event is dispatched at the end of the Form::setData() method. This event is mostly here for reading data after having pre-populated the form. It contains the form event and also some form builder settings. @see \FormBuilderBundle\Event\Form\PreSubmitEvent https://symfony.com/doc/current/form/events.html#a-the-formevents-pre-submit-event **Example** ```php 'formPreSubmitEvent' ]; ``` ### Submit Success The `FORM_SUBMIT_SUCCESS` event occurs when a frontend form submission was successful. **Example** ```php 'formSubmitSuccess' ]; ``` ### Mail Pre Submit This Event has been marked as deprecated since version 3.3. Use the `OUTPUT_WORKFLOW_GUARD_SUBJECT_PRE_DISPATCH` event instead. The `FORM_MAIL_PRE_SUBMIT` event occurs before sending an email. **Example** ```php 'formMailPreSubmit' ]; ``` ### Output Workflow Guard - Subject Pre Dispatch Read more about this event [here](./OutputWorkflow/30_Events.md). **Example** ```php 'checkSubject' ]; ``` --- ## Custom Fields with Events It's possible to add some custom fields (we call them dynamic fields) to every form. > Info: It's always a good idea to use [presets](60_Presets.md) if you're using custom fields. 1. Register a Listener: ```yaml services: App\EventListener\FormListener: autowire: true tags: - { name: kernel.event_subscriber } ``` 2. To add custom fields, you need to listen to the form pre set data event. > **Important!** Do not add fields to the symfony form directly! > Form Builder will add additional data to your field, like template, order, email label and so on. ```php 'formPreSetData' ]; } public function formPreSetData(PreSetDataEvent $event) { $formEvent = $event->getFormEvent(); /** @var FormDataInterface $formData */ $formData = $formEvent->getData(); /** @var FormDefinitionInterface $formDefinition */ $formDefinition = $formData->getFormDefinition(); // get the form id/name from backend $formId = $formDefinition->getId(); $formName = $formDefinition->getName(); // get form options like the selected form preset $formOptions = $event->getFormOptions(); //add dynamic fields depending on custom presets, is available. var_dump($formOptions['form_preset']); // add your fields $formData->getFormDefinition()->addDynamicField( //field name 'your_dynamic_field_name', //field type EmailType::class, //all the field options [ //no need to add translations here, fb will do this for you. 'label' => 'Your Field Label', 'help_text' => 'Help Text for your Custom Field', 'constraints' => [ new NotBlank(), ] ], //optional options [ //add a template 'template' => 'col-xs-6', //set the order of your field 'order' => 10, //no need to add translations here, fb will do this for you. 'email_label' => 'Your Field Email Label', // form builder usually tries to render the value for the email by itself. //optional: add a output transformer (only affects this element) 'output_transformer' => 'my_output_transformer', ] ); } public function checkValue(FormInterface $field, $value, $locale) { return 'YOUR_TRANSFORMED_VALUE'; } } ``` > Info: Checkout the [dynamic fields with ajax example](72_DynamicFieldsWithAjax.md) to learn how to combine dynamic fields with ajax forms. --- ## Dynamic Fields With Ajax First, be sure you have enabled the [ajax submission mode](20_AjaxForms.md). ### Dynamic Fields and Data in Ajax Forms For example, if you want to add a [dynamic field](71_DynamicFields.md) and fill it with data based on some request information. If you're also using the ajax mode the data gets lost since the ajax request does not contain your special data anymore. To fix this, you need to add some more form events: ```php requestStack = $requestStack; } public static function getSubscribedEvents(): array { return [ FormBuilderEvents::FORM_PRE_SET_DATA => 'formPreSetData', FormBuilderEvents::FORM_PRE_SUBMIT => 'formPreSubmit' ]; } public function formPreSetData(PreSetDataEvent $event): void { $formEvent = $event->getFormEvent(); $formOptions = $event->getFormOptions(); //only apply this to a special preset if ($formOptions['form_preset'] !== 'dynamic_form') { return; } /** @var FormDataInterface $formData */ $formData = $formEvent->getData(); /** @var FormDefinitionInterface $formDefinition */ $formDefinition = $formData->getFormDefinition(); //create some choices based on a request value. $entryId = $this->requestStack->getMainRequest()->get('entry', null); // 1. Add a hidden field to keep the value, // since the request value gets lost during the ajax request. $formDefinition->addDynamicField('entry_id', HiddenType::class,['data' => $entryId]); // 2. Add the dynamic choice field. $this->addEventDateField($formDefinition, $entryId); } public function formPreSubmit(PreSubmitEvent $event): void { $formOptions = $event->getFormOptions(); if ($formOptions['form_preset'] !== 'dynamic_form') { return; } $formEvent = $event->getFormEvent(); /** @var FormInterface $form */ $form = $formEvent->getForm(); /** @var array $formData */ $formData = $formEvent->getData(); /** @var FormDataInterface $dataClass */ $dataClass = $form->getData(); /** @var FormDefinitionInterface $formDefinition */ $formDefinition = $dataClass->getFormDefinition(); // remove entry_id: we don't need it anymore. $formDefinition->removeDynamicField('entry_id'); //re-add the event date and populate it again! $this->addEventDateField($formDefinition, $formData['entry_id']); } private function addEventDateField(FormDefinitionInterface $formDefinition, $id): void { $formDefinition->addDynamicField( 'event_date', ChoiceType::class, [ 'label' => 'Date', 'required' => true, /* * set error_bubbling to "true" if you want to submit error * to main form as "general error". */ 'error_bubbling' => false, /* * Uncomment section if you want some expanded custom bootstrap checkboxes * * 'multiple' => true, * 'expanded' => true, * 'label_attr' => [ * 'class' => 'checkbox-custom' * ], */ 'choices' => $this->getChoices($id), 'constraints' => [ new NotBlank() ] ], /* * This third argument is FormBuilder related stuff. */ [ 'template' => 'col-12', 'order' => 10 ] ); } private function getChoices($id = null): array { if (empty($id)) { return [ 'Test 1' => 'test1', 'Test 2' => 'test2', 'Test 3' => 'test3' ]; } return [ 'Test 1 (for ' . $id . ')' => 'test1', 'Test 2 (for ' . $id . ')' => 'test2', 'Test 3 (for ' . $id . ')' => 'test3' ]; } } ``` --- ## Dynamic Multi File FormBuilder comes with a smart multi-file upload type. It allows you to use different adapters/libraries like DropZoneJs. ### Highlights - File Upload per file type (yes, it's possible to place multiple upload fields per form) - Large File Support: Process chunked files to allow large file uploads - Different adapters: Choose between different upload handler or create a custom one! - Stateless: no session is required to handle file uploads - Different storage principals: Store data as opendxp assets (`/formdata` asset folder) and add a download-link to mail **or** add them as native mail attachments - Stay clean: unsubmitted data / chunk data will be swiped via maintenance - Prebuild Extensions: Use included jQuery extensions to set up your form in the front end in no time! ### Field Configuration There are some options in the (backend) field configuration: | Name | Description | |----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Max File Size` | Max file size will be calculated in MB. Empty or zero means no limit | | `Allowed Extensions` | Define allowed extensions, for example: `pdf, zip` (Format depends on active adapter) | | `Item limit` | The maximum number of files that can be uploaded. Empty or zero means no limit | | `Send Files as Attachment` | All Files will be stored in your opendxp asset structure (/formdata) by default. If you check this option, the files will be attached to the mail instead of adding a download link | ### Setup Per default, DropZone will be used. If you want to change the dmf adapter, you need to define it: ```yaml form_builder: dynamic_multi_file_adapter: OpenDxp\Bundle\FormBuilderBundle\DynamicMultiFile\Adapter\DropZoneAdapter ``` ### Front-End Setup By default, you don't need to implement more than the standard initialization, described in [FormBuilder Javascript Core Extension](./91_Javascript.md). The core extension will try to fetch the handler path, defined by `dynamicMultiFileHandlerOptions.defaultHandlerPath`. ### Security #### Field Reference ```yaml form_builder: security: enable_upload_field_reference: true ``` The Field Reference feature ensures that every uploaded file is associated with an existing form field. When enabled, the client must send a reference to the corresponding form field along with the file. The server validates that the field exists and that the upload complies with the field’s configuration (e.g., allowed file types, maximum upload size). > [!CAUTION] > This option is disabled by default to avoid breaking existing uploads. > Enable it when you want to enforce field-level validation. #### Server MIME Type Validation ```yaml form_builder: security: enable_upload_server_mime_type_validation: true ``` Server MIME Type Validation enforces that uploaded files match the allowed MIME types defined on the server. When enabled, the server checks the actual file content rather than relying solely on file extensions provided by the client. This ensures that only valid file types are accepted, preventing spoofed files or uploads that do not match the allowed formats. > [!CAUTION] >Important: When MIME type validation is active, you must list the allowed MIME types in your form field configuration. > Users can no longer just specify file extensions (like `pdf` or `jpg`); the server will validate the real MIME type of the uploaded file (for example, `application/pdf` or `image/jpeg`). > If the MIME type of the file is not included in the server configuration, the upload will be rejected, even if the file extension appears valid. > Always ensure the MIME types in your configuration match the types you expect to allow for uploads. > [!CAUTION] > Note: This option is disabled by default to maintain backward compatibility. > Enable it when you want the server to strictly validate MIME types for uploaded files. #### Upload Policy Validator The Upload Policy Validator allows projects to define custom security and policy rules for file uploads, such as IP-based rate limits or user-specific upload rules. The bundle itself contains no validation logic or infrastructure dependencies (e.g., cache, Redis, database). Projects provide their own implementation and register it via bundle configuration. ##### Example: IP-Based Rate Limiting A common use case is limiting the number of uploads per IP address within a certain time window. This can be implemented easily using the Symfony RateLimiter component. To keep the limiter lightweight, in this example we use a dedicated APCu cache service. ```yaml form_builder: security: upload_policy_validator: App\Formbuilder\PolicyValidator\UploadedFilePolicyValidator ``` > [!NOTE] > The service must implement the interface `OpenDxp\Bundle\FormBuilderBundle\Validator\Policy\UploadPolicyValidatorInterface`. This configuration defines a sliding-window rate limiter that allows a maximum of 10 uploads per 5 minutes per client: ```yaml # config/packages/rate_limiter.yaml: framework: rate_limiter: form_builder_upload: policy: sliding_window limit: 10 interval: '5 minutes' cache_pool: cache.form_builder_upload_rate_limiter services: cache.form_builder_upload_rate_limiter: class: Symfony\Component\Cache\Adapter\ApcuAdapter arguments: - 'form_builder_upload' - 0 # TTL is set to 0 so entries are not automatically evicted. The RateLimiter manages expiration internally. ``` ```php namespace App\Formbuilder\PolicyValidator; use OpenDxp\Bundle\FormBuilderBundle\Validator\Policy\UploadPolicyValidatorInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\RateLimiter\RateLimiterFactory; use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException; use OpenDxp\Bundle\FormBuilderBundle\Stream\Upload\UploadedFileInterface; class UploadedFilePolicyValidator implements UploadPolicyValidatorInterface { public function __construct(private RateLimiterFactory $formBuilderUploadLimiter) {} public function validate(UploadedFileInterface $file, ?Request $request = null): void { $limiter = $this->formBuilderUploadLimiter->create($request->getClientIp()); $limit = $limiter->consume(1); if (!$limit->isAccepted()) { throw new TooManyRequestsHttpException( null, 'Rate limit exceeded. Please wait before uploading more files.' null, 429 ); } } } ``` *** ### Available Adapter - [DropZoneJs](./DynamicMultiFile/01_DropZoneJs.md) - [Custom Adapter](./DynamicMultiFile/99_CustomAdapter.md) --- ## Conditional Logic ![Condition on a checkbox showing a hidden field](./img/conditional_logic.png) Use the conditional logic to hide/show fields, toggle classes, change validation and more, depending on given field values. ### Preparation - Include the [conditional logic](91_Javascript.md) extension - Add the `fb-cl-hide-element` class with a `display:none;` property to your project style ### Conditions | Name | Description | Options | |------|-------------|---------| | Element Value | Select fields which should have a conditional logic | Types: `contains`, `checked`, `not checked`, `greater than`, `less than`, `value is equal`, `value is not`, `value empty` | | Output Workflow | Select output workflow to apply conditional logic | All available form output workflows | ### Actions | Name | Description | Require Depending Fields | Options | |------|-------------|--------------------------|---------| | Toggle Visibility | Change the visibility of one ore more fields. | Yes | State: `Show`, `Hide` | | Add Validation | Add one or more validations to fields. | Yes | Validation-Types: Drop-Down of given Validations | | Remove Validation | Remove one or more validations of fields. | Yes | All Types: remove all validations of selected fields | | Change Value | Change the value of one ore more fields. | Yes | Value: *mixed* | | Fire JS-Event | Fire custom javascript event of one ore more fields. | Yes | Event Name: *string* (only `a-z0-9.` chars) | | Toggle Classes | Toggle a Class of one ore more fields | Yes | Class Name: *string* | | Toggle Availability | Toggle a availability state | Yes | State: `Enabled`, `Disabled` | | Switch Output Workflow | Switch entire Output Workflow | No | None | | Success Message | Change Success Message (**Warning!** Use this action with caution. If there is no "Output Workflow" condition, this action will apply to all given output workflows of given form) | No | Type: `Text`, `Snippet`, `Redirect to Document`, `Redirect to external Page` | --- ## Dynamic Choice The Dynamic Choice Type allows to generate Drop-Down / Checkbox / Radio Elements with dynamic content. For Example a Product List. ### Usage In the FormBuilder Backend add a "Dynamic Choice Type" Field. There you'll find a "Service Name" Field with the defined Services. In the next Section you'll learn how to add such services. ### Error Handling **Important**: It's not possible to add custom validation messages within the DynamicChoice Service. That's because you're dealing with a already rendered form type (dynamic choice). To add some validations you could use the default constraints in the form builder itself or by extending the default options via [form extensions](http://symfony.com/doc/current/form/create_form_type_extension.html). ### Add Service ```yaml App\Services\FormBuilderBundle\ProductChoices: autowire: true public: false tags: - { name: form_builder.dynamic_choice_builder, label: 'Product Selector' } ``` ### PHP Service (Simple) ```php builder = $builder; // transform data back to string (to display the product name in the email for example) $builder->addModelTransformer(new CallbackTransformer( function ($entries) { return $entries; }, function ($entries) { if (empty($entries)) { return $entries; } if (is_array($entries)) { $data = []; foreach ($entries as $id) { $product = Product::getById($id); $data[] = $product->getName(); } return implode(', ', $data); } else { $product = Product::getById($entries); return $product->getName(); } } )); } public function getList() { $product1 = Product::getById(89); $product2 = Product::getById(47); return [ $product1->getName() => $product1->getId(), $product2->getName() => $product2->getId() ]; } } ``` ### PHP Service (Advanced) You could implement the `AdvancedChoiceBuilderInterface` to get more control about your choice element: ```php getData()`. ### 1.0.1 - [NEW FEATURE] Migrate security feature from legacy source [#13](https://github.com/open-dxp/formbuilder-bundle/pull/13) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Rename form_builder namespace and related identifiers to opendxp_form… [#2](https://github.com/open-dxp/formbuilder-bundle/pull/2) - [CHORE] Update identifiers to `opendxp_form_builder` namespace across FormBuilder bundle [#3](https://github.com/open-dxp/formbuilder-bundle/pull/3) - [BUGFIX] Fixed template paths [#4](https://github.com/open-dxp/formbuilder-bundle/pull/4) - [CHORE] Adjust test matrix [#5](https://github.com/open-dxp/formbuilder-bundle/pull/5) - [CHORE] Fix doc paths [#9](https://github.com/open-dxp/formbuilder-bundle/pull/9) - [CHORE] Adjust Test Setup [#12](https://github.com/open-dxp/formbuilder-bundle/pull/12) - [BUGFIX] Update Form.php [#10](https://github.com/open-dxp/formbuilder-bundle/pull/10) --- ## Dynamic Multi File | DropZone ### Enable Handler ```yaml form_builder: dynamic_multi_file_adapter: OpenDxp\Bundle\FormBuilderBundle\DynamicMultiFile\Adapter\DropZoneAdapter ``` ### Configure Library Learn how to configure this extension in frontend [here](https://github.com/open-dxp/jquery-opendxp-formbuilder/blog/master/docs/11_dmf_fine_uploader.md). ### Field Configuration Notes With DropZone you need to use the mime type in `Allowed Extensions` configuration. Example: `image/jpeg,image/png,image/gif,image/jpg,application/pdf` --- ## Dynamic Multi File | Custom Adapter Creating a custom adapter is quite easy. There are 5 steps to go: - Evaluate your library - Register Services & adjust form builder - Create Form Type - Create Adapter - Create Js Handler *** ### I. Register Services ```yaml services: _defaults: autowire: true autoconfigure: true public: true App\DynamicMultiFile\Adapter\MyUploaderAdapter: tags: - { name: form_builder.dynamic_multi_file.adapter } App\Form\Type\DynamicMultiFile\MyUploaderType: public: false tags: - { name: form.type } ## tell form builder to use your custom adapter form_builder: dynamic_multi_file_adapter: App\DynamicMultiFile\Adapter\MyUploaderAdapter ``` ### II. Override default handler path ```javascript $('form.formbuilder.ajax-form').formBuilderAjaxManager({ dynamicMultiFileHandlerOptions: { // tell form builder core extension where to lazy load your handler from! defaultHandlerPath: '/bundles/app/js/dynamic-multi-file-adapter/lib', // other options will be passed to your new handler // you can define any options here. libPath: 'https://cdnjs.cloudflare.com/ajax/libs/my-3rd-party-lib.min.js', }, }); ``` ### III. Register Services #### FormType ```php vars = array_merge_recursive($view->vars, [ 'attr' => [ 'data-field-id' => $view->parent->vars['id'], 'data-engine-options' => json_encode([ 'multiple' => isset($options['multiple']) ? $options['multiple'] : false, 'max_file_size' => is_numeric($options['max_file_size']) && $options['max_file_size'] > 0 ? $options['max_file_size'] : null, 'item_limit' => is_numeric($options['item_limit']) && $options['item_limit'] > 0 ? $options['item_limit'] : null, 'allowed_extensions' => is_array($options['allowed_extensions']) ? $options['allowed_extensions'] : null, ]), 'class' => join(' ', [ 'dynamic-multi-file', sprintf('element-%s', $view->vars['name']) ]) ] ]); } public function configureOptions(OptionsResolver $resolver): void { // these options are required to support! $resolver->setDefaults([ 'max_file_size' => null, 'allowed_extensions' => [], 'item_limit' => null, 'submit_as_attachment' => false, 'submit_as_admin_deep_link' => false ]); } public function getBlockPrefix(): string { return 'form_builder_dynamicmultifile_my_uploader'; } public function getParent(): string { return TextType::class; } } ``` #### Adapter ```php fileStream = $fileStream; } public function getForm(): string { return MyUploaderType::class; } public function getJsHandler(): string { return 'my-uploader'; } public function onUpload(Request $request): Response { // second argument needs to be false, if you also invoke the onDone action! $result = $this->fileStream->handleUpload([ 'binary' => 'REQUEST_PARAM', // replace REQUEST_PARAM with the mapped request parameter, provided in your JS library 'uuid' => 'REQUEST_PARAM', 'chunkIndex' => 'REQUEST_PARAM', 'totalChunkCount' => 'REQUEST_PARAM', 'totalFileSize' => 'REQUEST_PARAM', ], true); return new JsonResponse($result); } public function onDone(Request $request): Response { // if you need a dedicated endpoint for a chunked upload completion event, // use this action (which is mostly not required) return new JsonResponse([ 'success' => false, 'message' => 'not implemented' ], 403); } public function onDelete(Request $request): Response { // $identifier = mostly the upload uuid $identifier = $request->attributes->get('identifier'); // some libraries will trigger this action after user cancels an active (chunked) file upload $checkChunkFolder = $request->request->get('uploadStatus') === 'canceled'; $result = $this->fileStream->handleDelete($identifier, $checkChunkFolder); return new JsonResponse($result); } } ``` ### IV. Twig Form Theme ```twig {% block form_builder_dynamicmultifile_my_uploader_widget %} {% apply spaceless %}
{# your adapter markup #}
{% endapply %} {% endblock %} ``` ### V. JavaScript Handler ```javascript // assets/js/dynamic-multi-file-adapter/lib/jquery.fb.dmf.my-uploader.js ;(function ($, window) { 'use strict'; function FormBuilderDynamicMultiFileMyUploader() { return this; } $.extend(FormBuilderDynamicMultiFileMyUploader.prototype, { init: function ($form, $dmfFields, dataUrls, options) { if (this.initialized === true) { return; } this.$form = $form; this.$dmfFields = $dmfFields; this.dataUrls = dataUrls; this.options = options; this.initialized = true; this.prepareLibrary(); }, prepareLibrary: function () { if (window.myUploaderLibrary !== undefined) { this.prepareForm(); return; } if (typeof this.options.libPath === 'undefined') { return; } $.getScript(this.options.libPath, function (data, textStatus, jqxhr) { if (jqxhr.status === 200) { this.prepareForm(); } }.bind(this)); }, prepareForm: function () { this.addListener(); this.$dmfFields.each(this.setupMyUploadElement.bind(this)); }, setupMyUploadElement: function (index, el) { var _ = this, $el = $(el), $element = $el.find('.my-uploader-container'), fieldId = $el.data('field-id'), storageFieldId = fieldId + '_data', $storageField = this.$form.find('input[type="hidden"][id="' + storageFieldId + '"]'), config = $el.data('engine-options'), myUploadConfiguration; // this is just an example configuration, // check the corresponding docs provided by your js lib myUploadConfiguration = { addUrl: _.getDataUrl('file_add'), deleteUrl: _.getDataUrl('file_delete'), doneUrl: _.getDataUrl('file_chunk_done'), onAdd: function(response) { this.addToStorageField($storageField, { id: response.uuid, fileName: response.fileName }); }, onRemove: function(response) { this.removeFromStorageField($storageField, { id: response.uuid }); } }; // allow 3rd party hooks this.$form.trigger('formbuilder.dynamic_multi_file.init', [$el, this.options, myUploadConfiguration]); $element.myUploaderLibrary(myUploadConfiguration); }, addToStorageField: function ($storage, newData) { var data = typeof $storage.val() === 'string' && $storage.val() !== '' ? $.parseJSON($storage.val()) : []; data.push(newData); $storage.val(JSON.stringify(data)); }, removeFromStorageField: function ($storage, newData) { var position, data = typeof $storage.val() === 'string' && $storage.val() !== '' ? $.parseJSON($storage.val()) : []; position = $.map(data, function (block) { return block.id }).indexOf(newData.id); if (position === -1) { return; } data.splice(position, 1) $storage.val(JSON.stringify(data)); }, addListener: function () { this.$form.on({ // add events for repeater fields! 'formbuilder.layout.post.add': function (ev, layout) { var $el = $(layout), $instances; $instances = $el.find('[data-dynamic-multi-file-instance]'); if ($instances.length === 0) { return; } $instances.each(this.setupMyUploadElement.bind(this)); }.bind(this), 'formbuilder.layout.pre.remove': function (ev, layout) { var $el = $(layout), $uploadFields; $uploadFields = $el.find('[data-dynamic-multi-file-instance]'); if ($uploadFields.length === 0) { return; } $uploadFields.each(function (index, el) { var $el = $(el), config = $el.data('engine-options'); // check if field has an active upload process. // if so, throw an error which will be catched via alert: // throw new Error('Cannot remove this block.'); }); } }); }, getDataUrl: function (section) { return this.dataUrls[section]; } }); // window instance requires to be called "formBuilderDynamicMultiFileHandler" window.formBuilderDynamicMultiFileHandler = new FormBuilderDynamicMultiFileMyUploader(); })(jQuery, window); ``` --- ## Migrating to OpenDXP(Formbuilder) ### Migrating from dachcom-digital/formbuilder to Version 1.0 #### Global Changes - Changed PHP top-level namespace from `FormBuilderBundle` to `OpenDxp\Bundle\FormBuilderBundle`. - Renamed Bundle from `FormBuilderBundle` to `OpenDxpFormBuilderBundle`. #### Deprecations / Replacements - Support for fineuploader has been removed --- ## API Channel Use the mail channel to submit structured to any kind of API you want. - [Mapping](./09_ApiChannel.md#mapping) | Map form fields to predefined api fields - [API Provider](./09_ApiChannel.md#api-provider) | Create a custom api provider - [Guard Event Listener](./09_ApiChannel.md#guard-event-listener) | Hook into api provider process - [Code Example: Trigger Value](./09_ApiChannel.md#example-trigger-value) | Dispatch Channel by given trigger - [Field Transformer](./16_FieldTransformer.md) *(Optional)* | Use a field transformer to modify single api field values ### Note The FormBuilder API Channel does **not** ship preconfigured API Provider. They can be simple but also complex. But no worries, it's quite easy to integrate your own api provider, read more about it [here](./09_ApiChannel.md#api-provider) ### Available Options | Name | Type | Description | |--------------|------------------------|-----------------------------------------------------| | Api Provider | `ApiProviderInterface` | Select your API Provider. | | Options | `mixed` | If available, various provider configuration fields | ### Mapping ![Form fields mapped to the predefined fields of an API provider](../img/api_channel_mapping.png) If the API Provider supports predefined API fields, you're able to map form fields to these fields which will show up in a dropdown element. If there are no predefined API fields, you need to enter them manually. #### Container "Fieldset" Mapping If an API field is assigned to the fieldset itself, the child elements will be created as an array branch. Otherwise, child elements will be assigned flat. #### Container "Repeater" Mapping If no API field is assigned to the repeater itself, the child elements will be skipped. *** ### API Provider Integrating an api provider is very simple. In this example, we're going to set up an API provider for MailChimp. #### API Configuration Fields Every API Provider is allowed to provide custom configuration fields (see example below). This allows you to select various data for each form (like a campaign ID in MailChimp) #### API Predefined Fields If the API Provider returns predefined you **must** map your form fields with these given fields. > Note! You're allowed to add a predefined only once, but you're allowed to add multiple predefined properties to a single form field! ```bash $ composer require mailchimp/marketing ``` First, we need to register a new service: ```yml AppBundle\FormBuilder\ApiProvider\MailChimpApiProvider: autowire: true public: false tags: - { name: form_builder.api.provider, identifier: mailchimp } ``` Then, we're going to implement the service itself: ```php getClient(); $campaignsData = $mailchimp->campaigns->list(); $campaignStore = []; foreach ($campaignsData->campaigns as $campaign) { $campaignStore[] = [ 'value' => $campaign->id, 'label' => $campaign->settings->title ]; } return [ [ 'type' => 'text', 'label' => 'My Config', 'name' => 'myConfig', 'required' => true, ], [ 'type' => 'select', 'label' => 'Campaign', 'name' => 'campaign', 'store' => $campaignStore, 'required' => true, ] ]; } public function getPredefinedApiFields(FormDefinitionInterface $formDefinition, array $providerConfiguration): array { // maybe they will come from a remote campaign list. // just return an empty array if you don't want to provide predefined api fields. $fields = [ 'EMAIL', 'MMERGE6', 'FNAME', 'LNAME' ]; if ($providerConfiguration['campaign'] === '123') { $fields[] = 'SPECIAL_FIELD'; } return $fields; } public function process(ApiData $apiData): void { $mailchimp = $this->getClient(); $campaignId = $apiData->getProviderConfigurationNode('campaign'); $campaigns = $mailchimp->campaigns->get($campaignId); $body = [ 'status' => 'subscribed', 'email_address' => $apiData->getApiNode('EMAIL'), 'merge_fields' => $apiData->getApiNodes() ]; try { $mailchimp->lists->addListMember($campaignId, $body); } catch(\Throwable $e) { // don't forget to wrap your remote calls in a correct exception: // I. fail silently. no error will be visible to the user // II. OR: only channel should get bypassed (upcoming channels will be processed) // error will be visible to the user after workflow has been completely dispatched throw new GuardChannelException($e->getMessage()); // III. OR: workflow should not go one. cancel from now on // error will be visible to the user after workflow has been completely dispatched throw new GuardOutputWorkflowException($e->getMessage()); } } protected function getClient(): MailchimpMarketing\ApiClient { $mailchimp = new MailchimpMarketing\ApiClient(); $mailchimp->setConfig([ 'apiKey' => 'YOUR_API_KEY', 'server' => 'YOUR_SERVER_PREFIX' ]); return $mailchimp; } } ``` *** ### Guard Event Listener As in every output channel, you're able to hook into the dispatch event via `OUTPUT_WORKFLOW_GUARD_SUBJECT_PRE_DISPATCH` event. ```php 'checkSubject', ]; } public function checkSubject(ChannelSubjectGuardEvent $event): void { $subject = $event->getSubject(); // only apply if subject represents an ApiData instance if (!$subject instanceof ApiData) { return; } // only apply for specific api provider if( $subject->getApiProviderName() !== 'mailchimp') { return; } // different fail scenarios can be applied: $event->shouldFail('My invalid message for a specific channel! Allow further channels to pass!', true); // OR $event->shouldFail('My invalid message! If this happens, no further channel will be executed!', false); // silently skip channel if ($subject->getProviderConfigurationNode('myConfig') === 'a special value') { $event->shouldSuspend(); return; } } } ``` ** ### Example: Trigger Value In some scenarios, you want to trigger your API channel only, if a specific form value is given (A checkbox for example). We'll release this in a [dedicated feature](https://github.com/open-dxp/formbuilder-bundle/issues/304) in upcoming versions. Until then, this can be solved by use a custom provider configuration field: #### Configuration Field First, we have to add a configuration field. Let's call it `consentTriggerValue`: ```php // AppBundle\FormBuilder\ApiProvider\MailChimpApiProvider public function getProviderConfigurationFields(FormDefinitionInterface $formDefinition): array { return [ [ 'type' => 'text', 'label' => 'Consent Trigger Value', 'name' => 'consentTriggerValue', 'required' => false, ], ... ]; } ``` #### Trigger Field Then, we need to add a trigger field. Let's call it `CONSENT_TRIGGER`: ```php // AppBundle\FormBuilder\ApiProvider\MailChimpApiProvider public function getPredefinedApiFields(FormDefinitionInterface $formDefinition, array $providerConfiguration): array { return [ ... 'CONSENT_TRIGGER' ]; } ``` #### Channel Configuration Append our freshly created fields in the API output channel. Set `Consent Trigger Value` to `true` and map your checkbox field to `CONSENT_TRIGGER`. #### Dispatch Process And finally, check given consent value in your `process` method: ```php public function process(ApiData $apiData): void { $consentTriggerValue = $apiData->getProviderConfigurationNode('consentTriggerValue'); // configuration values are always available as strings if ($consentTriggerValue === 'true') { $consentTriggerValue = true; } // in our example we're dealing with a checkbox. // which means that it's not available as node if unchecked if (!$apiData->hasApiNode('CONSENT_TRIGGER')) { return; } // otherwise, it has to be the same value as defined in our configuration node! if ($consentTriggerValue !== $apiData->getApiNode('CONSENT_TRIGGER')) { return; } ... } ``` And you're done. This API channel will only dispatch if a user gives consent to it. --- ## Output Workflows ![Output workflow scenarios with email, object and custom channels](../img/output_workflow_scenarios.png) The Output Workflows allows you to define powerful finishing workflows, after a form has been successfully submitted. To give you a slight overview of the idea behind all this, we'll show you some scenarios you may want to achieve: #### Default Scenario You simply want to send all the form data as email to a given admin and to the user for confirmation. - Create Output Workflow - Add a new Email-Channel and select a valid opendxp mail template - Add another Email-Channel and select a valid opendxp mail template - **Note**: Using the `%FIELD_NAME%` placeholders in the `to` field for example is still valid!) #### Extended Scenario I You want to offer an event registration form. After a client has submitted the form, you want to send him a confirmation email and store the data in a structured DataObject called `Event`. - Create Output Workflow - Add a new Email-Channel and select a valid opendxp mail template - Add a new Object-Channel and select the resolver strategy - Map your form fields with all the object fields of `Event` #### Extended Scenario II You want to offer an event registration form. After a client has submitted the form, you want to send him a confirmation email and submit all the data to some external services via API. - Create Output Workflow - Add a new Email-Channel and select a valid opendxp mail template - Create a [Custom Channel](./12_CustomChannel.md) As you can see, these are powerful tools which allows you to define workflows without writing a single line of code. Want to learn more? Let's start with the [Email Channel](./10_EmailChannel.md). ### Output Workflow Topics - [API Channel](./09_ApiChannel.md) - [Email Channel](./10_EmailChannel.md) - [Object Channel](./11_ObjectChannel.md) - [Custom Channel](./12_CustomChannel.md) - [Input Transformer](./14_InputTransformer.md) - [Output Transformer](./15_OutputTransformer.md) - [Success Management](./20_SuccessManagement.md) - [Events](./30_Events.md) --- ## Email Channel Use the mail channel to submit your form data via email documents. ### Localization You're able to define an email for every given locale, depending on your opendxp system settings. There is also a `Default` fallback field. If a requested locale can't be found during submission, the default configuration will be used. ### Available Options | Name | Type | Description | |-----------------------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Mail Template | OpenDxp Mail Type | Use it to define the mail template via drag'n'drop. | | Ignored Field in Email | Tags | In some cases, you don't want to send specific fields via mail. For example, if you send a copy to the user. Add one or multiple fields as string. *Notice:* The field name needs be identical to the field name in your form configuration. | | Allow Attachment | Checkbox | If this is checked, attachments or attachments-links will be appended to the mail. | | Force Plain Text Submission | Checkbox | If you want to force the plain text submission, you need to check this option. Read more about the submission types [below](./10_EmailChannel.md#mail-submission-types). | | Use custom template fields layout | Checkbox | If this is checked, you need to add your own data to the mail template. You can use all the field names as placeholder. This function is only necessary in rare cases. | | Disable Mail-Logging | Checkbox | If this is checked, no log entry of the sent email will be created. | *** ### Placeholder Place your form somewhere on your Website. If you want to submit the form to the user, you can use your field names as placeholders. Formbuilder automatically will transform the field into the given address. For example, you can set a placeholder called `%emailaddress%` (where *emailaddress* is the name of your form field) in the *To:* field ("Settings" Tab of your email template). **Subject, From, ReplyTo** You also may want to add some placeholder in the subject of your mail template. To do so, just add a placeholder like `%emailaddress%` to the subject field. They will get transformed automatically. > [!NOTE] > If the double-opt-in-feature is enabled, an additional property `double_opt_in_session_email` is available! *** ### Mail Submission Types #### HTML FormBuilder always submits html mails. However, it will also append a text/plain version to each email. With that, the email client is able to choose between html and plain text. #### Plain Text In some cases you may want to force the text/plain submission. To do so, you need to set the [_mail_force_plain_text_ Property](./10_EmailChannel.md#available-options). #### Advanced HTML Templating Use the [emailizr](https://github.com/open-dxp/emailizr-bundle) library to generate simple structured html templates and inline styled markup out of the box. This library does **not** comes with the default FormBuilder installation. #### Configure html2text Options The default html2text options in OPENDXP_ are not quite good enough for real text emails. You may want to change those settings: ```yaml form_builder: email: html_2_text_options: strip_tags: true hard_break: true ``` You'll find all available options directly on GitHub via [thephpleague/html-to-markdown](https://github.com/thephpleague/html-to-markdown) *** ### Mail Layout Editor https://user-images.githubusercontent.com/700119/266572709-6367f49b-9f86-4d5a-8029-45067d629733.png ### Things to know - Always save your form before opening the mail editor *** ### Custom Widget Use the mail editor to specify some special mail templates. It's very easy to add some custom template widgets (Eg. date field). #### Register Service ```yml App\MailEditor\Widget\SpecialWidget: tags: - { name: form_builder.mail_editor.widget, type: special } ``` #### Add PHP Service ```php [ 'type' => 'input', 'defaultValue' => null, 'label' => 'form_builder.mail_editor.widget_provider.special.link' ], ]; } public function getValueForOutput(array $config, string $layoutType) { $form = $config['form']; $link = isset($config['link']) ? $config['link'] : ''; return 'SPECIAL_DATA'; } } ``` ### Template Parser #### Build-In Parser - Inky Parser (Only available if emailizr has been installed) - PlainText Parser #### Custom Template Parser ```yaml App\MailEditor\Parser\TemplateParser\MySpecialParser: tags: - { name: form_builder.mail_editor.template_parser } ``` ```php ', '
'], "\n", $template); } } ``` --- ## Object Channel ![Form fields mapped to the attributes of an Event object](../img/object_channel_mapping.png) Use the object channel to generate or enrich DataObjects. ### Configuration There are two different resolver strategies you can rely on. #### I. Create new Object If you want to create a new object after each form submission, use this one. You need to choose a data class afterward. You're able to map fields and field collections. ##### Options | Name | Description | |-----------------------|---------------------------------------------------| | `Object Storage Path` | Define where all the objects should be stored. | | `Object Class` | Choose, which data object type should be created. | #### II. Use existing Object If you want to append data to a existing object after each form submission, use this one. You need to define an object reference afterwards. **Attention:** You're able to map field collections only! ##### Options | Name | Description | |---------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Referencing Object` | Define where all the objects should be stored. | | `Dynamic Object Resolver` | If any resolver has been registered, you could choose one. Read more about the dynamic object resolver [below](./11_ObjectChannel.md#dynamic-object-resolver). | *** ### Available Mapping Data This table shows all possible data mapping fields: | FormBuilder Type | Allowed OpenDxp Type | |----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------| | `Text` | `Text/Input`, `Text/Textarea`, `Text/Wysiwyg`, `CRM/Firstname`, `CRM/Lastname`, `CRM/Email` | | `Hidden` | `Text/Input`, `Text/Textarea`, `Text/Wysiwyg`, `Relation/Many-to-One-Relation`, `Relation/Many-to-Many-Relation` | | `Text Area` | `Text/Textarea`, `Text/Wysiwyg` | | `Integer` | `Text/Input`, `Text/Textarea`, `Text/Wysiwyg`, `Number/Number`, `Number/Slider`, `Relation/Many-to-One-Relation`, `Relation/Many-to-Many-Relation` | | `Checkbox` | `Other/Checkbox`, `CRM/NewsletterActive`, `CRM/NewsletterConfirmed`, `CRM/Consent` | | `Date` | `Date/Date` | | `Date Time` | `Date/DateTime` | | `Time` | `Date/Time` | | `Birthday` | `Date/Date` | | `Choice` | `Text/Input`,`Select/Select`, `Select/MultiSelect`, `CRM/Gender`, `Relation/Many-to-One-Relation`, `Relation/Many-to-Many-Relation` | | `Dynamic Choice` | `Text/Input`,`Select/Select`, `Select/MultiSelect`, `CRM/Gender`, `Relation/Many-to-One-Relation`, `Relation/Many-to-Many-Relation` | | `Country` | `Text/Input`,`Select/Country`, `Select/Country (MultiSelect)` | | `Html Tag` | unsupported | | `Snippet` | unsupported | | `reCAPTCHA v3` | unsupported | | `Dynamic Multi File` | unsupported | | `Submit` | unsupported | #### Dynamic Choices Mapping If you're using the dynamic choice type mapping, make sure your mapped opendxp field is connected to the same options provider source! ### Container Mapping This Channel also allows you to store `1:N` container data (Repeater, Fieldset) by storing them as a field collection in your data object. You need to add the field collection relation to your form field. After that you're able to sub-map the field collection object. ### Dynamic Object Validation Constraints There are two default validation constrains available within the field collection mapping. | Type | Description | |-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Uniqueness Validation` | If enabled, you need to define a referencing uniqueness field. This will raise an `GuardOutputWorkflowException` exception, if the validation fails. The message will be translated via opendxp translation engine. | | `Count Validation` | If enabled, you ned to define a referencing count field (mostly a number field). This will raise an `GuardOutputWorkflowException` exception, if the validation fails. The message will be translated via opendxp translation engine. | ### Events You're able to implement a guard and enrichment event. Read more about it [here](./30_Events.md). *** ### Dynamic Object Resolver You may want to extend the object channel storage definition to not only store them on a static place but change it individually, based on given form data. A Resolver is strategy aware, which means you're able to define if a resolver should be available for `Existing Objects` or `New Objects` or `both`. There are two ways to do this: Use the runtime data services or create a custom one: #### I. Use Runtime Data Object Resolver > Note: The Runtime Data Object Resolver is only available if you're using the "Use existing Object" strategy! If you need to add more logic, use a custom resolver (see next section "Create a custom Resolver") Example: You want to show some events on your website. Every event has its own detail page on your website. To allow user to apply to your event, you may want to add a form at the bottom of those event pages. To achieve this, you need to do some configuration work. Luckily, FormBuilder ships some pre-configured services, so you only need to configure them properly. ##### I. Add Runtime Data Provider First, you need to determinate an object identifier. Mostly it's an ID in your query string. Were using a [runtime data provider](./../85_RuntimeData.md) to achieve this. ```yaml form_builder.form.runtime_data.event_id_fetcher: class: OpenDxp\Bundle\FormBuilderBundle\Form\RuntimeData\Provider\RequestDataProvider autowire: true arguments: $expr: 'request.query.get("eventId", null)' $runtimeId: 'event_id' tags: - { name: form_builder.runtime_data_provider} ``` ##### II. Add Object Resolver Second, create a dynamic object resolver and append the ID from the runtime data pool. ```yaml form_builder.output_workflow.object.dynamic_object_resolver.event: class: OpenDxp\Bundle\FormBuilderBundle\OutputWorkflow\DynamicObjectResolver\ObjectByRuntimeDataResolver autowire: true arguments: $runtimeDataId: 'event_id' $objectIdentifier: 'name' $isLocalizedValue: false tags: - { name: form_builder.output_workflow.object.dynamic_resolver, identifier: 'my_runtime_object_resolver', label: 'My Runtime Object Resolver'} ``` #### II. Create a custom Resolver ```yaml App\FormBuilder\OutputWorkflow\DynamicObjectResolver\CustomObjectResolver: autowire: true tags: - { name: form_builder.output_workflow.object.dynamic_resolver, identifier: 'my_dynamic_object_resolver', label: 'My Dynamic Object Resolver'} ``` ```php setKey('YOURKEY'); $object->setParent('YOURPARENT'); // return object, the object mapper will do the rest return $object; } } ``` --- ## Custom Output Workflow Channel To create a custom output workflow channel, you need to create some configuration classes. Let's do this! ### Service Definition ```yaml services: App\FormBuilder\MyChannel: tags: - { name: form_builder.output_workflow.channel, type: myChannel } ``` ### Output Transformer Read [here](./15_OutputTransformer.md#custom-output-transformer) how to add a single output transformer to your new custom channel. ### Channel Context Read [here](./13_ChannelContext.md) how to support channel context within your new custom channel. ### PHP Configuration Form Type Class ```php add('myConfigField', TextType::class); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([]); } } ``` ### PHP Service Class ```php getLocale() ?? $submissionEvent->getRequest()->getLocale(); $form = $submissionEvent->getForm(); // Output Transformer (See section "Output Transformer" above). // This is optional, if you don't want to use any output transformer, you could use the raw form values directly. $formData = $this->formValuesOutputApplier->applyForChannel($form, [], 'myChannel', $locale); // now, do your work... } } ``` ### ExtJS Class You need to register this class via `\OpenDxp\Event\BundleManagerEvents::JS_PATHS` Event. Make sure, that you've defined a low priority, to allow loading fb resources first!. ```js opendxp.registerNS('Formbuilder.extjs.formPanel.outputWorkflow.channel.myChannel'); Formbuilder.extjs.formPanel.outputWorkflow.channel.myChannel = Class.create(Formbuilder.extjs.formPanel.outputWorkflow.channel.abstractChannel, { panel: null, getLayout: function () { this.panel = new Ext.form.FormPanel({ title: false, defaults: { labelWidth: 200 }, items: [{ xtype: 'textfield', value: this.data ? this.data.myConfigField : null, fieldLabel: 'My Config Field', name: 'myConfigField' }] }); return this.panel; }, isValid: function () { return this.panel.form.isValid(); }, getValues: function () { return this.panel.form.getValues(); } }); ``` --- ## Channel Context The `ChannelContext` object stores data within a full workflow livecycle. If you need to pass data from one channel to another, this object comes in handy! All core Channels (Email, Object, API) receives the `OpenDxp\Bundle\FormBuilderBundle\OutputWorkflow\Channel\ChannelContext` object ### Channel Context and Signal Storage The Channel Context is also available in Signal Storage (`OutputWorkflowSignalsEvent->getContextItem('channelContext)`). This can be helpful, if you need to clean up data after an exception occurs or the workflow has been completely processed. ### Channel Context in Custom Channel To receive the channel context in a custom channel, you need to implement the `ChannelContextAwareInterface`: > [!IMPORTANT] > If your channel also dispatches a `ChannelSubjectGuardEvent`, > don't forget to pass the channel context to it to pass the context to upcoming channels! If your channel implements the `ChannelContextAwareInterface`, the `OutputWorkflowDispatcher` automatically will inject the active `ChannelContext` object. ```php **Don't get confused!** > Some core output transformers also supports input transformation. > Since we won't the namespace that because of BC reasons, we'll keep it that way (for now). ### Override default Input Transformer If you want to transform the text field value for example, you need to add your own transformer. First, let FormBuilder know about your transformer. > You're also able to set up your custom input transform for your dynamic fields via the `input_transformer` configuration node. ```yaml form_builder: types: text: input_transformer: text_input_transformer ``` Now you need to register your new transformer: ```yaml App\OutputTransformer\TextInputTransformer: autowire: true tags: - { name: form_builder.transformer.input, type: text_input_transformer } ``` *** After that, you have to set up a PHP-Service: ```php You're also able to set up your custom input transform for your dynamic fields via the `input_transformer` configuration node. ```yaml form_builder: types: text: output_transformer: text_input_transformer ``` Now you need to register your new and shiny transformer. Since there is no default text field transformer, you could apply this transformer to all channels. ```yaml App\OutputTransformer\TextInputTransformer: autowire: true tags: - { name: form_builder.transformer.output, type: text_input_transformer, channel: _all } ``` If you want to apply this transformer to the [object output channel](./15_OutputTransformer.md) only, change the channel: ```yaml App\OutputTransformer\TextInputTransformer: autowire: true tags: - { name: form_builder.transformer.output, type: text_input_transformer, channel: object } ``` *** After that, you have to set up a PHP-Service: ```php **Note:** If you don't add any transformer, the `fallback_transformer` will be used again. ```yaml App\OutputTransformer\MyChannelOutputTransformer: autowire: true tags: - { name: form_builder.transformer.output, type: date_transformer, channel: myChannel } - { name: form_builder.transformer.output, type: choice_transformer, channel: myChannel } - { name: form_builder.transformer.output, type: choice_transformer, channel: myChannel } # To use this transformer also for all the other fields, use the fallback_transformer. # In fact, if you're removing the tags above, this fallback will be used on every field - { name: form_builder.transformer.output, type: fallback_transformer, channel: myChannel } ``` ### Target Aware Transformer In some rare cases you may need the target field, before you're able to map the data. In our object output channel for example, it's allowed to map choice values to dropdowns but also to input fields. ```php getRawValue(); $target = $targetAwareData->getTarget(); if ($target instanceof Select) { return is_array($rawValue) ? $rawValue[0] : $rawValue; } elseif ($target instanceof Multiselect) { return !is_array($rawValue) ? [$rawValue] : $rawValue; } elseif ($target instanceof Input) { return is_array($rawValue) ? join(', ', $rawValue) : $rawValue; } return $rawValue; } /** * {@inheritdoc} */ public function getLabel(FieldDefinitionInterface $field, FormInterface $formField, $rawValue, $locale) { return null; } } ``` --- ## Field Transformer Field transformer can be used to transform fields by configuration. For example this comes in handy if you're using the [API Output Channel](./09_ApiChannel.md). The mapping shows the transformer next to the API field. ### Service Registration ```yaml AppBundle\FormBuilder\FieldTransformer\PhoneNumberTransformer: autowire: true public: false tags: - { name: form_builder.output_workflow.field_transform, identifier: phoneNumberTransformer } ``` Within the service, you're able to modify your value. ```php parse($formField->getData(), 'DE'); return $phoneUtil->format($phoneInstance, PhoneNumberFormat::E164); } } ``` --- ## Success Management Each Output Workflow is able to process its own success workflow. #### Simple Text If you're adding a text type, the form is just returning the text value you could use for a output. "Thank you for your message" for example. #### Snippet A Snippet could be useful if you need more output structure. FormBuilder will render the snippet and return its html data. #### Redirect to Document Use a document to get its path to perform a redirect for example. #### Flash Messages on Redirect If you're using `Document` as a success handler you're able to define a flash message. To define a flash message you need to fill out the `Flash Message` below. *** ### Flash Messages Implementation Be sure you have included the twig template somewhere on top in your main layout: ```twig {% include '@OpenDxpFormBuilder/Common/redirect_flash_message.html.twig' %} ``` ### Javascript Example This is how your javascript listener could look like: ```javascript $('form.ajax-form').on('formbuilder.success', function (ev, message, redirect, $form) { if (redirect) { document.location.href = redirect; } else { alert(message[0]['message']); } } ); ``` --- ## Events(OutputWorkflow) ```yaml services: App\FormBuilder\OutputWorkflowEventListener: tags: - { name: kernel.event_subscriber } ``` ```php ['addChannelContextData', 'checkSubject'], ]; } public function addChannelContextData(ChannelSubjectGuardEvent $event): void { // this could be a data object but also a field collection $subject = $event->getSubject(); if ( // if it's a special channel, add some context data to fetch it again in the next channel! $event->getWorkflowName() === 'my_workflow' && $event->getChannelType() === 'mail' && $event->hasChannelContext() ) { $event ->getChannelContext() ->addContextData('special_key', 'my_special_data'); } } public function checkSubject(ChannelSubjectGuardEvent $event): void { // this could be a data object but also a field collection $subject = $event->getSubject(); if ($event->getWorkflowName() === 'my_workflow') { $event->shouldFail('My invalid message for a specific channel! Allow further channels to pass!', true); return; } if ($event->getWorkflowName() === 'my_second_workflow') { $event->shouldFail('My invalid message! If this happens, no further channel will be executed!', false); return; } if ($event->getChannelType() === 'object') { // silently skip channel $event->shouldSuspend(); return; } } } ``` --- ## 40_Funnels ### Funnels The Funnel-Feature allows you to create additional user journeys after the form has been submitted. #### Example In this example, we've implemented a full checkout which allows users to buy goods which they have selected in the initial form builder form. > 💰 **Attention!** The cart feature itself is not available under the open source licence! Below you'll find a brief walk through to get the idea behind this powerful feature: ![Funnel with a summary layer, two channels and a thank you layer](../img/funnel_flow.png) 1. The first Funnel Layer renders a Summary Page (_"Checkout Summary Layer"_) by using a custom snippet. There are two actions: 1. "Buy now" which will lead to the next channel 2. "Back to form", which returns to the (restored) form 2. The Cart Processor Channel processes the Payment itself (Off-Page Payment for example). Every default channel comes with two "virtual funnel actions": 1. "On Success": Which will lead to the next channel 2. "On Error:" "Back to form", which returns to the (restored) form 3. The Email Channel (Which should be familiar to you) triggers an email submission. Since it's also a default chanel, the two virtual funnel actions most be defined: 1. "On Success": Which will lead to the next channel 2. "On Error:" "Back to form", which returns to the (restored) form 4. The last Funnel Layer renders a "Thank You" Page (_"Dynamic Layout Layer"_) by using a custom snippet. There is just one action: 1. "Done": A disabled action, so no button will be rendered *** ### Some important Facts - An existing workflow cannot be transformed into a funnel, just on creation time - A Funnel is not able to process the default success management, use a final funnel layer to restore this feature - The initial form will be stored within a storage provider. By default, a session storage will be shipped, but you're able to create your own storage provider - Every funnel layer creates a physical URL (Initially a UUID/v4 will be generated, but you're able to rename them) - Every funnel layer receives the `SubmissionEvent` object, so you're able to process users data which has been collected via form builders root form - Every funnel layer will be submitted as a form. If a funnel layer provides some additional form data, it will be stored within the storage provider via `FunnelRuntimeData` - After the last channel has been called OR an exception raised, a `funnel_finished` flag will be added to the url. This indicates, that the workflow is done and the current storage will be flushed - If you're using some custom form fields, make sure you've also defined an [Input Transformer](./14_InputTransformer.md)! *** ### Enable Funnel Feature Funnels are disabled by default, so let's enable it: ```yaml form_builder: funnel: enabled: true ``` ### Add Routes Import preconfigured funnel routes from the FormBuilder package or copy them into your project. Don't freak out, we're talking about one tiny route only: ```yaml # config/routes.yaml form_builder_routing_funnels: resource: '@OpenDxpFormBuilderBundle/config/opendxp/routing_funnels.yaml' # or import routes without the {locale} flag in routes # form_builder_routing_funnels: # resource: '@OpenDxpFormBuilderBundle/config/opendxp/routing_funnels_not_localized.yaml' ``` ### Further Information - [Create a Funnel](./Funnel/0_CreateFunnel.md) - [Funnel Layer & Custom Funnel Layers](./Funnel/10_FunnelLayer.md) - [Funnel Actions & Custom Funnel Actions](./Funnel/20_FunnelActions.md) - [Storage Provider & Custom Storage Provider](./Funnel/30_StorageProvider.md) - [Custom Storage Class](./Funnel/40_CustomStorageClass.md) - [Root Form Serialization Groups](./Funnel/50_RootForm.md) --- ## 0_CreateFunnel ### Funnels | Create a Funnel An existing workflow cannot be transformed into a funnel, just on creation time. So after you've clicked the "Add Output Workflow" Button, you need to check the "Is Funnel Output Workflow" #### Funnel Layer Naming Each funnel layer is available within a dedicated route: `/fb/funnel/{funnelId}/{channelId}/{storageToken}`. After you've added a fresh funnel layer, a UUID/V4 as `{channelId}` will be generated. You're able to rename the funnel layer after clicking on the blue pencil. #### The Funnel Layer Every Funnel Workflow comes with a new Channel, called "Funnel Layer". Alright, let's dive deep [into the funnel layers](./10_FunnelLayer.md). --- ## 10_FunnelLayer ### Funnel Layer A Funnel Layer is basically the same as an output workflow you already know. The big difference: It's a real frontend page with different actions, triggered by the user itself. #### Dynamic Layout Layer By default, there is only one layer, a so-called "_Dynamic Layout Layer_". This layer is configured as `dynamicFunnelActionAware`, which means: - that you need to define you're own actions (See next chapter) - that you need to place them in your snippet template So, go ahead, create a snippet and drag it into the "Layout" field. Next, we need to configure some [funnel actions](./20_FunnelActions.md). *** #### Custom Funnel Layer It is very easy to configure a custom funnel layer. ##### Configuration ```yaml services: App\Funnel\DummyLayer: tags: - { name: form_builder.output_workflow.funnel_layer, type: dummyLayer } ``` ##### PHP Service ```php TextType::class, 'options' => [] ]; } public function dynamicFunnelActionAware(): bool { /** * If you're returning true, * user is allowed to define its own funnel actions, * and you should return an empty array in the method below: getFunnelActionDefinitions() */ return false; } public function getFunnelActionDefinitions(): array { /** * If you want to define some predefined actions, * dynamicFunnelActionAware() needs to return false. * Then you're able to add them in your funnel layer layout (see template below) */ return [ new FunnelActionDefinition('dummyButton', 'Top Button') ]; } public function buildForm(FunnelLayerData $funnelLayerData, FormBuilderInterface $formBuilder): void { /** * If you need additional information from a given user, * just add some additional fields to the Layer form type. * You're also able to fetch this submitted data in upcoming channels * via SubmissionEvent->getFunnelRuntimeData() */ $formBuilder->add('consent', CheckboxType::class, ['constraints' => [new IsTrue()]]); } public function handleFormData(FunnelLayerData $funnelLayerData, array $formData): array { return $formData; } public function buildView(FunnelLayerData $funnelLayerData): void { $funnelLayerConfiguration = $funnelLayerData->getFunnelLayerConfiguration(); $viewArguments = [ 'dummyField' => $funnelLayerConfiguration['dummyField'] ]; $funnelLayerData->setFunnelLayerView('/funnel/dummy_layer.html.twig'); $funnelLayerData->setFunnelLayerViewArguments($viewArguments); } } ``` ##### JS Service ```javascript opendxp.registerNS('Formbuilder.extjs.formPanel.outputWorkflow.funnelLayer.dummyLayer'); Formbuilder.extjs.formPanel.outputWorkflow.funnelLayer.dummyLayer = Class.create(Formbuilder.extjs.formPanel.outputWorkflow.funnelLayer.abstractLayer, { getConfigItems: function () { return [ { xtype:'textfield', name: 'dummyField', fieldLabel: 'My Dummy Field' } ]; } }); ``` ##### Twig Partial ```twig {% if formThemePath is not null %} {% form_theme form formThemePath %} {% endif %} {% block funnel_content %} {{ dump(dummyField) }}
{{ form_widget(form.consent) }}
{% if funnelActions.hasByName('dummyButton') %} {{ form_widget(form.dummyButton, {attr: {class: 'btn-primary'}, label: 'Do something' }) }} {% endif %} {% endblock funnel_content %} ``` --- ## 20_FunnelActions ### Funnel: Funnel Actions There are two types of general funnel actions. #### Dynamic Actions If a funnel channel is configured as `dynamicFunnelActionAware`, an admin is able to add 1:n action definitions. Additionally, template placeholder will be available. #### Preconfigured Actions If a funnel channel has preconfigured action definitions by returning an array via `getFunnelActionDefinitions`, an admin is able to set actions to these exact predefined buttons. #### Global Configuration - `Allow Invalid Form Submission`: This allows you to define an action, which skips any form constraints *** #### Funnel Action Types There some predefined funnel action types: ##### Type: Channel Route Action This action navigates to a channel. - `Allow Invalid Form Submission`: This allows you to define an action, which skips any form constraints. ##### Type: Form Route Action This action navigates back to the form. - `Populate Form`: Restores form values ##### Type: Disable Action This action skips any further process (mostly used if a given layer comes with some predefined action definitions) No further configuration needed. This action won't show up in form rendering process. --- ## 30_StorageProvider ### Funnels | Storage Provider By default, FormBuilder uses a session storage provider. It is not required to create a storage provider unless you have to. However, creating a custom storage provider is very easy. Your storage provider needs to implement the `StorageProviderInterface`: #### Configuration ```yaml form_builder: funnel: enabled: true storage_provider: App\Storage\MyStorageProvider ``` #### PHP Service ```php generateToken(); // @todo: store $formStorageData return $token; } public function update(Request $request, string $token, FormStorageData $formStorageData): void { // @todo: update $formStorageData } public function flush(Request $request, string $token): void { // @todo: delete data } public function fetch(Request $request, string $token): ?FormStorageData { // @todo: fetch data } protected function generateToken(): string { // @todo: generate unique token return sprintf('fbst-%s', Uid::v1()->toRfc4122()); } } ``` --- ## 40_CustomStorageClass ### Funnels | Custom Storage Class In some rare scenarios, you may want to extend the signal storage. #### Configuration ```yaml form_builder: funnel: enabled: true signal_storage_class: App\Storage\MySignalStorageClass ``` #### PHP Service ```php context = $context; // @todo: validate context } public function setStorageProvider(StorageProviderInterface $storageProvider): void { $this->storageProvider = $storageProvider; } public function getStorageProvider(): StorageProviderInterface { return $this->storageProvider; } public function storeSignal(OutputWorkflowSignalEvent $signal): void { // @todo: store signal } public function getSignals(): array { // @todo: load signals } } ``` --- ## 50_RootForm ### Funnels | Root Form Some useful hints, if you're going wild with the FormBuilder funnel feature. #### Serialization During the whole funnel workflow process, data gets serialized all the time. While doing this, we're doing this within the group `OutputWorkflow`. If you've extended root forms with some complex form types, make sure your serializer data is configured within the right group: ```yaml # config/serialization/MyEntity.yaml App\Entity\MyEntity: attributes: id: groups: [Default, OutputWorkflow] ``` --- ## FormBuilder Bundle ![Form definition rendered in four ways and finished by an output workflow](docs/img/form_builder_overview.png) #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.x` | `^7.4` | DD.MM.YYYY | Feature Branch | `1.x` | ### Installation ```bash composer require "open-dxp/formbuilder-bundle":"~1.0.0" ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\FormBuilderBundle\OpenDxpFormBuilderBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpFormBuilderBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\FormBuilderBundle\Migrations'` ### Usage 1. Go to `Settings` => `Form Builder Settings` and create your form (Make sure your [spam protection](docs/03_SpamProtection.md) is covered). 2. Open a document and place the form area brick like any other bricks via drag and drop. 3. Use the edit button at the right top corner to configure your form. Also make sure you've included the [flash template](docs/OutputWorkflow/20_SuccessManagement.md#flash-messages-implementation) if you want to have some success messages after a redirect. It's also possible to render a form via Twig or even within a controller method. [Click here](docs/0_Usage.md) to learn more about the form rendering types. ### Overriding Templates Nothing to tell here, it's just [Symfony](https://symfony.com/doc/current/templating/overriding.html) standard. ### Further Information - [Usage (Rendering Types, Configuration)](docs/0_Usage.md) - [Headless Mode](docs/1_HeadlessMode.md) - [SPAM Protection](docs/03_SpamProtection.md) - [Cloudflare Turnstile](docs/03_SpamProtection.md#cloudflare-turnstile) - [FriendlyCaptcha](docs/03_SpamProtection.md#friendly-captcha) - [Honeypot](docs/03_SpamProtection.md#honeypot) - [ReCaptcha V3](docs/03_SpamProtection.md#recaptcha-v3) - [Math Captcha](docs/03_SpamProtection.md#math-captcha) - [Email Checker](docs/03_SpamProtection.md#email-checker) - [Double-Opt-In Feature](docs/04_DoubleOptIn.md) - [Output Workflows](docs/OutputWorkflow/0_Usage.md) - [API Channel](docs/OutputWorkflow/09_ApiChannel.md) - [Email Channel](docs/OutputWorkflow/10_EmailChannel.md) - [Object Channel](docs/OutputWorkflow/11_ObjectChannel.md) - [Custom Channel](docs/OutputWorkflow/12_CustomChannel.md) - [Channel Context](docs/OutputWorkflow/13_ChannelContext.md) - [Output Transformer](docs/OutputWorkflow/15_OutputTransformer.md) - [Field Transformer](docs/OutputWorkflow/16_FieldTransformer.md) - [Success Management](docs/OutputWorkflow/20_SuccessManagement.md) - [Funnels](docs/OutputWorkflow/40_Funnels.md) - [Backend Administration of Forms](docs/01_BackendUsage.md) - [Genius](docs/120_Genius.md) [Ask about forms and the mails they sent, optional] - [Export Forms](docs/02_ExportForms.md) - [Ajax Forms](docs/20_AjaxForms.md) - [Dynamic Fields (Add form elements via events)](docs/71_DynamicFields.md) - [Dynamic Fields with Ajax Forms](docs/72_DynamicFieldsWithAjax.md) - [Available Form Types](docs/30_FormTypes.md) - [Dynamic Choice Type](docs/82_DynamicChoice.md) - [Dynamic Multi File Type](docs/80_FileUpload.md) - [Container Type](docs/84_ContainerType.md) - [Create Custom Form Type](docs/40_CustomFormType.md) - [Custom Form Type Backend Layout](docs/50_CustomFormTypeBackendLayout.md) - [Form Presets](docs/60_Presets.md) - [Events](docs/70_Events.md) - [Mastering File Uploads](docs/80_FileUpload.md) - [DropZoneJs](docs/DynamicMultiFile/01_DropZoneJs.md) - [Custom Adapter](docs/DynamicMultiFile/99_CustomAdapter.md) - [Conditional Logic](docs/81_ConditionalLogic.md) - [Form & Field Attributes](docs/83_Attributes.md) - [Form Runtime Data](docs/85_RuntimeData.md) - [Form Data Injection](docs/86_FormDataInjection.md) - [Frontend Tips](docs/90_FrontendTips.md) - [FormBuilder Javascript Plugins](docs/91_Javascript.md) - [Configuration Flags](docs/100_ConfigurationFlags.md) - [Custom form templates](docs/110_CustomTemplates.md) - [Testing](docs/200_Tests.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## 01_Preparation ### FormBuilder Cart | Preparation ![image](./images/payment-gateways.png) First, you need to enable some payment gateways. You'll find a list of supporting gateways [here](./02_SupportedGateways.md). ### FormBuilder Adjustments - Enable Funnels: https://github.com/open-dxp/formbuilder-bundle/blob/1.x/docs/OutputWorkflow/40_Funnels.md#enable-funnel-feature - Adjust Layout (Extend FormBuilder Layout from FormBuilderCart Layout) ### Form Configuration Enable Funnels: https://github.com/open-dxp/formbuilder-bundle/blob/1.x/docs/OutputWorkflow/40_Funnels.md#enable-funnel-feature ![image](./images/form-elements.png) - Create a Form - Add at least one product - You're able to create a simple product or using an existing product object. This object needs to implement the `OpenDxp\Bundle\FormBuilderCartBundle\Model\ProductInterface` - Add the payment section ### Funnel Configuration - Create a Funnel Workflow - Add a Funnel Layer with Layer `Checkout Summary Layer` - Drag a snippet into the `Layout` relation field - Note: You're not able to set any actions in your snippet. - Adjust the view, if needed: `views/funnel/layer/checkout_summary_layer.html.twig` - Add Channel `Cart Processor` - **Important!** This channel needs to be added **after** the `Checkout Summary Layer` Funnel - Add a final Funnel Layer (For example, the `Dynamic Layout Layer` to show a decent "Thank you" page, but you're able to add additional channels of course) - Connect all Funnel Actions Done! --- ## FormBuilder Cart | Supported Gateways This bundle comes with a list of pre-configured gateways. Some of them have further dependencies, which you have to install manually! #### Offline Simple Gateways, allows payments like `Invoice` or `Prepayment`. > Dependencies: none #### SaferPay Gateway do dispatch payments like `CreditCard`, `Twint`, `Apple Pay`, `Google Pay`, `Postfinance`, `Sofort`... > Dependencies: `karser/payum-saferpay:^0.4` --- ## Changelog(Formbuilder-cart) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.0 - [NEW FEATURE] Initial release --- ## Migrating to OpenDXP(Formbuilder-cart) ### Migrating from `dachcom/pimcore-formbuilder-cart:^2.0` to `open-dxp/formbuilder-cart-bundle:^1.0` - Changed PHP top-level namespace from `FormBuilderCartBundle` to `OpenDxp\Bundle\FormBuilderCartBundle`. - Renamed Bundle from `FormBuilderCartBundle` to `OpenDxpFormBuilderCartBundle`. - Symfony configuration key changed from `form_builder_cart` to `opendxp_form_builder_cart` --- ## FormBuilder Cart Bundle #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|------------------|--------| | **1.x** | `1.3` | `^7.4` | 08.2026 | `Feature Branch` | `1.x` | ### Installation ```json "require": { "open-dxp/formbuilder-cart-bundle" : "~1.0.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\FormBuilderCartBundle\OpenDxpFormBuilderCartBundle::class => ['all' => true], ]; ``` Execute: `$ bin/console opendxp:bundle:install OpenDxpFormBuilderCartBundle` ### Further Information - [Preparation](./docs/01_Preparation.md) - [Supported Gateways](./docs/02_SupportedGateways.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). *** ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Fetch Manager This component will enable the fetch functionality and validation state for invalid fields. - [Enable Component](./01_fetch_manager.md#enable-component) - [Element Transformer](./01_fetch_manager.md#element-transformer) - [Extended Usage](./01_fetch_manager.md#extended-usage) - [Endpoints](./01_fetch_manager.md#endpoints) ### Enable Component ```js import {FetchManager} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new FetchManager(form); }); }); ``` ### Element Transformer #### Predefined Element Transformers Depending on the form template, predefined Element Transformers are used automatically. - Tailwind 2 - Bootstrap 4 - Bootstrap 5 - Bootstrap 3 #### Custom Element Transformers Use the elementTransformer option to customize the validations. Use this option when a custom form template is set. ```js new FetchManager(form, { elementTransformer: { addValidationMessage: (form, field, messages) => { form.classList.add('error-form'); field.classList.add('error-field'); messages.forEach((message) => { let errorEl = document.createElement('div'); errorEl.className = 'error-message'; errorEl.innerText = message; field.after(errorEl); }); }, removeFormValidations: (form) => { form.classList.remove('error-form'); form.querySelectorAll('.error-field').forEach((el) => el.classList.remove('error-field')) form.querySelectorAll('.error-message').forEach((el) => el.remove()); } } }); ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new FetchManager(form, { // avaiable options submitBtnSelector: 'button[type="submit"]', resetFormMethod: (form) => { // set a custom reset function if form has been submitted. Default: null console.log(form); }, onRequestDone: (response, form) => { console.log(response, form); }, onFail: (response, form) => { console.log(response, form); }, onFatalError: (response, form) => { console.log(response, form); }, onErrorField: (fieldError, form) => { console.log(fieldError.field, fieldError.messages, form); }, onGeneralError: (generalErrorMessages, form) => { console.log(generalErrorMessages, form); }, onSuccess: (messages, redirect, form) => { console.log(messages, redirect, form); }, elementTransformer: { addValidationMessage: (form, field, messages) => { console.log(field, messages); }, removeFormValidations: (form) => { console.log(form); } } }); }); }); ``` ### Endpoints To prevent multiple identical requests for the endpoints, create an endpoint instance and set the result to the Fetch Manager. ```js import {Endpoints, FetchManager} from '@open-dxp/js-formbuilder'; let formBuilderForms = document.querySelectorAll('.formbuilder.ajax-form'); if (formBuilderForms.length) { new Endpoints().getEndpoints(formBuilderForms[0].dataset.ajaxStructureUrl) .then((endpoints) => { formBuilderForms.forEach((formBuilderForm) => { new FetchManager(formBuilderForm, {}, endpoints); }); }).catch((error) => { console.error('formbuilder error: fetching file structure', error); }); } ``` --- ## Conditional Logic Component This component will enable the conditional logic functionality. ### Enable Extension ```js import {ConditionalLogic} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new ConditionalLogic(form); }); }); ``` #### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new ConditionalLogic(form, { conditions: {}, actions: { toggleElement: { onEnable: function (action, actionId, ev, el) { console.log(action, ev, el); } } }, elementTransformer: { hide: function (el) { el.classList.add('hidden'); } }, hideElementClass: 'fb-cl-hide-element' }); }); }); ``` --- ## Repeater Component This component will enable the repeater functionality. ### Enable Component ```js import {Repeater} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new Repeater(form); }); }); ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new Repeater(form, { addClass: 'btn btn-info', removeClass: 'btn btn-danger', containerClass: '.formbuilder-container.formbuilder-container-repeater', containerBlockClass: '.formbuilder-container-block', onRemove: (container, cb) => { container.remove(); cb(); // always trigger the callback action! }, onAdd: (container, newForm, cb) => { let parser = new DOMParser(), newBlock = parser.parseFromString(newForm, 'text/html').body.firstChild; container.appendChild(newBlock); cb(newBlock); // always trigger the callback action! }, renderCreateBlockElement: (block, classes, text) => { let element = document.createElement('button'); element.className = classes; element.textContent = text; return element; }, allocateCreateBlockElement: (container, element) => { container.appendChild(element); }, renderRemoveBlockElement: (block, classes, text) => { let element = document.createElement('button'); element.className = classes; element.textContent = text; return element; }, allocateRemoveBlockElement: (block, element) => { block.appendChild(element); }, }); }); }); ``` --- ## Tracker Component This component will enable the tracker functionality. If enabled, this extension tries to submit insensible data like dropdown selection, checked radios/boxes to google analytics or matomo. > **Configuration:**: You need to listen to the `form_builder_submission` event in your tag manager! ### Enable Component ```js import {Tracker} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new Tracker(form); }); }); ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new Tracker(form, { onBeforeSubmitDataToProvider: (data, formName, $form) => { // add some special value to data // warning: in some cases, no data will be submitted (gtag, ga) return data; }, provider: 'google', // choose between "google" or "matomo" trackDropDownSelection: true, trackCheckboxSelection: true, trackRadioSelection: true, trackHiddenInputs: true, invalidFieldNames: ['_token', 'formCl', 'formRuntimeData', 'formRuntimeDataToken'], }); }); }); ``` --- ## reCAPTCHA V3 Component This component will enable reCAPTCHA v3 functionality on your form. Workflow: - Loads `https://www.google.com/recaptcha/api.js` if not available - Adds token to captcha field on your form ### Back-End Configuration First, you need to set up some server side configuration via form builder. Read more about it [here](https://github.com/open-dxp/formbuilder-bundle/blob/master/docs/03_SpamProtection.md#recaptcha-v3). ### Enable Component ```js import {RecaptchaV3} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new RecaptchaV3(form); }); }); ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new RecaptchaV3(form, { disableFormWhileLoading: true, reCaptchaFieldClass: 'input.re-captcha-v3', }); }); }); ``` --- ## Friendly Captcha Component This component will enable Friendly Captcha functionality on your form. ### Back-End Configuration First, you need to set up some server side configuration via form builder. Read more about it [here](https://github.com/open-dxp/formbuilder-bundle/blob/master/docs/03_SpamProtection.md#friendly-captcha). ### Enable Component ```js import {FriendlyCaptcha} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new FriendlyCaptcha(form); }); }); ``` ### Default Options ```js { useAutoWidget: true, autoWidgetVersionToLoad: null, // change to explict version you want to load from cdn: e.g. 0.9.16, null means latest setupField: null, friendlyCaptchaFieldClass: 'div.form-builder-friendly-captcha' } ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new FriendlyCaptcha(form, { useAutoWidget: false, // disable it to use your own implementation (see next option "setupField") setupField: function (element, form, options) { const friendlyCaptionOptions = { doneCallback: function (solution) { console.log("CAPTCHA completed successfully, solution:", solution); }, sitekey: options.sitekey, } const widget = new WidgetInstance(element, friendlyCaptionOptions); widget.start(); formBuilderForm.addEventListener('formbuilder.success', () => widget.reset()); formBuilderForm.addEventListener('formbuilder.error', () => widget.reset()); } }); }); }); ``` --- ## Cloudflare Turnstile Component This component will enable Friendly Captcha functionality on your form. ### Back-End Configuration First, you need to set up some server side configuration via form builder. Read more about it [here](https://github.com/open-dxp/formbuilder-bundle/blob/master/docs/03_SpamProtection.md#friendly-captcha). ### Enable Component ```js import {CloudflareTurnstile} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new CloudflareTurnstile(form); }); }); ``` ### Default Options ```js { useAutoWidget: true, setupField: null, cloudflareTurnstileFieldClass: 'div.form-builder-cloudflare-turnstile', } ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new CloudflareTurnstile(form, { useAutoWidget: false, // disable it to use your own implementation (see next option "setupField") setupField: function (element, form, options) { let setupDispatched = false; const setupTurnstile = function () { let widgetId; // make sure, setup only gets called once! if (setupDispatched === true) { return; } setupDispatched = true; widgetId = turnstile.render(element, { sitekey: options.sitekey, callback: function (token) { console.log(`Challenge Success ${token}`); }, }); formBuilderForm.addEventListener('formbuilder.success', () => turnstile.reset(widgetId)); formBuilderForm.addEventListener('formbuilder.error', () => turnstile.reset(widgetId)); } // load the script with explicit flag // getScript: see @open-dxp/js-formbuilder/src/js/utils/helper.js getScript(`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`, false) .then(() => { turnstile?.ready(() => setupTurnstile()); }) .catch((error) => { console.error(error); }); } }); }); }); ``` --- ## 06_dynamic_multi_file ### Install Dynamic Multi File Handlers Depending on the file handler you want to use, you may need to install some dependencies or include them. - [Drop Zone (default)](./10_dmf_drop_zone.md) > Read more about the dynamic multi file setup [here](https://github.com/open-dxp/formbuilder-bundle/blob/master/docs/80_FileUpload.md) --- ## Dynamic Multi File | DropZone(Formbuilder-js) ![image](https://user-images.githubusercontent.com/700119/119269406-daf90080-bbf7-11eb-9059-01485bf2edf7.png) - Resource: https://www.dropzonejs.com - Handler: `{DropzoneHandler}` - Library: [Dropzone](https://www.npmjs.com/package/dropzone) *** ### Implementation ```bash npm i dropzone ``` #### CSS Include CSS. E.g. `@import "dropzone/dist/dropzone.css";` ### Enable Handler ```js import {DropzoneHandler} from '@open-dxp/js-formbuilder'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new DropzoneHandler(form); }); }); ``` ### Extended Usage ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.formbuilder.ajax-form').forEach((form) => { new DropzoneHandler(form, { dropzoneOptions: { // add some dropzone library options }, }); }); }); ``` ```js import {Endpoints, DropzoneHandler} from '@open-dxp/js-formbuilder'; let formBuilderForms = document.querySelectorAll('.formbuilder.ajax-form'); if (formBuilderForms.length) { new Endpoints().getEndpoints(formBuilderForms[0].dataset.ajaxStructureUrl) .then((endpoints) => { formBuilderForms.forEach((formBuilderForm) => { new DropzoneHandler(form, { dropzoneOptions: { // add some dropzone library options } // set enpoints to prevent multiple identical requests }, endpoints); }); }).catch((error) => { console.error('formbuilder error: fetching file structure', error); }); } ``` --- ## Changelog(Formbuilder-js) ### 1.0.2 - [BUGFIX] Fix the conditional logic for selects, contains, empty groups and the state on load [#3](https://github.com/open-dxp/js-formbuilder/pull/3) ### 1.0.1 - [BUGFIX] Handle undefined `action.fields` in conditional logic listener ID generation [#1](https://github.com/open-dxp/js-formbuilder/pull/1) ### 1.0.0 - [NEW FEATURE] Initial release --- ## FormBuilder JavaScript Extensions We're providing some helpful Javascript Extensions to simplify your daily work with the OpenDXP FormBuilder. This Library provides all JS components for the [OpenDXP FormBuilder Bundle](https://github.com/open-dxp/formbuilder-bundle). ### Installation ```bash npm i @open-dxp/js-formbuilder ``` ### Extensions Overview - [Fetch Manager](./docs/01_fetch_manager.md) - [Conditional Logic Component](./docs/02_conditionalLogic.md) - [Repeater Component](./docs/03_repeater.md) - [Tracker Component](./docs/04_tracker.md) - Spam Protection - [reCAPTCHA V3 Component](./docs/05_1_recaptchaV3.md) - [Friendly Captcha Component](./docs/05_2_friendlyCaptcha.md) - [Cloudflare Turnstile Component](./docs/05_3_cloudflareTurnstile.md) - [Dynamic Multi File Libraries](./docs/06_dynamic_multi_file.md) - [Drop Zone](./docs/10_dmf_drop_zone.md) ### Upgrade Notes #### 1.0.2 - **[BUGFIX]**: Fix the conditional logic for selects, contains, empty groups and the state on load #### 1.0.1 - **[BUGFIX]**: Handle undefined action.fields in listener ID #### 1.0.0 - Initial Release *** ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2025 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Changelog(Formbuilder-subscribe) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.0 - [NEW FEATURE] Initial release --- ## FormBuilder Subscribe Bundle ### Release Plan | Release | Supported Formbuilder Versions | Release Date | Maintained | Branch | |---------|--------------------------------|--------------|----------------|--------| | **1.x** | `^1.x` | 2026 | Feature Branch | 1.x | ![Newsletter form sending its fields through the Brevo API channel to a Brevo contact list](./docs/img/formbuilder_subscribe_api_channel.png) ### Installation ```json "require": { "open-dxp/formbuilder-subscribe-bundle": "^1.0", } ``` Add Bundle to `bundles.php`: ```php return [ # add to bottom OpenDxp\Bundle\FormBuilderSubscribeBundle\OpenDxpFormBuilderSubscribeBundle::class => ['all' => true], ]; ``` ### Configuration #### Brevo Generate or retrieve API key as described [here](https://help.brevo.com/hc/en-us/articles/209467485-Create-and-manage-your-API-keys). ```yaml opendxp_formbuilder_subscribe: brevo: enabled: true api: api_key: 'brevo-api-key' ``` #### Mailchimp Generate or retrieve API key as described [here](https://mailchimp.com/en/help/about-api-keys/#Generate_an_API_key). ```yaml opendxp_formbuilder_subscribe: mailchimp: enabled: true api: api_server: 'mailchimp-api-server' # e.g. us19 api_key: 'mailchimp-api-key' ``` ### FormBuilder API Channel At the moment, only Brevo is supported. Mailchimp coming soon. This bundle provides an API channel for a FormBuilder output workflow to subscribe/unsubscribing from emails lists. 1. In FormBuilder configuration, choose your form and configure your API channel. 2. Select `[FormBuilderSubscribeBundle] Brevo` 3. Configure as desired #### Data Mapping The data mapping editor is enriched with available fields for your brevo contacts. To map a form's field value to a brevo enum field, choose `[FormBuilderSubscribeBundle] Brevo: Attribute Enum Value` as transformer. ![Data mapping of form fields to Brevo fields with the enumeration value transformer](./docs/img/formbuilder_subscribe_data_mapping.png) ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Concepts ### Site-based Host Configuration Each OpenDXP site can be individually configured for the headless bundle. Open **Edit Site** in the context menu of the site's document in the document tree. The settings are in **Additional Settings**. The **Headless** scope provides three settings: | Setting | Type | Description | |--------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------| | **General Domain** | Checkbox | Marks this site as the general domain used across the application. Only one site should be marked at a time. | | **Flush Frontend Cache** | Checkbox | When enabled, this site's frontend receives the cache tags of every change. See [Frontend Cache](28_ConfigurationFrontendCache.md). | | **Asset Base URI** | Text | A base URL prepended to all asset paths for this site. Overrides the global `assets.host` setting. | #### General Domain Mark exactly one site as the **General Domain**. The headless bundle reads this site's main domain and uses it as the application's base host wherever a general domain is needed. The value is cached and automatically cleared when site settings change. #### Asset Base URI Every asset path in API responses gets a base URL prepended to it. The bundle resolves the asset base URI in the following order: 1. **Context site** – if the current request has a headless context site, its **Asset Base URI** setting is used (falling back to the global `assets.host` if not set on the site). 2. **Global `assets.host`** – if no context site is available but `assets.host` is configured, that value is used directly. 3. **General Domain site** – if no context site is available *and* `assets.host` is not configured, the site marked as **General Domain** is used as a fallback source for its **Asset Base URI**. 4. **`null`** – if none of the above apply, no base URI is prepended. > See [Asset Routing](21_ConfigurationRouting.md#asset-routing) for the global `assets.host` configuration. #### Flush Frontend Cache Sites with **Flush Frontend Cache** enabled receive the cache tags of every change at their frontend. The URL is built from the site's main domain and the configured path: ``` https://{site.mainDomain}{frontend_cache.path} ``` Each enabled site gets its own request. See [Frontend Cache](28_ConfigurationFrontendCache.md). --- ## Authentication & Certification ### Certificate Put certificate in a folder of your choice (mind security!), e.g. `config/jwt`: #### Create a JWT Secret ```bash $ vendor/bin/generate-defuse-key ``` ```bash cd openssl genrsa -out private.pem -aes256 4096 # use jwt secret openssl rsa -pubout -in private.pem -out public.pem # use jwt secret ``` #### Add Variables in Your CI/CD Platform ```dotenv JWT_PASSPHRASE=[YOUR_JWT_PASSPHRASE] JWT_PUBLIC_KEY=/public.pem JWT_SECRET_KEY=/private.pem ``` #### JWT Authentication ```dotenv # .env.local JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/dev_private.pem JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/dev_public.pem JWT_PASSPHRASE=not-a-secure-passphrase-for-development ``` ### Authentication This Bundle only supports User's which are OpenDXP DataObjects (so far). The default class name is `User` (which resolves to `\OpenDxp\Model\DataObject\User`), and is identified by the field `loginIdentifier`. The user class **needs to implement** `OpenDxp\Bundle\HeadlessBundle\Model\ApiUserInterface`. You can use the class definition from `/config/install/class_User_export.json` if you want the default `User` class. There is also a default class `OpenDxp\Bundle\HeadlessBundle\Model\ApiUser`, which can be used as parent class for your user class (e.g. `App\Model\MyUser` extends `OpenDxp\Bundle\HeadlessBundle\Model\ApiUser`). #### Custom User class You can override the class name and the identifier field as follows: ```yaml opendxp_headless: api_user: class_name: MyUser identity_field: myIdentifierField ``` Keep in mind, that if you change this config, you need to adjust your user implementation accordingly, to fulfill `ApiUserInterface`, e.g. ```php public function getLoginIdentifier(): ?string { return $this->getMyIdentifierField(); } // etc. ``` #### Login Identifier / Email Address By default, the login identifier is also used as the user's email address. In this case, the following validation configuration should be set in the project: ```yaml # config/validator/RequestChangeLoginIdentifierTokenCommand.yaml OpenDxp\Bundle\HeadlessBundle\Domain\Account\Command\RequestChangeLoginIdentifierTokenCommand: properties: newLoginIdentifier: - Email: ~ ``` If the login identifier does not correspond to the email address (e.g., username), make sure to implement the `getEmailAddress()` method of `ApiUserInterface` accordingly to return user's email. #### Impersonation An api user with the role `ROLE_ALLOWED_TO_IMPERSONATE` acts as another user by sending the target's login identifier in the `X-OpenDxp-Api-Impersonate` header on the request. The caller authenticates with its own JWT on every request; the header is handled by Symfony's `switch_user` mechanism on the stateless `headless_api` firewall. > [!NOTE] > Impersonation is enabled by default. To disable it, remove the `switch_user` configuration from the firewall. Keep in mind the firewall node is > replaced, not merged. If you override the firewall config, make sure to preserve any existing settings you still need. ```yaml opendxp_headless: security_firewall: # Do not configure switch_user here. ``` - Omit the header to end the impersonation. The caller re-authenticates with its own JWT on every request, so revoking the role or the user ends the impersonation on the next request. - A refused switch (missing role, unknown user, voter denial) answers a 403 in every case. The status does not reveal whether the target exists. - `GET /account` returns the target user's data and `impersonatedBy` so the PWA can show an impersonation notice. - Every switch dispatches Symfony's `SwitchUserEvent` (`SecurityEvents::SWITCH_USER`, caller token + target user) for auditing, and the request is granted `IS_IMPERSONATOR`. Roles are not persisted by the bundle. A project grants the role by overriding `getRoles()` in its user class, for example: ```php public function getRoles(): array { $roles = parent::getRoles(); if ($this->canImpersonate()) { // any custom criterion $roles[] = 'ROLE_ALLOWED_TO_IMPERSONATE'; } return array_unique($roles); } ``` ##### Who may impersonate whom Checking `ROLE_ALLOWED_TO_IMPERSONATE` determines whether the caller is allowed to impersonate another user. It does not, by itself, restrict which users may be impersonated. If you need to limit impersonation on user-based criteria, **add a custom voter**. This allows you to express target-specific authorization rules within Symfony's authorization system. Set `switch_user.role` to a dedicated attribute that does not start with `ROLE_` and register a voter for that attribute (a service tagged `security.voter`). Symfony's built-in role voter abstains on attributes without `ROLE_` prefix, leaving the custom voter responsible for the decision. This works with the default `affirmative` strategy because no other voter grants access for the custom attribute. The role itself is unchanged: endpoints and `#[IsGranted]` keep using `ROLE_ALLOWED_TO_IMPERSONATE`, and the voter checks it internally. This approach is documented in Symfony's [Limiting User Switching](https://symfony.com/doc/current/security/impersonating_user.html#limiting-user-switching). ```yaml opendxp_headless: security_firewall: # ... switch_user: provider: api_user_provider parameter: X-OpenDxp-Api-Impersonate role: headless.user.impersonate ``` ```php use OpenDxp\Bundle\HeadlessBundle\Model\ApiUserInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\Security\Core\Authorization\Voter\Voter; class ImpersonationTargetVoter extends Voter { public function __construct( private AccessDecisionManagerInterface $accessDecisionManager, ) { } protected function supports(string $attribute, mixed $subject): bool { return 'headless.user.impersonate' === $attribute && $subject instanceof ApiUserInterface; } protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool { // check whether the caller is allowed to impersonate at all if (!$this->accessDecisionManager->decide($token, ['ROLE_ALLOWED_TO_IMPERSONATE'])) { return false; } // e.g. only allow impersonating users of the same shop return $this->isInSameShop($token->getUser(), $subject); } } ``` > [!NOTE] > The attribute must not start with `ROLE_`. With a `ROLE_` prefix the role voter grants on the role alone, and under the default `affirmative` strategy one grant is enough, so a voter denial would be ignored. > With a dedicated attribute the switch also fails closed: if the voter is not registered, nothing grants the attribute and the switch is refused. #### Impersonation from the Backend Admin UI The Backend admin UI offers an **Impersonate** button in the toolbar of the user object edit view. It is shown to backend users with the `admin` role, on objects of the configured `api_user.class_name`. Clicking the button mints a single-use impersonation token and opens the URL it responds with: ``` {general domain}/_impersonate?token={token} ``` - The host is the main domain of the site marked **General Domain** in its headless site settings (the decoupled frontend). Without such a site the request fails with a 400. - The path is configured by the `headless_admin_impersonate` remote route (see [routing configuration](21_ConfigurationRouting.md#remote-routes) for details). The token is opaque and carries no user data. Server-side it maps to the target user and the admin who minted it, lives **5 minutes** and is **single-use**. The frontend application at that path can exchange the token at `POST /auth/impersonate/token` (`{ impersonationToken }`) for a valid JWT token of the user the token was minted for. This endpoint has no route security. The token is the entire authorization (magic-link model). The received token is identical to a normal login token, except that it carries an actor claim (`act: { "sub": "", "src": "opendxp-admin" }`) identifying the backend admin that minted it. Unlike the header-based flow above, a backend admin has no ApiUser identity, so there is no caller to switch from. Redemption issues a plain JWT for the target user. `GET /account` answers `impersonatedBy` from that claim, so the PWA gets the impersonation notice from the same endpoint in both flows. A project without this flow disables the route: ```yaml opendxp_headless: api_routes: impersonate_by_token: enabled: false ``` ### Account `GET /account` returns the first name, the last name, the avatar and the locale of the user. If the request was made through impersonation, the response also includes `impersonatedBy`, which contains the `identifier` of the impersonating party and the `source` of the impersonation. The `source` is either `switch_user` if the impersonation was initiated through the header flow, or `opendxp_admin` if it was initiated through the OpenDXP Admin UI. `PUT /account` and `PATCH /account` update the first name, the last name and the locale. `PATCH` leaves out every field the request does not contain. The locale must be one of the system languages. A frontend reads it to show the user's language and sends it as `X-OpenDxp-Api-Locale`. The update uses the API form `account`. A project that needs more fields replaces its form type: ```yaml opendxp_headless: api_forms: account: form_type: App\Form\Type\AccountType ``` A project without account updates disables the route: ```yaml opendxp_headless: api_routes: account_update: enabled: false ``` --- ## Setup, Configuration, Security, DevOps ### OpenDXP Configuration #### Sites For every OpenDxp site, you **have** to define context subdomains: - `api.your-main-domain.com` (your FQDN where the api is exposed) - `services.your-main-domain.com` Each site can also be individually configured for the headless bundle (General Domain, Flush Frontend Cache, Asset Base URI) via the site's **Additional Settings** in the admin panel. See [Site-based Host Configuration](00_Concepts.md#site-based-host-configuration) for details. ### Security #### Notes - Form option `csrf_protection` for all forms will be disabled #### Setup ```yaml # config.yaml opendxp: # [..] security: password_hasher_factories: OpenDxp\Model\DataObject\User: OpenDxp\Security\Hasher\Factory\UserAwarePasswordHasherFactory # security.yaml security: providers: # [...] api_user_provider: id: OpenDxp\Bundle\HeadlessBundle\Security\ApiUserProvider # [...] firewalls: headless_api: '%opendxp_headless.firewall_settings%' ``` #### Swagger Authentication If you want to add a simple basic auth to your swagger documentation, add this to your security configuration: ##### Main Security Configuration ```yaml # packages/security.yaml security: password_hashers: # [...] Symfony\Component\Security\Core\User\InMemoryUser: algorithm: bcrypt providers: swagger_provider: memory: users: my_user: password: '$2y$13$123' # generate it with bin/console security:hash-password # you may want to use an env or parameter variable here roles: ['ROLE_SWAGGER'] # [...] firewalls: swagger: pattern: ^/doc host: 'api\..+' # you may want to use an env or parameter variable here stateless: true http_basic: realm: 'API Documentation' provider: swagger_provider # [...] access_control: - { path: ^/doc, host: 'api\..+', # you may want to use an env or parameter variable here roles: ROLE_SWAGGER } # [...] ``` ##### Disable Authentication in DEV Environment #### ```yaml # packages/dev/config.yaml security: firewalls: swagger: security: false ``` ### DevOps TBD --- ## Backend Logging There is a preconfigured application logger `headless` you may want to use: `@opendxp.headless_logger` ```php class YourClass { public function __construct(protected LoggerInterface $headlessLogger) { } public function myMethod() { $this->headlessLogger->error('Your message'); } } ``` --- ## 20_Configuration --- ## Routing ### Introduction Every API call requires two given headers: - X-OpenDxp-Api-Locale - X-OpenDxp-Api-Site Knowing that, this will: - change the active request `locale` and `defaultLocale` to the given locale value - apply given site value to OpenDXP's site resolver - change the active request context host by using the `mainDomain` of the given site value This ensures, that every underlying url/route generation will use the right context, regardless of the api endpoint host! *** ### Route Document The "route document" is your starting point for an uri. It provides all necessary information to handle the requested uri. #### Route Document Resolvers ##### Route entity Resolve entities for your custom routes by creating a service and implement `HeadlessBundle\RouteDocument\RouteEntityResolverInterface`, tag it with `headless.resolver.route_document.route_entity`. The route document resolves a data object by its URL slug without a resolver of your own. Its `routeType` is `data_object`. With the I18nBundle, `attributes.i18n.alternateLinks` holds the slugs of the data object in the other languages. The built-in `DataObjectRouteEntityResolver` service can be used to resolve a data object for your (static) route. Provide the route name, the route variable name (which holds the data object's id) and the data object class name as constructor arguments: ```yaml services: my.headless.route_entity_resolver.my_object: class: OpenDxp\Bundle\HeadlessBundle\RouteDocument\RouteEntity\DataObjectRouteEntityResolver arguments: [ 'my_route_name', 'my_route_variable', 'MyDataObjectClass' ] tags: - { name: headless.resolver.route_document.route_entity } ``` ##### Breadcrumb The breadcrumb can be modified by defining a service with the `headless.resolver.route_document.breadcrumb` tag. The service must implement `HeadlessBundle\RouteDocument\BreadcrumbResolverInterface`. ```php class CategoryBreadcrumbResolver implements BreadcrumbResolverInterface { public function supports(mixed $routeEntity, RouteDocument $routeDocument): bool { return $routeEntity instanceof CategoryInterface; } public function resolve(mixed $routeEntity, RouteDocument $routeDocument, Container $breadcrumb): void { if (!$routeEntity instanceof CategoryInterface) { return; } $breadcrumb->addPage( new Page\Document([ 'id' => sprintf('category_%s', $routeEntity->getId()), 'label' => $routeEntity->getName($routeDocument->getLocale()) ?? $routeEntity->getKey() ]) ); } } ``` ### Headless Routes #### Routing Within the headless concept, by default, it is not allowed to call "frontend" routes anymore. However, for certain cases you want a route to be available to the public, for example to deliver dynamically generated content (PDFs, RSS Feeds, ...) directly from your back-end. ##### Allowing routes To allow specific routes, you need some additional configuration. First, you need to add your route to the `routes` configuration. With that, you're telling symfony, that this route can be accessed (whitelisted). ```yaml opendxp_headless: routes: - my_simple_route ``` ##### Host Problematic Since requests may happen within the api context – which runs under `api.domain.tld` – absolute routes will be generated with the wrong host. So, when generating absolute urls for your route, the host will be probably wrong (because the generation happens withing the api context). For that, you have to tell symfony router, which host you want to use. By setting the `host_context` to the routes configuration, you are telling symfony, to force use the given host (context). In order to make this work, it is crucial that corresponding entries are present in your OpenDXP site configuration. The concrete host will be resolved within the router, which looks for a matching domain against the configured `host_context` in all configured domains of the OpenDXP site. The special value `_main_domain` tells the router to resolve to the site's main domain. For example, context `services` means, that the router searches for a domain starting with `services.` As a result, the host context `services` requires a `services.domain.tld` subdomain. ```yaml opendxp_headless: routes: # for absolute urls, host will be resolved to a domain starting with services in site's domains. - { name: my_simple_route, host_context: 'services' } # for absolute urls, host will be resolved to the site's main domain. - { name: my_frontend_route, host_context: '_main_domain' } ``` #### Configuration ```yaml # packages/headless.yaml opendxp_headless: # symfony routes, which should be publicly available routes: # host_context: # This will transform your route host to the given context host. # API calls are wrapped in api.your-main-domain.tld, therefor all upcoming routes will be rendered in a wrong context. # Use the host_context to set the desired host, based on the given OpenDXP site. # In this example, the host would change to: services.your-main-domain.tld/my-custom-service - { name: my_custom_service_route, host_context: 'services' } # It's also possible to define routes without context. # For example, we'll look at the fos_js_routing_js route (Already whitelisted in OpenDxp\Bundle\HeadlessBundle, so it's not required to add it anymore). # It should be available in backend, even if it's not in the /admin context: # For this, adding the route name is fine since the host should be the same as set in given request - fos_js_routing_js ``` ##### Redirect TBD ##### Theme TBD *** ### API Routes TBD *** ### Host Patterns In rare cases, you may have to overwrite the default host patterns. These are the default values and requires to be written in a regex pattern: ```yaml opendxp_headless: host_patterns: api: '\.?api\.' backend: '\.?backend\.' services: '\.?services\.' static: '\.?static\.' ``` OpenDXP trusts the backend host of every site and of the general domain by placing the `backend` pattern in front of the domain. `backend.domain1.com` therefore belongs to the site `domain1.com`, and `backend.staging.domain1.com` belongs to `staging.domain1.com`. Since `www` only names the web host of a domain, the site `www.domain1.com` gets the backend host `backend.domain1.com` as well. Admin login links for a lost password, an invitation or a token login point to these hosts, and a pattern like `\.?backoffice\.` makes them `backoffice.domain1.com` instead. A backend host that does not follow this form needs to be configured via `opendxp.security.trusted_hosts`. See [Domain and Host Handling](https://github.com/open-dxp/opendxp/blob/1.x/doc/02_MVC/04_Routing_and_URLs/06_Domain_and_Host_Handling.md#trusted-hosts). ### Remote Routes If you need to generate a remote route (The FE Route in your PWA/NextJs Application, which is probably unknown in the API/Backend Context), you need to define them: ```yaml opendxp_headless: remote_routes: my_remote_route_to_a_special_place_we_dont_know: path: /{_locale}/my-special-route/{token} ``` Just use the headless router to generate it: ```php $myLink = $this->headlessRouter->generate( 'my_remote_route_to_a_special_place_we_dont_know', [ 'token' => 'a_not_so_secret_token' ], $this->headlessRouter->extractRouteContextParameters($command->getHeadlessContextStack()), null, HeadlessRouterInterface::REMOTE_ROUTE ); ``` *** ### Asset Routing Configure a global base URI that is prepended to all asset paths in API responses: ```yaml # packages/headless.yaml opendxp_headless: assets: host: '%headless_asset_host%' # define it via parameter in your env based parameter (e.g. https://static.my-domain.test) ``` This value acts as a **global fallback** when no context site is available. A site-specific **Asset Base URI** configured in the admin panel takes precedence over this value. If `assets.host` is **not** configured and no context site can be determined, the site marked as **General Domain** is used as a last-resort fallback for its asset base URI. > See [Site-based Host Configuration](00_Concepts.md#site-based-host-configuration) for the full resolution order and per-site asset base URI configuration. --- ## Response Entity Mapping The Response Entity Mapping allows you to override existing response entities from external bundles like this or the coreshop headless bundle. ```yaml # packages/headless.yaml opendxp_headless: ## Response Entity Mapping ## If you want to override/extend response entities, you have to define it here! response_entity_mapping: OpenDxp\Bundle\HeadlessBundle\Domain\Common\ResponseEntity\NavigationPageWithChildren: App\Domain\Common\ResponseEntity\MyCustomNavigationPageWithChildren ``` --- ## API Filter A filter turns query parameters into a typed object the handler can read. Queries and commands both take them. ### Filter in a Domain Action The action receives each filter as a `#[MapQueryString]` argument and hands them to `handle()`: ```php final class GetInsightsAction extends ApiQueryAction { public function __invoke( #[MapQueryString] ?PaginationFilter $paginationFilter, #[MapQueryString] ?OrderFilter $orderFilter, #[MapQueryString] ?InsightsFilter $insightsFilter, ): JsonResponse { return $this->handle(new GetInsightsQuery(), [$paginationFilter, $orderFilter, $insightsFilter]); } } ``` The message has to accept them: ```php class GetInsightsQuery implements QueryInterface, FilterAwareInterface { use FilterTrait; } ``` Then the handler asks for the one it needs: ```php if ($query->hasFilter(PaginationFilter::class)) { $pagination = $query->getFilter(PaginationFilter::class); } ``` The same works for a command, through `handleWithResponse()`, `handleVoid()` or `handleDelete()`. `make:api-query --filter=pagination` and `make:api-command --filter=pagination` write all three parts. `--help` lists the names this installation knows. ### Own filters A filter extends `AbstractFilter`, one public property per query parameter: ```php class InsightsFilter extends AbstractFilter { #[Assert\Choice(callback: [InsightType::class, 'getValues'])] public ?string $insightType = null; } ``` That is enough for a filter used by an action. Registering it under `available_filter` is only needed so an `api_routes` entry can reach it by name: ```yaml opendxp_headless: available_filter: insights_filter: App\Domain\Insight\Filter\InsightsFilter ``` The names the bundle brings along are `pagination`, `order`, `prefix`, `navigation`, `element_property`, `asset_mime`, `asset_thumbnail`, `listing_extender` and `search_term`. Installed bundles add their own, `headless_config` lists them all. ### Filter Params To use the filter params feature, your desired filter property needs to implement the `HeadlessBundle\Filter\FilterParamsInterface`. #### Example ```php ## a classy filter class which introduces a filter param property namespace App\Filter; class SpecialFilter extends AbstractFilter { public ProductFilter $filter; } ## and the corresponding filter params aware DTO namespace App\Dto; class ProductFilter implements FilterParamsInterface { #[OA\Property( type: 'array', items: new OA\Items( properties: [ new OA\Property(property: 'id', type: 'integer') ], type: 'object', uniqueItems: true ), example: [ '1' => '50', '2' => '51', ] )] public array $category; public int $manufacturer; } ``` Form Request Output: ```bash filter[category][1]=50&filter[category][2]=51&filter[manufacturer]=0' ``` --- ## API Forms ### Introduction API Forms are a powerful feature of the OpenDXP Headless Bundle, enabling the definition, validation, and processing of forms via API endpoints. They offer a flexible way to use and manage forms in OpenDXP's headless mode. ### Core Concepts API Forms consist of several core components: 1. **Form Type**: The Symfony Form Type class that defines the form 2. **Form Data Resolver**: A service that provides the data for the form 3. **Form Options Resolver**: Optional – A service that provides additional options for the form 4. **Validation Groups**: Optional – Defines validation groups for the form 5. **Form Field Priority**: Optional – Allows sorting of form fields ### Configuration #### In YAML Configuration The basic configuration of an API Form is done in the file: `headless.yaml` ```yaml opendxp_headless: api_forms: demo_form_schema: # Unique name of the form form_type: App\Form\Type\DemoApiForm # The Symfony Form Type class form_data_resolver: OpenDxp\Bundle\HeadlessBundle\Form\FormDataResolver\NullDataResolver # Data resolver form_data_resolver_config: { className: 'User' } # Optional configuration for the resolver form_data_voter: 'APP_DEMO_FORM' # Optional voter for access control attributes: # Field priorities (optional) field1: priority: 10 field2.subfield: priority: 5 ``` #### Form Data Resolver Form Data Resolvers are services that provide the initial data for the form. The bundle includes several predefined resolvers: 1. **NullDataResolver**: Returns `null` (for new entities) 2. **DataObjectDataResolver**: Creates or loads a OpenDXP data object 3. **ArrayDataResolver**: Returns an empty array Example configuration for a DataObjectDataResolver: ```yaml form_data_resolver: OpenDxp\Bundle\HeadlessBundle\Form\FormDataResolver\DataObjectDataResolver form_data_resolver_config: className: 'CoreShopCustomer' # OpenDXP class name identifier: 'id' # Optional: Parameter for identification (default: 'id') checkRouteParams: true # Optional: Checks route parameters (default: true) ``` #### Implementing Custom Form Data Resolvers To create a custom form data resolver, implement the `FormDataResolverInterface`: ```php namespace App\Form\FormDataResolver; use OpenDxp\Bundle\HeadlessBundle\Context\HeadlessContextStack; use OpenDxp\Bundle\HeadlessBundle\Form\FormDataResolver\FormDataResolverInterface; use Symfony\Component\HttpFoundation\Request; final class CustomDataResolver implements FormDataResolverInterface { public function resolve(HeadlessContextStack $contextStack, Request $request, array $config): mixed { // Implement your logic return $yourData; } } ``` You must then register your resolver as a service and tag it with `headless.resolver.form_data`. #### Form Data Voter `form_data_voter` names the attribute of a voter. The API asks the voter about the resolved form data before it handles the form. A request the voter denies answers 403. A form that loads data by its ID can answer 404 instead. It then uses the same message as for data that does not exist. A client cannot tell whether the data exists: ```yaml form_data_voter: !php/const App\Security\Voter\AddressVoter::ACCESS form_data_voter_status_code: 404 form_data_voter_message: 'address not found' ``` `#[MapApiForm]` takes the same values as `formDataVoter`, `formDataVoterStatusCode` and `formDataVoterMessage`. ### Usage in Controllers #### Using the MapApiForm Attribute The `MapApiForm` attribute allows direct integration of API Forms into controller methods: ```php #[Route(path: '/demo-form-action', name: 'demo_form_action', methods: ['POST'])] final class DemoFormCommandAction extends ApiCommandAction { public function __invoke( #[MapApiForm( formType: DemoApiForm::class, formDataResolver: NullDataResolver::class, validationGroups: ['app:api:form'] )] DemoFormCommand $demoCommand, ): JsonResponse { return $this->handleWithResponse($demoCommand); } } ``` #### Using the SchemaRoute Attribute The bundle also allows forms to be integrated via a reference: ```php #[AsController] #[SchemaRoute(reference: '#/api_forms/demo_form_schema')] #[Route(path: '/demo-form-query/{id}', name: 'demo_form_query', methods: ['GET'])] final class DemoFormQueryAction extends ApiQueryAction { // Controller method } ``` ### Dynamic Form Schema The bundle automatically generates schema endpoints for configured forms. For a form named `demo_form_schema`, an endpoint is created at `/demo-form-schema/schema`. This schema includes all information about the form, including: * Field types * Validation rules * Select options * Field priorities * The format of a date field with the widget `single_text`, in `options.date_time.format` and `options.date_time.html5` ### FormBuilder Integration The bundle also integrates with the OpenDXP FormBuilder: ```yaml parameters: headless_enable_form_builder_area_brick: false # Default ``` FormBuilder forms are automatically detected and made available at the endpoint `/form/{alias}`. A choice field of FormBuilder can hold a tooltip and a relation per choice. The schema lists them in `options.choice.enumMeta`, in the order of `enum`. The tooltip is translated. The relation belongs to the locale of the request and holds the id and the type of the element. A choice without meta has `null`. ```json "enum": ["red", "blue"], "options": { "choice": { "enumTitles": ["Red", "Blue"], "enumMeta": [ {"tooltip": "A bright red", "relation": {"id": 42, "type": "asset"}}, null ] } } ``` ### Field Priorities Form fields can be assigned priorities to control their order: ```yaml attributes: address: priority: 198 address.street: priority: 4 firstname: priority: 193 lastname: priority: 192 ``` Fields are sorted from highest to lowest priority. ### Complex Form Structures The bundle supports complex nested form structures, as often found in e-commerce applications: ```yaml core_shop_customer_registration: form_type: App\Form\Type\CustomerRegistrationForm form_data_resolver: OpenDxp\Bundle\HeadlessBundle\Form\FormDataResolver\DataObjectDataResolver form_data_resolver_config: { className: 'CoreShopCustomer' } attributes: address: priority: 198 address.street: priority: 4 # more nested fields ``` ### Data Processing and Normalization The bundle includes a `SchemaDataNormalizer` that normalizes form data for the API response. This normalizer: 1. Correctly processes enum values 2. Converts complex objects into simple IDs 3. Handles arrays and nested structures ### API Endpoint Integration API Forms can be used in various API endpoints: ```yaml api_routes: customer_create: route: path: '/customers' methods: [ 'POST' ] action_class: CoreShopHeadlessBundle\Domain\Customer\Action\CreateCustomerAction action_request: request_class: CoreShopHeadlessBundle\Domain\Customer\Command\CreateCustomerCommand request_form: reference: '#/api_forms/customer_registration' ``` --- ## API Routes for DataObjects ```yaml # packages/headless.yaml opendxp_headless: # enable, if you want to support data object endpoints out of the box data_object_api_routes: - class_name: News ## optionally, you may want to modify the route config too route_config: single: action_response: response_class: 'App\Domain\News\ResponseEntity\News' collection: route: action_class: 'App\Domain\Common\Action\GetDataObjectsForSiteContextQueryAction' action_request: request_class: 'App\Domain\Common\Query\DataObjectsForSiteContextQuery' ``` --- ## Open Search ### Configuration ```yaml # packages/headless.yaml opendxp_headless: opensearch: hosts: # your index hosts credentials: # your index credentials ``` #### API Search types It is possible, to preconfigure specific search types: ```yaml # packages/headless.yaml opendxp_headless: # enable, if you want to have search types api_search_types: my_search_type: {} my_extended_search_type: additional_filter: - special_filter # (additional filters, see Api Filter) action_response: response_class: 'App\Domain\Search\ResponseEntity\MyExtendedSearchResponse' ``` this will create the endpoints `search/my-search-type` and `search/my-extended-search-type`. > [!IMPORTANT] > Every search type needs a `PRE_SEARCH` listener that sets its index. See the listener below. ### Search PHP API This bundle provides a service to query an opensearch index. Use the service `HeadlessBundle\OpenSearch\Service\OpenSearchService` to perform a search: ```php use OpenDxp\Bundle\HeadlessBundle\OpenSearch\Dto\OpenSearchDemand; use OpenDxp\Bundle\HeadlessBundle\OpenSearch\Service\OpenSearchService; class MySearchService { public function __construct(protected OpenSearchService $openSearchService) {} public function mySearch() { $searchDemand = new OpenSearchDemand(); $searchDemand->setLocale('en'); $searchDemand->setOffset(0); $searchDemand->setLimit(200); $searchDemand->setOrder('id'); $searchDemand->setOrderDirection('desc'); $searchDemand->addConstraints([ 'first_constraint': 'abc', 'second_constraint': 124 ]); // use a 'search type' of your choice $result = $this->openSearchService->search('my_search_type', $searchDemand); // do something with the result $result->getHits(); $result->getTotalCount(); $result->getAggregations(); } } ``` In order to modify the search, listen to the events provided: ```php class MySearchEventListener implements EventSubscriberInterface { public function getSubscribedEvents(): array { return [ OpenSearchEvents::POST_BUILD_SORTS => ['onPostBuildSorts'], OpenSearchEvents::POST_BUILD_QUERY => ['onPostBuildQuery', 10], // lower priority OpenSearchEvents::POST_BUILD_POST_FILTER => ['onPostBuildPostFilter'], OpenSearchEvents::POST_BUILD_AGGREGATIONS => ['onPostBuildAggregations'] OpenSearchEvents::PRE_SEARCH => ['onPreSearch'] ]; } public function onPreSearch(PreSearchEvent $event): void { // check for correct search type if ($event->getSearchType() !== 'my_search_type') { return; } // last chance to modify the search demand, before the search will be performed // set the index which will be queried $searchDemand = $event->getSearchDemand(); $searchDemand->setIndex('my_other_index'); } public function onPostBuildSorts(PostBuildSortsEvent $event): void { // check for correct search type if ($event->getSearchType() !== 'my_search_type') { return; } $sorts = $event->getSorts(); // modify existing sorts, or override with your own $event->setSorts([new FieldSort('my_field', FieldSort::DESC)]); } public function onPostBuildQuery(PostBuildQueryEvent $event): void { // check for correct search type if ($event->getSearchType() !== 'my_search_type') { return; } $query = $event->getQuery(); $searchDemand = $event->getSearchDemand(); if ( $searchDemand->hasConstraint('first_constraint') && $searchDemand->getConstraint('first_constraint') == 'abc' ) { // modify query based on your constraints $query->add(new TermQuery('my_field', 'my_value')); } } //... } ``` ### Vector search Three query builders cover the vector side of OpenSearch. They implement `OpenSearchDSL\BuilderInterface`, so they go into a search like any other query. | Class | Query | Use | |--------------------------------|----------|--------------------------------------------------------| | `OpenSearch\Query\KnnQuery` | `knn` | you hold the vector already | | `OpenSearch\Query\NeuralQuery` | `neural` | OpenSearch turns the query text or image into a vector | | `OpenSearch\Query\HybridQuery` | `hybrid` | combines a lexical query with a vector query | Both `KnnQuery` and `NeuralQuery` take a filter. Pass the same restriction you would add to the bool query, so that the nearest neighbours are searched inside the allowed documents instead of being dropped afterwards. ```php $knn = new KnnQuery('ai_embedding', $vector, 100, $workspaceFilter); ``` #### Hybrid queries A hybrid query only works as the top level query, OpenSearch rejects it inside a bool query. `Search::addQuery()` always merges into a bool, so a hybrid query is set through `PostBuildSearchEvent` instead. The event fires after every other build step and before the request is sent. It carries the `Search` object, so it is also the place for `setMinScore()` and `setSource()`. ```php public function onPostBuildSearch(PostBuildSearchEvent $event): void { if ($event->getSearchType() !== 'my_search_type') { return; } $search = $event->getSearch(); $hybrid = new HybridQuery(); $hybrid->add($search->getQueries()); $hybrid->add(new KnnQuery('ai_embedding', $vector, 100, $workspaceFilter)); $event->setRootQuery($hybrid); $event->setSearchPipeline('my_normalization_pipeline'); $search->setMinScore(0.6); $search->setSource(['excludes' => ['ai_embedding']]); } ``` `setSearchPipeline()` names the search pipeline of the request. A hybrid query needs a pipeline with a normalization processor, otherwise the scores of the two queries are not comparable. Exclude the vector field from the returned `_source`. Derived source keeps the vector out of the stored `_source`, but puts it back when the source is read, and `search()` hands the whole source to the caller. Do this in the request, never in the mapping: excluding the vector from the stored source breaks `update` and `_reindex`. Without `setMinScore()` a vector search always answers with the nearest neighbours, however far away they are. ### Dynamic Search This bundle works perfectly in conjunction with dynamic search bundle (open-dxp/dynamic-search-bundle) and the open search index provider bundle(open-dxp/dynamic-search-index-provider-opensearch-bundle). #### Index mapping definition To build document definitions for OpenDXP elements, extend from `OpenDxp\Bundle\HeadlessBundle\DynamicSearch\Definition\Document\AbstractElementDefinition` #### Field Transformer Generating element urls from cli is hard. Use the provided `OpenDxp\Bundle\HeadlessBundle\ThirdParty\DynamicSearch\Transformer\Field\ElementPathExtractor` to generate your element urls while indexing. Example: ```php $definition ->addSimpleDocumentFieldDefinition([ 'name' => 'frontend_path', 'index_transformer' => [ 'type' => 'explicit', 'configuration' => [ 'type' => 'text', 'index' => false ] ], 'data_transformer' => [ 'type' => ElementPathExtractor::class, 'configuration' => [ 'arguments' => [ 'locale' => $normalizerOptions['locale'] ?? null, 'site' => $this->getSite() ] ] ] ]); ``` --- ## Flush API Cache Trigger > **Deprecated** since 1.4, removed in 2.0. Use the [Frontend Cache](28_ConfigurationFrontendCache.md) instead. Enable cache flush triggers to notify your frontend API whenever content is updated in the backend. Triggering is configured in two places: the global bundle configuration and the per-site settings in the admin panel. > For a conceptual overview of how site-based host configuration works, see [Site-based Host Configuration](00_Concepts.md#site-based-host-configuration). ### Global Configuration ```yaml # packages/headless.yaml opendxp_headless: api_flush_cache_trigger: api_key: 'YOUR_API_KEY' path: '/trigger-api-cache-flush' # method: POST (optional, default "GET") ``` | Option | Description | |-----------|------------------------------------------------------------------| | `api_key` | Sent as `X-Flush-Cache-Key` header with every request | | `path` | Path appended to each site's `mainDomain` to build the flush URL | | `method` | HTTP method used for the flush request, defaults to `GET` | ### Per-site Configuration **Flush Frontend Cache** must be enabled individually for each site via the site's **Additional Settings** in the admin panel. See [Site-based Host Configuration](00_Concepts.md#site-based-host-configuration) for details. ### Request Headers Every flush request includes the following headers: | Header | Value | |-------------------------|--------------------------------------------------------| | `X-Flush-Cache-Key` | Configured `api_key` | | `X-Flush-Cache-Type` | `document` \| `dataObject` \| `asset` \| `translation` | | `X-Flush-Cache-Id` | ID of the updated element | | `X-Flush-Cache-SubType` | Subtype of the updated element | > **Logging:** > Exceptions are logged in the Application Logger ("headless" component), see [backend logging](11_BackendLogging.md) --- ## Frontend Cache A headless frontend often caches the API responses it renders. When an editor changes a page, the frontend should rebuild only the parts that show this page. The frontend cache makes this possible. Every API response carries the header `X-Cache-Tags`. The header lists the elements in the response, for example `document_42,asset_12`. The frontend stores the response under these tags. When an element changes, OpenDXP sends its tags to the frontend. The frontend then drops the cache entries with these tags and keeps all others. This works with every frontend that can cache by tag, such as Next.js, Nuxt or TanStack Start. > [!NOTE] > The frontend cache is for frontends with a cache of their own, like the data cache of Next.js. > If only Varnish caches the API, FOSHttpCacheBundle already clears it. You may not need the frontend cache then. ### Requirements The frontend cache builds on the HTTP cache of OpenDXP. Set it up first, as described in [HTTP Cache](https://github.com/open-dxp/opendxp/blob/1.x/doc/21_Deployment/07_HTTP_Cache.md). ### Configuration Enable the frontend cache and set a secret. The frontends receive the secret as a bearer token. ```yaml # config/packages/headless.yaml opendxp_headless: frontend_cache: enabled: true secret: '%env(FRONTEND_CACHE_SECRET)%' path: /api/revalidate # the default ``` Then tick **Flush Frontend Cache** in the headless settings of each site that should receive the tags. See [Site-based Host Configuration](00_Concepts.md#site-based-host-configuration). The bundle provides the service `OpenDxp\Bundle\HeadlessBundle\HttpCache\FrontendCacheClient`. It is a proxy client of FOSHttpCacheBundle. The project decides how FOSHttpCacheBundle uses it. #### Without a proxy If the frontends are the only caches, the frontend cache client is the proxy client: ```yaml # config/packages/fos_http_cache.yaml fos_http_cache: tags: enabled: true cache_manager: custom_proxy_client: OpenDxp\Bundle\HeadlessBundle\HttpCache\FrontendCacheClient ``` #### With a proxy like Varnish FOSHttpCacheBundle sends its invalidations to one proxy client. To reach Varnish and the frontends, the project combines both in a `MultiplexerClient`: ```yaml # config/services.yaml services: app.http_cache.proxy_clients: class: FOS\HttpCache\ProxyClient\MultiplexerClient arguments: - ['@fos_http_cache.proxy_client.varnish', '@OpenDxp\Bundle\HeadlessBundle\HttpCache\FrontendCacheClient'] ``` ```yaml # config/packages/fos_http_cache.yaml fos_http_cache: proxy_client: varnish: http: servers: ['varnish:80'] tags: enabled: true cache_manager: custom_proxy_client: app.http_cache.proxy_clients ``` The same works with every other proxy client of FOSHttpCacheBundle. Replace `varnish` with its name. ### The endpoint of the frontend OpenDXP sends the tags at the end of each request, command or worker message that changed something. Each site receives one request: ```http POST https://{main domain of the site}/api/revalidate Authorization: Bearer {secret} Content-Type: application/json {"tags": ["document_42", "document_list"]} ``` The frontend checks the secret. It drops every cache entry with one of the tags and answers with a 2xx status. If a frontend cannot be reached, the other frontends still receive their request. OpenDXP writes the failure to the headless log, see [Backend Logging](11_BackendLogging.md). ### Example: Next.js Next.js stores the result of a function under the tags the function sets. This needs `cacheComponents: true` in `next.config.js`. ```ts // src/api/routeDocument.ts import { cacheTag } from 'next/cache'; export async function getRouteDocument(uri: string) { 'use cache'; const response = await fetch(`${process.env.API_BASE_URI}/route-document/${uri}`); cacheTag(...(response.headers.get('X-Cache-Tags') ?? '').split(',').filter(Boolean)); return response.json(); } ``` The endpoint drops the cache entries of the tags it receives: ```ts // src/app/api/revalidate/route.ts import { revalidateTag } from 'next/cache'; export async function POST(request: Request) { if (request.headers.get('Authorization') !== `Bearer ${process.env.FRONTEND_CACHE_SECRET}`) { return new Response(null, { status: 401 }); } const { tags } = await request.json(); for (const tag of tags) { revalidateTag(tag, { expire: 0 }); } return Response.json({ success: true }); } ``` ### Upgrading from `api_flush_cache_trigger` `api_flush_cache_trigger` is deprecated since 1.4 and will be removed in 2.0. It sends a request to each site on every change, and the frontend then drops its whole cache. It keeps working as long as the frontend cache is disabled. 1. Configure the frontend cache as described above. 2. Remove `api_flush_cache_trigger` from your configuration. 3. Change the endpoint of your frontend so that it drops only the entries of the tags it receives. 4. Remove project classes that extend `ApiTriggerListener`. When the frontend cache is enabled, `ApiTriggerListener` sends no more requests. The **Flush Frontend Cache** setting of each site stays as it is. --- ## Email Configuration If you want to submit an email in headless, you should use the mail resolver. In this example, we use the email template paths resolver, but it's possible to use different email resolver (See section "Email Resolver" below) ```yaml opendxp_headless: email_template_paths: my_email_document_path: /{_site}/{_locale}/my-path/to/email-document ``` ```php $this->mailResolver->resolve('my_email_document_path', [ 'headlessContextStack' => $command->getHeadlessContextStack(), 'recipient' => $user->getLoginIdentifier(), // optional 'parameters' => [ 'aParameter' => $whichIsAvailableInMailDocument, ], ]); ``` ### Email Resolver #### Template Path Resolver This is available in headless core and is a simple path mapping configuration: ```yaml opendxp_headless: email_template_paths: my_email_document_path: /{_site}/{_locale}/my-path/to/email-document ``` #### Custom Resolver Take a look at the headless [coreshop mail resolver](https://git.dachcom.net/extensions/coreshop-headless/-/blob/master/src/Mailer/NotificationMailProcessor.php) which is also a custom email resolver ### Core Mail Resolver Events In headless bundle there are some points, where we need to dispatch email notifications. > Note! You need to add those identifiers (like "user_password_reset_request") to the configuration first (like described above) | Name | Description | Params | |----------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------| | `user_password_reset_request` | Fires, when a password reset has been requested (If coreshop is installed, this will be handled by coreshop notifications) | `resetLink`, `user` | | `user_password_reset` | Fires, after a new password has been set | `user` | | `user_password_change_password` | Fires, after a password a logged-in user has been changed | `user` | | `user_login_identifier_change_request` | Fires, after a new login identifier has been requested. If the user logs in with the email address, the mail is sent to the new address. Otherwise it is sent to the email address of the user | `changeLoginIdentifierLink`, `user` | | `user_login_identifier_change` | Fires, after the login identifier on a logged-in user has been set | `user` | #### Email-Templates There are some required emails, you need to add: ##### user_password_reset_request ```html

Hallo,

Bitte benutzen Sie folgenden Link, um das Passwort zurückzusetzen:

{{ resetLink }}

Falls Sie Ihr Passwort nicht zurücksetzen wollten, ignorieren Sie dieses E-Mail.

``` ##### user_login_identifier_change_request ```html

Hallo {{ user.firstName }} {{ user.lastName }},

bitte klicken Sie auf folgenden Link, um Ihre neue Email Adresse zu bestätigen: {{ changeLoginIdentifierLink }}

``` --- ## Thumbnail Definitions Mostly used, if you want to override thumbnail definitions from other bundles in your application (like the coreshop headless bundle) ```yaml # packages/headless.yaml opendxp_headless: # set thumbnail names, which are required by various asset generators thumbnail_definitions: asset: 'opendxpThumbnailConfigNameForAsset' ``` --- ## Cors ```yaml # packages/headless.yaml opendxp_headless: cors: origin_regex: false allow_headers: - 'X-OpenDxp-Api-Locale' - 'X-OpenDxp-Api-Site' - 'X-OpenDxp-Api-Impersonate' # if impersonate is enabled - 'content-type' - 'authorization' - 'x-retry' expose_headers: [] allow_origin: - https://my-different-allowed-domain.test ``` --- ## API Validation / Serialization ### Configure Serialization You may have to enable the serializing mapping first ```yaml # app/config/config.yaml framework: serializer: mapping: paths: - '%kernel.project_dir%/config/serialization' ``` ### Override Validation In this example, we want to change the validation of a property (`newPassword`) in command `HeadlessBundle\Domain\Account\Command\ResetPasswordCommand`. instead of the default `Assert\Length` length of `6`, we want to change the length to `10`. ```yaml # config/headless.yaml opendxp_headless: api_routes: account_reset_password_confirm: action_request: validation_groups: [ 'app:api:write' ] # config/serialization/ResetPasswordCommand.yaml HeadlessBundle\Domain\Account\Command\ResetPasswordCommand: attributes: newPassword: { groups: ['app:api:write'] } # config/validator/ResetPasswordCommand.yaml HeadlessBundle\Domain\Account\Command\ResetPasswordCommand: properties: newPassword: - NotBlank: { groups: [ 'app:api:write' ] } - Email: { groups: [ 'app:api:write' ] } - Length: { min: 10, groups: [ 'app:api:write' ] } ``` ### Override Serialization In this example, we want to change the Response Entity `OpenDxp\Bundle\HeadlessBundle\Domain\Document\ResponseEntity\OpenDxpDocument` to just return the `id` property. ```yaml # config/headless.yaml opendxp_headless: api_routes: document: action_response: serialization_context: groups: [ 'app:api:read' ] # config/serialization/OpenDxpDocument.yaml OpenDxp\Bundle\HeadlessBundle\Domain\Document\ResponseEntity\OpenDxpDocument: attributes: id: { groups: ['app:api:read'] } ``` --- ## API Documentation This bundle uses [NelmioApiDocBundle](https://github.com/nelmio/NelmioApiDocBundle) to generate the API documentation. Nearly all of the documentation is done via OpenApi Attributes (Swagger) in the corresponding action/command and response entity classes, there is also the possibility to define (reusable) `parameters`, `responses` and `schemas` via yaml, for example: ```yaml # app/config/packages/nelmio_api_doc.yaml nelmio_api_doc: documentation: components: parameters: myParameter: name: myParameter in: query schema: type: string responses: myResponse: description: 'my Response' content: application/json: schema: $ref: '#/components/schemas/MySchema' schemas: MySchema: type: object properties: myProperty: type: string example: 'myValue' # etc. ``` Learn more about the components structure here: [Components Structure](https://swagger.io/docs/specification/v3_0/components/#components-structure) ### Error Responses Every API route documents the errors it can answer. A route adds an error of its own under `action_response.open_api.status_responses`. The bundle documents these errors by itself: | Status | Documented for | |--------|-----------------------------------------------------------------| | 400 | Every route | | 401 | A route with `security` | | 403 | A route with `security` or a `form_data_voter` that answers 403 | | 404 | A route with the method `GET` or a placeholder in its path | | 415 | A route that reads a body other than a form | | 422 | A route with a method other than `GET` | | 500 | Every route | A `GET` route answers 404 also for a query parameter that breaks its constraints. A route that answers another error documents it, for example a resource that expired: ```yaml opendxp_headless: api_routes: my_route: action_response: open_api: status_responses: 410: '#/components/responses/myGoneError' ``` ### Predefined schemas This bundle provides a few pre-defined schemas, for example `RouteDocumentAttributes`, `NavigationPageCustomProperties`, `NavigationPageCustomHtmlAttributes` and more. The structure of some schemas cannot be known in advance, since it's allowed to put anything in there, and therefore the schema depends on the project's implementation. If they are in use, they must be defined/overridden in the project manually, for example: ```yaml # app/config/packages/nelmio_api_doc.yaml nelmio_api_doc: documentation: components: schemas: NavigationPageCustomProperties: type: array items: oneOf: - type: string - type: object properties: key: type: string value: type: string - $ref: '#/components/schemas/OpenDxpElement' # etc. NavigationPageCustomHtmlAttributes: type: object properties: 'data-custom-prop': type: string # etc. ``` --- ## Response Entities A response entity describes what an endpoint answers with: one public property per field. ```php class StoreItem implements ResponseEntityInterface { public string $name; public ?string $city = null; } ``` That is all you need as long as the source object has a `getName()` and a `getCity()`. Paths work too: `source: 'address.zip'` walks `getAddress()->getZip()`, and `get`, `is` and `has` are all tried. ### Resolution order Each property is filled in this order: ``` source → sourceResolver → transformer → responseMappingClass ``` Use a **source resolver** when what the getter returns is not yet something `responseMappingClass` can map. It runs once on the whole value, before a collection is split into items: ```php #[ApiTransformerProperty( sourceResolver: FieldCollectionSourceResolver::class, responseMappingClass: OpeningHour::class, isCollection: true, )] public array $openingHours; ``` The bundle ships resolvers for the usual containers: `Fieldcollection`, `ImageGallery`, Doctrine collections, json strings, timestamps. Write your own when the list has to be fetched first, from an id or from `$context['entity']`. Use a **transformer** to bring a single value into its final shape. It runs per item and works on any class, so it can be reused. Pass it the source object with `source: self::SOURCE_ENTITY`: ```php #[ApiTransformerProperty(source: self::SOURCE_ENTITY, transformer: ElementUrlTransformer::class)] public ?string $frontendPath; ``` > `source: self::SOURCE_ENTITY` skips the source resolver. Using both on one property does nothing. ### The two attributes | | `ApiTransformerProperty` | `ApiResponseEntityProperty` | |------------------|----------------------------|-----------------------------| | `source` | yes | yes | | `sourceResolver` | yes | yes | | `transformer` | yes | no | | nested entity | `responseMappingClass` | `class` | | collection | `isCollection: true` | property typed as `array` | | several types | array plus `discriminator` | no | For several types, pass an array of classes and a `discriminator`. The denormalizer picks by that field and the specification gets a `oneOf`. An array of classes counts as a collection unless `isCollection` says otherwise. Always name the **bundle** class in `responseMappingClass`, even when your project overrides it. The name passes through `response_entity_mapping` anyway, so you keep one switch point instead of two. ### Overriding an entity of a bundle The class alone has no effect. It needs the mapping entry as well: ```php class EcommerceProduct extends \OpenDxp\Bundle\HeadlessEcommerceBundle\Domain\Product\ResponseEntity\EcommerceProduct { public ?bool $isNew = null; } ``` ```yaml opendxp_headless: response_entity_mapping: OpenDxp\...\ResponseEntity\EcommerceProduct: App\Domain\Product\ResponseEntity\EcommerceProduct ``` `make:response-entity --extends` writes both. The parent is fully qualified because an override usually shares its short name, and importing that name would be a fatal error. See [Response Entity Mapping](23_ConfigurationResponseEntityMapping.md). ### Adding a type to a route of a bundle Some routes of a bundle answer with one class per type. `/assets/{id}/metadata` is one of them. Its `response_class` maps each metadata type to a class, and the field `type` decides which class applies. If your project registers its own asset metadata type, add an entry for it. The bundle keeps its own entries and adds yours: ```yaml opendxp_headless: api_routes: asset_metadata: action_response: response_class: isbn: App\Domain\Asset\ResponseEntity\IsbnAssetMetadata ``` The class extends `AbstractOpenDxpAssetMetadata` and declares the type and the data: ```php use OpenApi\Attributes as OA; use OpenDxp\Bundle\HeadlessBundle\Domain\Asset\ResponseEntity\AbstractOpenDxpAssetMetadata; class IsbnAssetMetadata extends AbstractOpenDxpAssetMetadata { #[OA\Property(enum: ['isbn'])] public ?string $type = null; public ?string $data = null; } ``` The API documentation lists the class next to the classes of the bundle. A type without an entry fails with the message `The response class has no entry for the type "isbn".` ### OpenAPI A typed property needs no `#[OA\Property]`. The describer builds the schema from the attribute: it registers the mapping class, turns `isCollection` into an array with `items`, an array of classes into `oneOf`, and keeps `nullable`. It gives up on one case: a property typed `array` or `mixed` without a mapping class. The specification then has an array without `items`, and a generated client makes `any[]` of it. Describe those yourself: ```php #[ApiTransformerProperty(transformer: AssetThumbnailTransformer::class, isCollection: true)] #[OA\Property(type: 'array', items: new OA\Items(properties: [ new OA\Property(property: 'video', ref: '#/components/schemas/CmsEditableStandardizedHeadlessVideo'), ]))] public ?array $videos = null; ``` `headless_lint_response_entities` finds these, and overrides missing their mapping entry. See [Development Tools](60_DevelopmentTools.md). --- ## Naming Conventions An endpoint is made of four classes, and each one has a job. The name should say which job it does, so that a reader who opens the folder can tell them apart without reading any code. ``` src/Domain/Product/ Query/ProductsQuery.php what the caller wants Action/ListProductsAction.php how it arrives over HTTP QueryHandler/ProductsQueryHandler.php where it is answered ResponseEntity/ProductItem.php what goes back ``` ### Messages A query is named after what it returns. Use the plural for a collection and the singular for one record. ```php ProductsQuery // a list of products ProductQuery // one product OrderHistoryQuery // one caller's order history ``` A command is named after the change it makes. Write it as an instruction, verb first, and keep it in the present tense. ```php CreateAddressCommand UnsubscribeCommand ApplyVoucherCommand ``` > [!TIP] > Read the class name out loud as a sentence. `CreateAddressCommand` says "create address", which is > an instruction. `AddressCreateCommand` says nothing, and that is the sign that the words are the > wrong way round. ### Actions The action is the HTTP side of the endpoint. It carries the operation, while the message carries the intent, so the two names are not the same word twice. For a query, the operation follows the resource: ```php GetProductAction // returns one record ListProductsAction // returns a collection ``` For a command, the message name already begins with a verb, so the action repeats it and adds nothing else: ```php CreateAddressCommand -> CreateAddressAction UnsubscribeCommand -> UnsubscribeAction ``` > [!NOTE] > `Get` and `List` are not interchangeable. `Get` answers with a single record, `List` answers with a > collection. Anyone reading the class list can therefore see which endpoints paginate. Some operations are neither a plain read nor a change to one resource. Name those with their own verb and a noun, and avoid the five words above so that the exception stays visible: ```php PickupCartAction ApplyVoucherToCartAction ``` ### Handlers and response entities A handler is named after the message it answers, with `Handler` appended. There is one handler per message, so nothing else needs to be decided. ```php ProductsQuery -> ProductsQueryHandler ``` A response entity is named after the shape it describes, not after the endpoint that returns it. The same entity often serves several endpoints. ```php ProductItem ProductSearchItem EcommerceProduct ``` > [!TIP] > When a response entity overrides one from a bundle, give it the same short name as its parent. The > namespace already tells the two apart, and the matching name makes the pair obvious in > `response_entity_mapping`. See [Response Entities](42_ResponseEntities.md). ### Filters, transformers and source resolvers Each of these is named after what it does, with its role appended: ```php PaginationFilter DistanceInKmTransformer OpeningHoursSourceResolver ``` ### The makers follow these rules Both makers derive every name from the two arguments you pass, so a generated endpoint already matches the conventions above: ```bash bin/console make:api-query Product Products --collection # ProductsQuery, ListProductsAction, ProductsQueryHandler, ProductsItem bin/console make:api-command Address CreateAddress # CreateAddressCommand, CreateAddressAction, CreateAddressCommandHandler, CreateAddressItem ``` For an operation whose name cannot be derived, pass it yourself: ```bash bin/console make:api-command Cart ApplyVoucher --action-name=ApplyVoucherToCart ``` See [Development Tools](60_DevelopmentTools.md). --- ## Navigation Enhancement It's crucial to build a solid cached navigation to prevent performance lags! Therefor you should always prebuild your navigation within the `NavigationPageCallbackEvent`! Everything your going to add there will be cached. ### Debugging While building a navigation on backend layer, it can be quite annoying, since every navigation build gets cached imitatively. To disable caching while developing you need to modify the `NavigationHandler` class: ```php // [...] // line 39 $navigationParams = []; // add this line to prevent caching $navigationParams['cache'] = false; // [...] ``` ### Event Listener ```php 'onPageCallback' ]; } public function onPageCallback(NavigationPageCallbackEvent $event): void { $navigationName = $event->getNavigationFilter()?->getNavigationName(); $opendxpContext = $event->getHeadlessContextStack()?->getContext(OpenDxpContext::class); if (!$opendxpContext instanceof OpenDxpContext) { return; } if ($navigationName === 'my_special_navigation') { $this->enrichSpecialNavigation($opendxpContext, $event->getPage()); } } protected function enrichSpecialNavigation(OpenDxpContext $opendxpContext, Page $page): void { $page->set('customProperties', [ 'my_additional_property' => 42, ]); // for example: if the OpenDXP document has a specific class, // we want to add some more pages to it! if (str_contains($page->getClass(), 'special_dynamic_nav_starts_here')) { $this->addAdditionalNodes($opendxpContext, $page); } } protected function addAdditionalNodes(OpenDxpContext $opendxpContext, Page $page): void { $objectListing = new Listing(); foreach ($objectListing as $object) { $customAttributes = [ 'my_additional_object_property' => $object->getTitle(), ]; $page->addPage([ 'id' => sprintf('my_object_%s', $object->getId()), 'uri' => $this->headlessRouter->generate( '', [], [ 'locale' => $opendxpContext->getLocale(), 'site' => $opendxpContext->getSite() ], $object, HeadlessRouterInterface::OPENDXP_ROUTE, UrlGeneratorInterface::ABSOLUTE_PATH ), 'label' => $object->myLabel(), 'customProperties' => $customAttributes, 'documentType' => MyObjectClass::class, 'documentId' => $object->getId(), ]); } } } ``` --- ## Development Tools(Headless) Two optional tools. Both are skipped when the package they need is missing, so a production install is not affected. Install them in your project: ```json "require-dev": { "symfony/maker-bundle": "^1.67", "open-dxp/mate-extension": "^1.0" } ``` ### Makers An API endpoint always consists of the same set of classes. Only the handler carries logic, everything else is wiring. ```bash bin/console make:api-query Product ProductList --collection --filter=order bin/console make:api-command Account Unsubscribe --void --method=DELETE ``` The query variant creates Query, Action, QueryHandler and a ResponseEntity, the command variant does the same for the write side. Both endpoints answer right away, only the handler needs your logic. Every name is derived the way [Naming Conventions](43_NamingConventions.md) describes, so `make:api-query Product Products --collection` writes `ListProductsAction` and `ProductsQuery`. Pass `--action-name` for an operation whose name cannot be derived. `--filter` works for both and is repeatable. A name registered in [`available_filter`](24_ConfigurationApiFilter.md) is wired up as it is, any other name becomes a new filter class in the domain, and the command says which of the two happened. `--help` lists the names this installation knows, including the ones installed bundles bring along. The four remaining commands write a single class into `src/Domain//`: ```bash bin/console make:response-entity Store StoreItem bin/console make:response-entity Product EcommerceProduct --extends='OpenDxp\Bundle\HeadlessEcommerceBundle\Domain\Product\ResponseEntity\EcommerceProduct' bin/console make:api-source-resolver Store OpeningHours bin/console make:api-transformer Store DistanceInKm bin/console make:api-filter Store NearBy ``` `--extends` writes the `response_entity_mapping` entry along with the class, into `config/packages/opendxp_headless_response_entities.yaml`. A file of its own, because parsing and dumping the file a project keeps its own configuration in would throw away comments and yaml anchors. Symfony merges every file under `config/packages`, so the entry is just as effective there, and it can be moved by hand at any time. [Response Entities](42_ResponseEntities.md) explains when a source resolver fits and when a transformer. Run `bin/console make:api-query --help` for all options. ### Mate [Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html) gives an AI agent tools that read the running application. `open-dxp/mate-extension` adds the tools for OpenDXP, and this bundle adds its own when Mate is installed. Set Mate up as the extension describes. | Tool | Answers | |-----------------------------------|-----------------------------------------------------------------------------| | `headless_api_endpoints` | Every endpoint served right now, and where each one comes from | | `headless_config` | The headless configuration after every bundle and the project had their say | | `headless_lint_response_entities` | Response entities with a hole a generated client would trip over | | `headless_search_setup` | The OpenSearch hosts, the index of every search type and its listeners | The bundle also ships three skills. `mate-headless-api` covers queries, commands, routes, message extensions and filters. `mate-headless-search` covers search types, their index and the search events. `mate-headless-response-entities` covers where a property value comes from, overriding a bundle entity, nesting and OpenAPI attributes. The agent creates the classes with the makers above. ```bash vendor/bin/mate tools:list ``` #### Data sources `headless_api_endpoints` reads the router, so it sees attribute routes and configured ones alike. `data_object_api_routes` and `api_search_types` are expanded into `api_routes` while the configuration is normalized, which the tool undoes by recomputing the names those entries produce. It says for each endpoint whether it comes from an attribute, from `api_routes`, from a data object route, from a search type or from a generated form schema route, and it points out `api_routes` entries that declare an endpoint of the project itself, which is what the key is not for. --- ## Testing(Headless) The headless bundle ships a test API in `OpenDxp\Bundle\HeadlessBundle\Test`. It sends requests to your headless endpoints and checks every response against the [API documentation](41_ApiDocumentation.md). This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Setup The documentation check validates every response with the OpenAPI validator. Install it as a development dependency: ```bash composer require --dev league/openapi-psr7-validator ``` The import in `tests/config/test.yaml` switches on the documentation check: ```yaml imports: - { resource: '@OpenDxpHeadlessBundle/config/test/services.yaml' } ``` > [!IMPORTANT] > Without the import, your tests still run, but no response is checked against the documentation. If the test environment has no JWT key pair, add a shared secret to the same file: ```yaml parameters: env(JWT_SECRET_KEY): 'a-secret-that-only-the-tests-know' env(JWT_PUBLIC_KEY): '' env(JWT_PASSPHRASE): '' lexik_jwt_authentication: encoder: signature_algorithm: HS256 ``` The test API signs in with users of your API user class. Its factory extends `AbstractApiUserFactory`: ```php */ final class UserFactory extends AbstractApiUserFactory { public static function class(): string { return User::class; } } ``` If your API user class has another name, use that class instead of `User`. The factory gives every user a unique email address as its login identifier. ### Sending a request `Api::start()` sends a JSON request without a user to the API host, in the default language of your installation: ```php use App\Tests\Factory\EventFactory; use OpenDxp\Bundle\HeadlessBundle\Test\Api; it('returns an event', function () { $event = EventFactory::new()->create([ 'title' => 'Open Day', 'seats' => 40, ]); $browser = Api::start()->get(sprintf('/events/%d', $event->getId())); $browser->assertStatus(200); expect($browser->json()->decoded())->toBe([ 'id' => $event->getId(), 'title' => 'Open Day', 'seats' => 40, ]); }); ``` `EventFactory` is a factory of your project. [Write the factory](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing/Factories_and_Stories#write-the-factory) shows how you write one. Pass the `json` option when your endpoint expects a request body: ```php $browser = Api::start()->post('/events', [ 'json' => [ 'title' => 'Open Day', 'seats' => 40, ], ]); $browser->assertStatus(201); ``` The API returns status 422 when the validation of a request fails. You may check which field the response reports: ```php $browser ->assertStatus(422) ->assertJsonMatches('violations[0].propertyPath', 'seats'); ``` ### Authenticated requests Use `Api::actingAs()` when your endpoint requires a signed-in user. The test API creates a token for the user and sends it as a bearer token: ```php use App\Tests\Factory\UserFactory; use OpenDxp\Bundle\HeadlessBundle\Test\Api; it('lists the bookings of the user', function () { $user = UserFactory::createOne(); $browser = Api::actingAs($user)->get('/bookings'); $browser->assertStatus(200); }); ``` To check that your endpoint refuses anonymous requests, send the same request with `Api::start()`: ```php Api::start()->get('/bookings')->assertStatus(401); ``` ### Choosing a site As soon as your installation has a site, the API refuses every request without the `X-OpenDxp-Api-Site` header. Pass the header in an `HttpOptions` object when your test creates a site: ```php use OpenDxp\Bundle\HeadlessBundle\Test\Api; use OpenDxp\Test\Factory\SiteFactory; use Zenstruck\Browser\HttpOptions; it('returns the events of the site', function () { $site = SiteFactory::createOne(); $options = HttpOptions::create()->withHeader('X-OpenDxp-Api-Site', (string) $site->getId()); $browser = Api::start($options)->get('/events'); $browser->assertStatus(200); }); ``` `Api::actingAs()` accepts the same options as its second argument: ```php Api::actingAs($user, $options)->get('/bookings'); ``` The options apply to every request that the returned browser sends. ### Choosing a locale The test API sends the default language of your installation in the `X-OpenDxp-Api-Locale` header. Override the header when you test a response in another language: ```php $options = HttpOptions::create()->withHeader('X-OpenDxp-Api-Locale', 'fr'); $browser = Api::start($options)->get('/events'); ``` The locale must be a valid language of your installation, or the API returns status 400. You may chain several `withHeader()` calls to send a site and a locale together. ### Using your own API host The test API sends its requests to `api.headless.test`, which matches the default [host pattern](21_ConfigurationRouting.md#host-patterns) of the API. If your project configures its own pattern, send a host that matches it: ```php $options = HttpOptions::create()->withServer(['HTTP_HOST' => 'headless.example.test']); $browser = Api::start($options)->get('/events'); ``` > [!NOTE] > Only requests to the API host are checked against the documentation. A request to any other host passes without a > check. ### User factory states The user factory has a state for each account flow: | State | Creates a user who | |--------------------------------------------------------------------------------------|------------------------------------------------------| | `withLocale(string $locale)` | has chosen a preferred language | | `withPassword(string $password)` | signs in with a known password | | `requestingPasswordReset(string $token, DateTimeInterface $requestedAt)` | has requested a password reset with this token | | `requestingLoginIdentifierChange(string $new, string $token, DateTimeInterface $at)` | has requested a new login identifier with this token | For example, a test of the login endpoint needs a user with a known password: ```php $user = UserFactory::new() ->withPassword('a-password-of-ada') ->create(); $browser = Api::start()->post('/auth/login', [ 'json' => [ 'loginIdentifier' => $user->getLoginIdentifier(), 'password' => 'a-password-of-ada', ], ]); ``` A test of a password reset link needs a user with a pending request: ```php use Carbon\Carbon; $user = UserFactory::new() ->requestingPasswordReset('a-token-of-ada', Carbon::now()) ->create(); Api::start()->post('/account/reset-password-request/a-token-of-ada', [ 'json' => ['newPassword' => 'a-new-password'], ]); ``` ### Failures The test fails with a message that names the request, the documented path and the reason. For example, if the documentation declares `title` as a string that cannot be null, an event without a title fails like this: ``` GET /events/{id} breaks the documentation. Body does not match schema for content-type "application/json" for Response [get /events/{id} 200] Keyword validation failed: Value cannot be null The field is "title". ``` These are the failures you will see most often: | Message | Meaning | |------------------------------------------------------------------|----------------------------------------------------------------------------------------| | `Body does not match schema ... The field is "..."` | The named field is missing, has the wrong type or is null although it may not be null. | | `OpenAPI spec contains no such operation [/events/{id},get,500]` | The endpoint returned a status that the documentation does not list. | | `OpenAPI spec contains no such operation [/events/{id}]` | The documentation does not describe the route at all. | | `The firewall "headless_api" keeps a session.` | The firewall of the API is not stateless. | | `GET /events/1 uses the session.` | The endpoint started or used a session. | Either the endpoint or its documentation is wrong. Fix the endpoint when it returns something it should not. Fix the [documentation](41_ApiDocumentation.md) when the endpoint is right and the description is incomplete. --- ## Changelog(Headless) ### 1.4.3 - [BUGFIX] `OpenDxpVideo` and `OpenDxpVideoThumbnail` take the output of `AssetThumbnailTransformer` as `responseMappingClass`. `videoParameter` and `formats` are objects now ### 1.4.2 - [SECURITY] [OPENDXP-SA-2026-021] The search API no longer takes the OpenSearch index from the request - [BUGFIX] Require `symfony/property-info` ^7.4 instead of exactly 7.4.0, so the bundle installs with the current Symfony 7.4 - [ENHANCEMENT] `headless_search_setup` checks that the index of every search type exists, also without Dynamic Search - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.4.1 - [ENHANCEMENT] The route document resolves a data object by its URL slug. A slug page has the `routeType` `data_object` instead of `symfony`, see [Routing](docs/21_ConfigurationRouting.md#route-entity) - [BUGFIX] The admin preview shows an unpublished data object by its URL slug - [BUGFIX] `DataObjectRouteEntityResolver` only resolves an unpublished data object in the admin preview - [CHORE] Require `open-dxp/i18n-bundle` 1.2.1 or newer when it is installed ### 1.4.0 - [ENHANCEMENT] The schema of a FormBuilder choice field holds the tooltip and the relation of each choice. See [API Forms](docs/25_ConfigurationApiForms.md#formbuilder-integration) - [ENHANCEMENT] The schema of a date field with the widget `single_text` holds its format - [CHORE] The services and static hosts serve every site declaration of OpenDXP 1.5, not only robots.txt - [CHORE] [OPT-IN] The development tools for AI agents run on Symfony AI Mate instead of `open-dxp/mcp-bundle`. `headless_how_to` and the scaffold tools are gone. The skills `mate-headless-api` and `mate-headless-response-entities` and the makers take their place, see `docs/60_DevelopmentTools.md` 1. Only if your coding agents used the MCP tools of this bundle: run `composer require --dev open-dxp/mate-extension`. 2. Set up Mate as the [installation of `open-dxp/mate-extension`](https://github.com/open-dxp/mate-extension#installation) describes. - [NEW FEATURE] [HIGHLIGHT] [MIGRATION] An API user with the role `ROLE_ALLOWED_TO_IMPERSONATE` acts as another user through the header `X-OpenDxp-Api-Impersonate`. A backend user with the permission `opendxp_headless_api_user_impersonation` opens the frontend as any API user, see `docs/01_CertificationAuthentication.md` > Support teams see the frontend exactly as a customer sees it, either through the API or with one click in the admin. - [NEW FEATURE] [HIGHLIGHT] `PUT`/`PATCH /account` updates the first name, the last name and the locale of the user, see `docs/01_CertificationAuthentication.md` > Users update their first name, last name and locale through `PUT` or `PATCH /account`. - [ENHANCEMENT] `GET /account` returns the locale of the user - [ENHANCEMENT] `ApiUserInterface` has the method `setLocale()`. The installed `User` class already has it through its field `locale` - [ENHANCEMENT] The field `locale` of the installed `User` class lists the system languages - [NEW FEATURE] Test API for requests to the API. It checks every response against the API documentation and checks that the API keeps no session, see `docs/61_Testing.md` - [ENHANCEMENT] The API documentation lists 401, 403, 404 and 415 for the routes that can answer them, see `docs/41_ApiDocumentation.md` - [BUGFIX] The `security` of an API route applies to every action. An action without an `#[ApiActionRequest]` argument skipped it before. - [BUGFIX] The `validation_groups` of a form request decide which constraints of the form data apply. The group `Default` applies only if the list contains it - [ENHANCEMENT] `form_data_voter_status_code` and `form_data_voter_message` set the status and the message of the response when the form data voter denies a request, see `docs/25_ConfigurationApiForms.md`. `SecurityChecker::checkSubject()` takes both as arguments - [BUGFIX] A request without the form of `#[MapApiForm]` returns 422 instead of 500 - [BUGFIX] An exception of a handler whose code is not a client error returns 500 - [BUGFIX] A document request that does not accept JSON returns 406 instead of 200 - [BUGFIX] `#[SchemaRoute]` registers the schema route of its form - [BUGFIX] A schema route without an OpenAPI tag no longer breaks the routing - [BUGFIX] The `url` of a data object whose class has no link generator is `null` instead of an error - [BUGFIX] `PaginationHelper` paginates a query without a pagination filter instead of failing - [BUGFIX] `/documents/{id}`, `/elements/{id}/properties`, `/assets/{id}/metadata` and `/assets/{id}/thumbnail` return 404 for an element that does not exist instead of an empty response - [BUGFIX] `/assets/{id}/thumbnail` returns 404 for a video and for an asset without a thumbnail, and refuses `options` that are not JSON - [BUGFIX] `/assets/{id}/metadata` describes metadata that refers to an element with `OpenDxpElement` instead of failing. The route uses `OpenDxpAssetMetadataScalar` and `OpenDxpAssetMetadataElement`, which the API documentation lists by `type` - [DEPRECATION] `OpenDxpAssetMetadata`. 2.0 removes the class, use `OpenDxpAssetMetadataScalar` or `OpenDxpAssetMetadataElement` - [ENHANCEMENT] The `response_class` of a project adds its types to the `response_class` of a bundle route. A project adds an asset metadata type this way, see `docs/42_ResponseEntities.md` - [ENHANCEMENT] A type without an entry in `response_class` fails with a message that names the type - [DEPRECATION] `WebsiteSetting`. 2.0 removes the class, use `AbstractWebsiteSetting` - [DEPRECATION] `OpenDxpElementProperty`. 2.0 removes the class, use `AbstractOpenDxpElementProperty` - [BUGFIX] The order filter returns 404 for an order other than `asc` or `desc` and for an order key that is not a field name. An unknown order key returns 400 instead of 500 - [BUGFIX] `/navigation` marks a dynamic node of the top level as active instead of failing - [BUGFIX] The API documentation allows `null` for `customProperties` and `customHtmlAttributes` of a navigation page - [BUGFIX] A bool website setting is a boolean in the response - [BUGFIX] `POST /account/avatar` without a file returns 422 instead of 500 - [BUGFIX] `DELETE /account/avatar/{id}` removes the avatar from the user and marks its command with `RemoveStamp` - [BUGFIX] The tokens of the password reset and of the login identifier change are random - [BUGFIX] Confirming a login identifier that another user took in the meantime returns 422 instead of creating a second user with it - [ENHANCEMENT] `AbstractApiUserFactory` has the states `requestingPasswordReset()` and `requestingLoginIdentifierChange()` - [ENHANCEMENT] If the user logs in with the email address, the mail to confirm a new login identifier is sent to the new address. Otherwise it is sent to the email address of the user - [BUGFIX] The error responses of the API documentation type `code` as `integer` - [DEPRECATION] `ApiUser::eraseCredentials()`. The API keeps no session, so 2.0 removes the method - [BUGFIX] A missing or invalid `X-OpenDxp-Api-Locale` or `X-OpenDxp-Api-Site` header returns 400 instead of 500 - [BUGFIX] The API returns a document with the `Accept` headers `*/*` and `application/*`. It also returns a document without an `Accept` header. - [ENHANCEMENT] `OpenDxpVideo` and `OpenDxpVideoThumbnail` describe the video that `AssetThumbnailTransformer` outputs - [BUGFIX] Empty player parameters of a video and the formats of a video conversion in progress are objects in JSON, not arrays - [ENHANCEMENT] A headless document names its template `_cmsTemplate` while the toolbox outputs camelCase (`opendxp_toolbox.headless.camel_case_property_names: true`) - [DEPRECATION] `DocumentEditableAreasTransformer::TEMPLATE_PROPERTY_SNAKE_CASE` (`_cms_template`). 2.0 names the template `_cmsTemplate` - [NEW FEATURE] [HIGHLIGHT] Frontend cache, see `docs/28_ConfigurationFrontendCache.md` > The Headless API supports HTTP caching natively. Every response carries cache tags, and a change to an element clears only the cached responses that contain it. - [DEPRECATION] `api_flush_cache_trigger` is deprecated, use the frontend cache instead - [NEW FEATURE] Domain redirects of the SEO bundle also apply to route documents, whether a page exists under the route or not (requires `open-dxp/opendxp` ^1.5) - [ENHANCEMENT] A redirect that answers a route document is counted as a hit - [ENHANCEMENT] A redirect without a target, such as `410 Gone`, returns its status code instead of 404 - [BUGFIX] Redirects that match or forward the query string see the query of the route - [ENHANCEMENT] [MIGRATION] The bundle has an installer: `bin/console opendxp:bundle:install OpenDxpHeadlessBundle` creates the table of the refresh tokens from the Doctrine mapping. An existing installation is marked as installed by the migrations. - [BUGFIX] Correct the API schema of links and thumbnails - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [BUGFIX] Every paginated listing sends its total count in `X-Pagination-Total-Count` - [DEPRECATION] `X-Api-Pagination-Total`. 2.0 removes the header, use `X-Pagination-Total-Count` ### 1.3.8 - [NEW FEATURE] OpenSearch vector search: `KnnQuery`, `NeuralQuery` and `HybridQuery` as query builders - [NEW FEATURE] `PostBuildSearchEvent` carries the `Search` object and takes a top level query plus a search pipeline ### 1.3.7 - [ENHANCEMENT] OpenSearch: a hit carries the raw `inner_hits` of its document under `inner_hits` when the query requested them ### 1.3.6 - [ENHANCEMENT] BodyListener: added a per-route opt-out (`_opendxp_headless_skip_body_validation` route default parameter) - [ENHANCEMENT] MCP scaffold tools: report the files they wrote, not only the class names - [ENHANCEMENT] `OpenDxp\Bundle\HeadlessBundle\Security\TrustedBackendLoginLinkHostResolver` decorates admin-bundle's `TrustedLoginLinkHostResolverInterface` (requires `open-dxp/admin-bundle` ^1.4.2, which introduces that interface) and trusts a request host matching the `host_patterns.backend`. This lets admin login links (lost password, invitation, token login) point at the backend host instead of the frontend domain. ### 1.3.5 - [NEW FEATURE] OpenDXP MCP support: tools that answer from the running installation which endpoints it serves, what the merged headless configuration says, which mechanism fits a given task, and where a response entity has a hole a generated client would trip over (requires `open-dxp/mcp-bundle`) - [NEW FEATURE] Maker support: `make:api-query`, `make:api-command`, `make:response-entity`, `make:api-source-resolver`, `make:api-transformer` and `make:api-filter` (requires `symfony/maker-bundle`) - [NEW FEATURE] Documentation for response entities: how a property gets its value, how one entity references another, when an OpenAPI attribute is needed - [BUGFIX] `UserLoginIdentifierChangeEvent` now extends the Symfony event instead of a doctrine entity - [BUGFIX] Fixed an error in `DocumentEditableAreasTransformer` for non-page-snippet documents ### 1.3.4 - [BUGFIX] Include scalar types bool and float in opensearch aggregation bucket value ### 1.3.3 - [ENHANCEMENT] Add support for resolving locale-to-URL mapping in remote routes (requires `opendxp/i18n-bundle >= 1.1.5`) ### 1.3.2 - [ENHANCEMENT] Handle `isCollection` attribute for oneOf relations in property and response mapping ### 1.3.1 - [ENHANCEMENT] Schema Routes: Also support `POST` requests - [BUGFIX] Fix wrong validation groups mapping in `MapApiForm` ### 1.3.0 - [ENHANCEMENT] Improve Asset Base Uri Fallback: Use site where `general domain` has been assigned - [ENHANCEMENT] PHP 8.5 support added - [ENHANCEMENT] Changed dependency `smoench/opensearch-dsl` to `shyim/opensearch-php-dsl` to provide better php support - [ENHANCEMENT] Make validation constraint messages configurable - [ENHANCEMENT] Use method attributes for Twig functions instead of `getFunctions`. - [ENHANCEMENT] Enhance Asset Base URI resolution: Add "General Domain" site fallback - [BUGFIX] Allow empty POST requests ### 1.2.2 - [ENHANCEMENT] Improve Setup/Auth Documentation by @solverat in #53 - [ENHANCEMENT] Update gesdinet/jwt-refresh-token-bundle to v2.0 and adapt configuration - [ENHANCEMENT] Update supports method in FormTypeDescriber to check for ObjectType using TypeInfo - [ENHANCEMENT] Update UniqueLoginIdentifier constructor for improved parameter handling - [BUGFIX] Respect all hosts in ApiTriggerListener ### 1.2.1 - [BUGFIX] Add static host fallback handling and site resolution logic ### 1.2.0 - [NEW FEATURE] Site-based host configuration - [NEW FEATURE] API Flush is now available for each site - [DEPRECATION] `api_flush_cache_trigger.enabled`: Use Site Configuration instead - [DEPRECATION] `api_flush_cache_trigger.uri`: Use Site Configuration and configure `api_flush_cache_trigger.path` instead - [NEW FEATURE] Asset (Static Host): While `assets.host` is still a valid configuration (will be used as fallback), you're able to define asset base uri for each site - [NEW FEATURE] General Domain definition: Define the open dxp general domain via Site Configuration - [ENHANCEMENT] Migrate nelmio property describer to type describer (symfony type info) - [BUGFIX] Fix OpenAPI schema for listing extender - [BUGFIX] Fix `getSupportedTypes` implementation for (de)normalizers - [BUGFIX] Fix type for id parameter in `getById` calls ### 1.1.1 - [BUGFIX] Add OpenDxp context check to BodyListener - [BUGFIX] Add `select` type to element property response class mappings ### 1.1.0 - [BUGFIX] Set router context using `RequestContext` in RouteDocumentResolver - [BC BREAK] Response entities changed 1. Replace the response entity `src/Domain/Common/ResponseEntity/Element` with `src/Domain/Common/ResponseEntity/OpenDxpElement`. 2. Replace the response entity `src/Domain/Common/ResponseEntity/ElementProperty` with `src/Domain/Common/ResponseEntity/OpenDxpElementProperty`. 3. Read `mimeType` instead of `mimetype` of `src/Domain/Asset/OpenDxpAsset`. 4. Read `asset.id` and `mimeType` instead of `assetId` and `mime` of `src/Domain/Asset/OpenDxpAssetThumbnail`. 5. Read `frontendPath` instead of `url` of `src/Domain/Asset/OpenDxpAsset`, `src/Domain/Document/OpenDxpDocument` and `src/Domain/DataObject/OpenDxpDataObject`. 6. Read `data` instead of `element` in the responses of `elements/{id}/properties` and `/website-settings`. - [CHORE] Add Symfony PropertyInfo - [ENHANCEMENT] Add OpenAPI attributes for schema and properties, update editable areas transformer - [CHORE] Bump NelmioApiDocBundle to ~5.9.0 - [BC BREAK] Change `Nelmio\ApiDocBundle\Annotation\Model` to `Nelmio\ApiDocBundle\Attribute\Model` 1. Replace `Nelmio\ApiDocBundle\Annotation\Model` with `Nelmio\ApiDocBundle\Attribute\Model` in your code. ### 1.0.1 - [BUGFIX] Use `is_a` for ResponseEntityInterface checks in ResponseEntityPropertyDescriber [#22](https://github.com/open-dxp/headless-bundle/pull/22) ### 1.0.0 - [NEW FEATURE] Initial Release --- ## Migrating to OpenDXP(Headless) ### Migrating from pimcore-headless ### Global Changes - [BC BREAK] DynamicSearch classes have been moved from `src/DynamicSearch` to `src/ThirdParty/DynamicSearch` - migrate according to new namespace: `OpenDxp\Bundle\HeadlessBundle\ThirdParty\DynamicSearch` - [BC BREAK] when using `AbstractElementDefinition` - `locale` field must be added manually (if needed) - field `sub_type` renamed to `subType` - [BC BREAK] in auth/ responses, the property `refresh_token` has been renamed to `refreshToken` --- ## Headless Bundle ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.0` | `^7.4` | 2025 | Feature Branch | 1.x | ### Installation ```json "require": { "open-dxp/headless-bundle": "^1.2", } ``` Add Bundle to `bundles.php`: ```php return [ # add to bottom OpenDxp\Bundle\HeadlessBundle\OpenDxpHeadlessBundle::class => ['all' => true], ]; ``` Add required configuration: ```yaml opendxp_headless: opensearch: hosts: - localhost:9200 # replace with your opensearch credentials: [] ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpHeadlessBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\HeadlessBundle\Migrations'` ### Dependencies - nelmio/api-doc-bundle - lexik/jwt-authentication-bundle - gesdinet/jwt-refresh-token-bundle - w3r-one/json-schema-bundle ### Supported Bundles (but not required) - open-dxp/seo-bundle (Highly Recommended) - open-dxp/i18n-bundle (Highly Recommended) - open-dxp/dynamic-search-bundle (Recommended) - open-dxp/dynamic-search-data-provider-trinity-bundle - open-dxp/dynamic-search-index-provider-opensearch-bundle - open-dxp/formbuilder-bundle ### Using OpenDxp in hybrid mode If you want to use this bundle with a default (classic) OpenDxp installation, please note the following limitations: - The headless-toolbox bundle is not supported - If you're using formbuilder-bundle, ensure the brick is [re-enabled](./docs/25_ConfigurationApiForms.md) *** > [!IMPORTANT] > Before starting with implementation, read the [Concepts](docs/00_Concepts.md) section carefully. > It explains how site-based host configuration works, including General Domain resolution, per-site Asset Base URI, and Flush Frontend Cache setup. ### Next Steps - [Setup/System Configuration](docs/10_OpenDxpConfigurationSecurityDevOps.md) - [Authentication & Certification (JWT)](docs/01_CertificationAuthentication.md) - [OpenDXP Configuration](docs/10_OpenDxpConfigurationSecurityDevOps.md#opendxp-configuration) - [Security](docs/10_OpenDxpConfigurationSecurityDevOps.md#security) - [DevOps](docs/10_OpenDxpConfigurationSecurityDevOps.md#devops) - [Backend Logging](docs/11_BackendLogging.md) - [Configuration](docs/20_Configuration.md) - [Routing](docs/21_ConfigurationRouting.md) - [Introduction](docs/21_ConfigurationRouting.md#introduction) - [Route Document](docs/21_ConfigurationRouting.md#route-document) - [Routes (`routes`)](docs/21_ConfigurationRouting.md#headless-routes) - [API Routes (`api_routes`)](docs/21_ConfigurationRouting.md#api-routes) - [Host Patterns (`host_patterns`)](docs/21_ConfigurationRouting.md#host-patterns) - [Remote Routes (`remote_routes`)](docs/21_ConfigurationRouting.md#remote-routes) - [Asset Routing (`assets`)](docs/21_ConfigurationRouting.md#asset-routing) - [OpenSearch (`opensearch`)](docs/27_ConfigurationOpenSearch.md) - [API Routes for Data Objects (`data_object_api_routes`)](docs/26_ConfigurationApiRoutesForDataObjects.md) - [Response Entity Mapping (`response_entity_mapping`)](docs/23_ConfigurationResponseEntityMapping.md) - [API Filter (`available_filter`)](docs/24_ConfigurationApiFilter.md) - [API Validation / Serialization](docs/40_ApiValidationSerialization.md) - [API Forms (`api_forms`)](docs/25_ConfigurationApiForms.md) - [Frontend Cache (`frontend_cache`)](docs/28_ConfigurationFrontendCache.md) - [API Cache Flush (`api_flush_cache_trigger`), deprecated](docs/28_ConfigurationApiCacheFlush.md) - [Email Configuration (`email_template_paths`)](docs/29_ConfigurationEmailTemplates.md) - [Thumbnail Definitions (`thumbnail_definitions`)](docs/30_ConfigurationThumbnailDefinitions.md) - [CORS Configuration (`cors`)](docs/31_ConfigurationCors.md) - [API Documentation](docs/41_ApiDocumentation.md) - [Response Entities](docs/42_ResponseEntities.md) - [Naming Conventions](docs/43_NamingConventions.md) - [Navigation Enhancement](./docs/50_NavigationEnhancement.md) - [Development Tools](docs/60_DevelopmentTools.md) - [Testing](docs/61_Testing.md) ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Configuration(Headless-ecommerce) ### Clean-Up After you've [installed](https://docs.opendxp.io/docs/bundles/ecommerce/Getting_Started/Installation) the Ecommerce Bundle with in a earlier setup, you need to clean up the default configuration. - Remove `OpenDxp\Ecommerce\Bundle\FrontendBundle\EcommerceFrontendBundle::class` from your `config\bundles.php` - Remove `opendxp.security.password_hasher_factories` from `config/packages/opendxp.yaml` - Remove `parameters.opendxp_ecommerce.security.frontend_regex` from `config/packages/security.yaml` - Remove `providers.opendxp_ecommerce_user` from `config/packages/security.yaml` - Remove `firewalls.opendxp_ecommerce_frontend` from `config/packages/security.yaml` - Remove `%opendxp_ecommerce.security.frontend_regex%/_partial` from `config/packages/security.yaml` in `access_control` *** ### Installation Then, proceed with the installation of the Headless Ecommerce Bundle: #### Security ```yaml # packages/security.yaml security: providers: # [...] guest_provider: id: OpenDxp\Bundle\HeadlessEcommerceBundle\Security\GuestProvider firewalls: # [...] # Ecommerce Headless Bundle Firewall # >> must be added BEFORE headless_api and AFTER opendxp_admin firewall ecommerce_guest: '%opendxp_headless_ecommerce_bundle.guest_firewall_settings%' # [...] ``` #### User Class We need to enrich our user entity with Ecommerce user entity. - Make your user class implementation (e.g. `App\Model\ApiUser`) extending from `\OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ApiUser` - Make your user class interface (e.g. `App\Model\ApiUserInterface`) extending from `\OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ApiUserInterface` - Copy field `customer` from `EcommerceUser` class into to your user class definition - Delete fields `firstname` and `lastname` in your user class definition - Keep the field `locale` in your user class definition. The customer registration sets it to the request locale - Delete `EcommerceUser` class - Add the email validation rule for the endpoint to change the login identifier. See [opendxp-headless docs](https://docs.opendxp.io/docs/bundles/headless/CertificationAuthentication#login-identifier--email-address) for details. #### Account Update The customer profile updates the customer. The account update of the headless bundle (`PUT`/`PATCH /account`) is disabled. A project that needs it, for example for a PWA next to the shop, enables it again: ```yaml opendxp_headless: api_routes: account_update: enabled: true ``` The customer holds the name of the user. The account update therefore changes only the locale. #### Customer Class Make sure the data object class `EcommerceCustomer` implements interface `\OpenDxp\Bundle\HeadlessEcommerceBundle\Model\CustomerInterface` (either in class definition or in your inheritance hierarchy) Add field `token` to `EcommerceCustomerClass`: - Location: In tab `information` at first position - Type: Input - Unique: true - Editable: false #### Product Class Make sure the data object `EcommerceProduct` implements the interface `\OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ProductInterface` (either in class definition or in your inheritance hierarchy). #### Attribute Group Class Adjust class `EcommerceAttributeGroup`: General Settings: - Implements interface(s): `\OpenDxp\Bundle\HeadlessEcommerceBundle\Model\AttributeGroupInterface` Add field `displayType`: - Type: Select - Options Source: Configure - Select Option Values: `list`, `range` Add field `unit`: - Type: Input *** #### Routes Remove all Ecommerce static routes which comes by default after ecommerce bundle installation, except: - `opendxp_ecommerce_product_detail` - `opendxp_ecommerce_category_list` > [!NOTE] > No static routes will be installed if the EcommerceFrontendBundle is not installed. Add the routes manually: ```yaml # backend/app/var/config/staticroutes/opendxp_ecommerce_category_list.yaml opendxp_static_routes: definitions: opendxp_ecommerce_category_list: name: opendxp_ecommerce_category_list pattern: '/(\b(?!admin\b)[a-zA-Z0-9-_]+)\/category\/(.*?)\~c([0-9]+)$/' reverse: /%%_locale/category/%%name-c%category controller: App\Controller\HeadlessController::nullAction variables: '_locale,name,category' defaults: null siteId: { } methods: { } priority: 2 creationDate: 1748444333 modificationDate: 1748444333 ``` ```yaml # backend/app/var/config/staticroutes/opendxp_ecommerce_product_detail.yaml opendxp_static_routes: definitions: opendxp_ecommerce_product_detail: name: opendxp_ecommerce_product_detail pattern: '/(\b(?!admin\b)[a-zA-Z0-9-_]+)\/product\/(.*?)\~p([0-9]+)$/' reverse: /%%_locale/product/%%name-p%product controller: App\Controller\HeadlessController::nullAction variables: '_locale,name,product' defaults: null siteId: { } methods: { } priority: 2 creationDate: 1748444333 modificationDate: 1748444333 ``` #### Validation All entity and form validation are bounded to group `opendxp_ecommerce_api`. If you need to add more granular validation, add your definition to `config/validator/`. Copy all files from `headless-ecommerce-bundle/config/validator/*.yaml.example` to your app `config/validator/` and remove the `.example` suffix. #### Messenger ```bash bin/console messenger:consume opendxp_ecommerce_notification opendxp_ecommerce_index --time-limit=300 ``` #### Dynamic Search This bundles ships some default definitions for category / product lists ```yaml # packages/dynamic_search.yaml dynamic_search: context: default: data_provider: options: always: # add ecommerce objects object_class_names: - EcommerceCategory - EcommerceProduct services: _defaults: autowire: true autoconfigure: true public: false # Create Document Definitions App\DynamicSearch\Definition\Document\EcommerceProductDefinition: ~ # you may want to this class from OpenDxp\Bundle\HeadlessEcommerceBundle\DynamicSearch\Definition\Document\ProductDefinition App\DynamicSearch\Definition\Document\EcommerceCategoryDefinition: ~ # you may want to this class from OpenDxp\Bundle\HeadlessEcommerceBundle\DynamicSearch\Definition\Document\CategoryDefinition ``` *** #### API Describer ##### Route Document Describer ```yaml nelmio_api_doc: documentation: components: schemas: # should already be defined in your project! RouteDocumentAttributes: items: oneOf: - $ref: '#/components/schemas/EcommerceAttribute' # <-- add this one # [...] ``` #### Order Completion Validator Before an order is completed, every registered validator sees it once. A validator that throws stops the completion, and the caller receives the message as a validation error. The bundle ships five of them: they check the customer, the addresses, the payment and shipping provider and the order entity itself. Add your own by implementing the interface: ```php namespace App\Ecommerce\Validator; use OpenDxp\Bundle\HeadlessEcommerceBundle\Domain\Order\Validator\OrderCompletion\OrderCompletionValidatorInterface; use OpenDxp\Bundle\HeadlessEcommerceBundle\Exception\OrderCompletionValidationException; use OpenDxp\Ecommerce\Component\Core\Model\OrderInterface; final readonly class CreditLimitValidator implements OrderCompletionValidatorInterface { public function validate(OrderInterface $order): void { if ($this->exceedsCreditLimit($order)) { throw new OrderCompletionValidationException('credit_limit_exceeded'); } } } ``` ```yaml services: App\Ecommerce\Validator\CreditLimitValidator: tags: - { name: opendxp_headless_ecommerce.validator.order_completion } ``` > [!NOTE] > The string you pass becomes the translation key > `headless.opendxp_ecommerce.validation.error.credit_limit_exceeded`, translated in the locale of the > request. Pass an `errorPath` as the second argument to point the error at a field, or a > `ConstraintViolationList` as the third when one message is not enough. > [!TIP] > A validator only says yes or no. To carry extra data along with the order, extend the form instead, > see the next section. *** ### Extend Order Completion Form Like any other form, you're able to extend the `OpenDxp\Bundle\HeadlessEcommerceBundle\Form\Type\OrderMetaDataType` by using a form extension service. Still, there are two things you need to know: - You're not able to fetch the order object via `$form->getData` (because of security reasons) but will return the submitted metadata as plain array. The order object is available in form options `order`. - You need to take care about the mapping by yourself! Create a form event listener and populate the order via `FormEvent::PRE_SUBMIT` event for example. *** ### Storage Lists Storage Lists will help you to generate simple lists like wishlist / compare list easily ##### Configuration ```yaml opendxp_headless_ecommerce: storage_list: # Wishlist already exists in ecommerce bundle, so we can use the default storage list config wishlist: use_ecommerce_default_storage_list_config: true # Comparelist does not exist in ecommerce bundle, so we have to define the models # Everything else will be handled by ecommerce headless bundle comparelist: api_path_name: compare-list storage_list_model: OpenDxp\Model\DataObject\EcommerceCompareList storage_list_item_model: OpenDxp\Model\DataObject\EcommerceCompareListItem # disable_caching: false / enable and set to true, if you want to disable opendxp object caching for list and list_item # paths: define storage path for data objects paths: list: ecommerce/comparelist item: items ``` ##### Models ###### storage_list_model - needs to extend from `OpenDxp\Bundle\HeadlessEcommerceBundle\StorageList\Model\StorageList` class - required fields: - token [input] - items [ecommerceRelations] - customer [ecommerceRelation] - store [ecommerceStore] ###### storage_list_item_model - needs to extend from `OpenDxp\Bundle\HeadlessEcommerceBundle\StorageList\Model\StorageListItem` class - required fields: - product [ecommerceRelation] (Stack: `opendxp_ecommerce.product`) - quantity [numeric] - storageList [ecommerceRelation] (Stack: `opendxp_ecommerce.[YOUR_STORAGE_LIST_NAME]`) ##### Add To Storage List DTO If you need to use another AddToListDTO: ```yaml opendxp_headless_ecommerce: storage_list: comparelist: add_to_storage_list_dto: App\DTO\YourAddToStorageListDtoClass ``` ##### Expiration If you want to enable the expiration service, add this to your storage_list_config ```yaml opendxp_headless_ecommerce: storage_list: comparelist: expiration: enabled: true params: days: 20 anonymous: true customer: true ``` ##### Storage Form Extension ```yaml services: App\Form\Extension\AddToCompareListFormExtension: tags: - { name: form.type_extension, extended_type: OpenDxp\Bundle\HeadlessEcommerceBundle\StorageList\Form\AddToStorageListType } ``` ```php add('myAdditionalFormField', TextType::class); } } public static function getExtendedTypes(): iterable { return [AddToStorageListType::class]; } } ``` --- ## Variants Many products come in more than one version. A bar counter is sold in white, red and blue, and each color in the sizes S, M and L. The customer buys one concrete version, for example the red counter in size M. Each of these versions is a **variant**. The product that holds them together is the **container**. Two terms appear throughout this page: - An **attribute group** is a property the customer chooses, for example *Color* or *Size*. - An **attribute** is one value of such a group, for example *Red* or *M*. The bar counter is therefore one container with 9 variants. Each variant is one combination of a color and a size. One of the variants is the **main variant**. It is the version the shop shows first. There are three kinds of product. `productType` says which one you got: | | buyable | meaning | |-------------|---------|-----------------------------------------------------------------| | `simple` | yes | A product without variants. It has no attribute groups. | | `container` | no | Holds the variants. It defines the attribute groups. | | `variant` | yes | One combination of attributes below a container. | All three are `EcommerceProduct` objects. A product counts as a container as soon as it has variant attribute groups. A container without maintained variants is still a container. That is a data error and not a different kind of product. To see what a shop can build with this, have a look at the [scenarios](#scenarios) at the end of this page. *** ### Product Detail The detail endpoint returns everything the variant selector needs in `variants`. > [!IMPORTANT] > On the detail page `variants` is an object. In the product listing `variants` is a list with a different shape. ```json { "variants": { "index": [ { "id": 1069, "url": "/en/shop/product/chair-green-xl", "attributes": [ { "groupId": 1073, "attributeId": 1074 }, { "groupId": 1071, "attributeId": 1072 } ] } ], "attributes": [ { "group": { "id": 1073, "name": "color" }, "selected": 1074, "attributes": [] } ], "mainVariant": { "id": 1069, "frontendPath": "https://shop.test/en/shop/product/chair-green-xl" }, "containerProduct": null } } ``` - `attributes` holds the attribute groups the customer picks from. `selected` is the attribute of the current variant. - `index` lists every variant with its combination of attributes and its url. Use it to find the target variant after a pick. - `mainVariant` is the variant to land on. It is set whenever `index` is not empty, and it always points to one of its entries. - `containerProduct` points back to the container. It is `null` on the container itself. #### Redirect A container has no page of its own. When the frontend loads a container, it has to redirect to the main variant: ```js if (product.productType === 'container') { redirect(product.variants.mainVariant.frontendPath) } ``` A `simple` product needs none of this. It is bought on its own page. On a variant you render the selector from `variants.attributes`. When the customer picks another attribute, you look up the variant with the new combination in `variants.index` and send the customer to its url. *** ### Product Listing Which kinds of product the listing shows is up to the project. `preFilter[productType]` takes the kinds you want: ``` GET /shop/products GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container GET /shop/products?preFilter[productType][]=variant ``` - The first request returns every product, containers and variants included. - The second request is the usual overview page. It shows one tile per product. - The third request lists every variant as its own tile. That makes sense when a shop has only a few variants. `preFilter` also narrows the facet counts. Leave it out and you get everything. Every hit carries the variants that belong to it. On a container these are all published variants. On a variant it is the variant itself. A simple product has no variants, so it is its own single entry: ```json { "id": 449, "productType": "container", "mainVariant": { "id": 1069, "url": "https://shop.test/en/shop/product/chair-green-xl" }, "variants": [ { "id": 1069, "url": "https://shop.test/en/shop/product/chair-green-xl", "position": 1, "isMainVariant": true, "image": { "path": "/Products/chair-green.jpg", "thumbnailName": "ecommerce_productList" }, "priceValues": [ { "store": 1, "price": 15000, "retailPrice": 18000, "discountAmount": 3000, "discountPercent": 16.67 } ], "attributes": [ { "attributeGroupId": 1073, "attributeGroupName": "color", "attributeGroupShowInList": true, "attributeId": 1074, "attributeName": "Green", "attributeValue": "green", "attributeType": "color", "attributeColor": "#12eb26" } ] }] } ``` - `position` is the order of the variants below their container. It starts at 1. - `isMainVariant` marks the main variant. It is the maintained main variant if that one is published. Otherwise it is the first published variant. - `image` is the first image of the variant as `ecommerce_productList` thumbnail. It is `null` if the variant has no image of its own. - `priceValues` is the price of this variant per store, after price rules. It has the same shape as `priceValues` on the hit. - `attributeGroupShowInList` is the `showInList` flag of the attribute group. It says whether the values of the group are meant to be shown in product lists. - `attributeType` is either `color` or `default`. Use it to decide whether to draw a colored dot or to print the value as text. > [!NOTE] > Prices are integers in the smallest currency unit. With the default `money_decimal_factor` of 100, `15000` is 150.00. > [!TIP] > A variant without its own images has `image: null`. Fall back to `images` of the hit. A container tile links to `mainVariant.url`, not to the container. With `variants` you can also show the available colors in the tile and link each color to its own variant. #### Filtering `filter[variantAttribute]` filters on variant attributes. The key is the id of the attribute group: ``` GET /shop/products?preFilter[productType][]=container&filter[variantAttribute][1073][]=1074 ``` This keeps every container that has a green variant. If you pass several attribute groups, one and the same variant has to satisfy all of them: ``` GET /shop/products?preFilter[productType][]=container &filter[variantAttribute][1073][]=1074 &filter[variantAttribute][1071][]=1072 ``` A container with a green variant and a separate XL variant does not match here. Only a container that has a green XL variant matches. #### Facets Variant attributes come back as their own filter group. The group is marked with `key: "variantAttribute"`: ```json { "key": "variantAttribute", "id": 1073, "label": "Color", "itemCount": 3, "values": [ { "value": 1074, "label": "Green", "itemCount": 3, "attributeType": "color", "attributeColor": "#12eb26" } ] } ``` `key`, `id` and `value` are the three parts of the request you send when the customer ticks "Green": ``` GET /shop/products?filter[variantAttribute][1073][]=1074 ``` The `itemCount` next to a value says how many products are left if the customer picks it. It counts products, not variants. A container with ten green variants counts as one. Every value also carries `attributeType` and `attributeColor`. A color filter can therefore show colored dots instead of a list of names. *** ### Matching Variants A listing can show one tile per product. The product tile shows one concrete variant. Below it, small tiles show the other variants, each with its image and a link to it. For this, the API has to know which variants fit the filters the customer has set. These are the **matching variants**. Take the bar counter with 9 variants: | Filter in the listing | `variants` | `matchingVariants` | |-----------------------|--------------|------------------------------------------| | none | all 9 | all 9, the main variant first | | Color Red | all 9 | Red S, Red M, Red L | | Red and M | all 9 | only Red M | `variants` always lists everything the product has. `matchingVariants` lists what the current search hit, in the order in which the tile shows it. Add `matchingVariants=true` to the request: ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true ``` Every hit then carries `matchingVariants` and `matchingVariantsTotal`: ```json { "id": 449, "productType": "container", "matchingVariantsTotal": 3, "matchingVariants": [ { "id": 1069, "position": 1, "isMainVariant": true, "priceValues": [], "attributes": [] } ] } ``` - The first entry is the variant to show as the big tile. - The entries have the same shape as the entries in `variants`. - The list holds at most 100 entries. `matchingVariantsTotal` is the exact number. Without `matchingVariants=true`, `matchingVariantsTotal` is `null` and `matchingVariants` is empty. Everything else then works as described above. > [!TIP] > Use `matchingVariantsTotal` to tell the two cases apart. With `matchingVariants=true` it is always at least 1. #### Filters on the variant With `matchingVariants=true`, one and the same variant has to satisfy these filters: - `filter[variantAttribute]` - `filter[range][price]`, compared with the price of the variant in the current store A product matches when at least one of its variants satisfies all of them. All other filters apply to the product as before. The price facet then shows the lowest and the highest variant price in the current store. #### Order The products are ordered like this: 1. With `orderKey=price`, the lowest price of the matching variants counts for `order=asc`. The highest counts for `order=desc`. 2. Products with the same price are ordered by `id`. 3. Without `orderKey=price`, the order is the same as without `matchingVariants`. Within `matchingVariants` the order is: 1. The price in the same direction, if the listing is ordered by price. 2. The main variant before the other variants. 3. `position`. `matchingVariants[0]` is therefore always the variant that placed the product in the list. Without a price order it is the main variant, as long as the main variant satisfies the filters. Otherwise it is the matching variant with the lowest `position`. > [!NOTE] > The big tile is the main variant, not the variant with `position` 1. A bar counter with the main variant White M > shows White M, even though White S comes first. #### Example: small tiles for colors The API does not decide how the small tiles look. This is one way to build them: 1. Group `matchingVariants` by their attributes whose `attributeGroupShowInList` is `true`, for example the color. 2. Every group becomes one small tile. It shows the image of the first variant in the group and links to it. 3. The groups keep the order in which they first appear. The group of `matchingVariants[0]` is therefore first and can be marked as selected. The color group has `showInList` set, the size group does not. A product in three colors and three sizes then shows three small tiles. With the filter "Red" it shows one. > [!NOTE] > `showInList` only groups the small tiles. A product never splits into several big tiles. > [!WARNING] > Changing an attribute group, for example its name or `showInList`, does not update the index. Reindex the products > afterwards. *** ### Extending Variant Entries A project can add its own fields to every entry in `variants`. It does so in its product definition, with two methods of `ProductDefinition`. The first method returns the mapping. The second method returns the values: ```php class EcommerceProductDefinition extends ProductDefinition { protected function getVariantFieldMapping(): array { return ['is_new' => ['type' => 'boolean']]; } protected function getVariantFieldValues(Concrete $variant, array $normalizerOptions): array { return ['is_new' => $variant->getIsNew()]; } } ``` If a key is used twice, the field of the bundle wins. > [!WARNING] > New fields need a rebuilt index mapping. `dynamic-search:os:rebuild-index-mapping` asks for confirmation first. > With `-n` it answers "no" and does nothing. To return the field in the API, extend `ProductSearchVariant` and register the class in `response_entity_mapping`: ```php class ProductSearchVariant extends \OpenDxp\Bundle\HeadlessEcommerceBundle\Domain\Product\ResponseEntity\ProductSearchVariant { #[ApiTransformerProperty(source: 'is_new')] public ?bool $isNew = null; } ``` ```yaml opendxp_headless: response_entity_mapping: OpenDxp\Bundle\HeadlessEcommerceBundle\Domain\Product\ResponseEntity\ProductSearchVariant: App\Domain\Product\ResponseEntity\ProductSearchVariant ``` *** ### Scenarios The same API supports very different product listings. The pictures below all use the same catalogue: a bar counter in three colors and three sizes, a standing table without variants and a bar stool in two colors. Each picture shows the request, the filter sidebar and the tiles the shop can build from the response. #### One tile per product The classic overview page. Each product appears once. A product with variants shows its colors as dots and links to its main variant. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container ``` ![One tile per product](img/variants/01-one-tile-per-product.svg) #### Every variant as its own tile Each variant is a product of its own in the listing. This suits shops with few variants, or shops that want every color and size to be visible at a glance. ``` GET /shop/products?preFilter[productType][]=variant ``` ![Every variant as its own tile](img/variants/02-every-variant.svg) #### Products and variants together Without a pre filter the listing returns containers, variants and simple products side by side. ``` GET /shop/products ``` ![Products and variants together](img/variants/03-products-and-variants.svg) #### Variant as tile, colors as small tiles The big tile is the main variant with its own price and a button to add it to the cart. The small tiles show the colors with their image. Hovering over a small tile shows its group and attribute, for example "Color: Red". Here only the color group has `showInList` set. The size is chosen on the product page, so the size does not create small tiles. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true ``` ![Variant as tile, colors as small tiles](img/variants/04-matching-variants-color.svg) #### Variant as tile, every variant as small tile The same request, but now the color group and the size group both have `showInList` set. Every combination of color and size becomes a small tile: nine for the bar counter, three of them visible and "+6". The tooltip names both attributes, for example "Color: White · Size: S". The first three small tiles are the white counter in M, S and L. They share one photo, only the tooltip tells them apart. `showInList` only decides how the small tiles are grouped. The product still gets exactly one big tile. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true ``` ![Variant as tile, every variant as small tile](img/variants/05-matching-variants-color-size.svg) #### The same listing, filtered by color The customer ticks "Red". The big tile switches to a red variant, and only the red variants remain. The standing table has no color and drops out. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true &filter[variantAttribute][1073][]=1078 ``` ![Filtered by color](img/variants/06-matching-variants-red.svg) #### The same listing, filtered by color and size The customer also ticks "M". Exactly one variant of the bar counter fits, so the small tiles disappear. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true &filter[variantAttribute][1073][]=1078&filter[variantAttribute][1071][]=1080 ``` ![Filtered by color and size](img/variants/07-matching-variants-red-m.svg) #### The same listing, ordered by price The customer sorts by price. Each product is placed by its cheapest variant, and that variant becomes the big tile. The bar counter now shows the blue variant, because it is the cheapest one. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true &orderKey=price&order=asc ``` ![Ordered by price](img/variants/08-matching-variants-price.svg) #### Colors as small tiles, sizes as text Another shop shows the same data differently. The colors become small tiles, and the sizes of the current color appear as a line of text. The API response is the same. Only the frontend decides differently, for example by `attributeType`. ``` GET /shop/products?preFilter[productType][]=simple&preFilter[productType][]=container&matchingVariants=true ``` ![Colors as small tiles, sizes as text](img/variants/09-matching-variants-size-text.svg) #### Product page The product page of a variant builds its selector from `variants.attributes`. Each attribute group becomes a row of choices, and `selected` marks the current one. When the customer picks another color, the frontend looks up the variant with the new combination in `variants.index` and goes to its url. The price and the cart button belong to the variant that is shown. ![Product page](img/variants/10-product-detail.svg) --- ## Request Context Every shop request belongs to a store, a cart, a customer, a currency, a locale and a country. The bundle works these six out on its own, and each of them can be answered differently. ### How a context is resolved Each of the six is a composite. It asks its resolvers one after the other and keeps the first answer it gets: ```php foreach ($this->apiContextResolver as $storeContext) { try { return $storeContext->getStore($routeDocument, $apiRequestAttributes); } catch (StoreNotFoundException) { continue; } } ``` > [!IMPORTANT] > Throwing is how a resolver says "not mine". A resolver that answers with a fallback ends the chain, > and every resolver behind it is never asked again. Each context has its own exception for this: `StoreNotFoundException`, `CartNotFoundException`, `CustomerNotFoundException`, `CurrencyNotFoundException`, `LocaleNotFoundException` and `CountryNotFoundException`. ### What the resolvers receive A resolver gets the route document of the request, and the request attributes. The attributes are every request header that starts with `X-OpenDxp-Api-`, with that prefix removed: ``` X-OpenDxp-Api-Shop-Store: 2 -> $apiRequestAttributes['shop-store'] X-OpenDxp-Api-Locale: de -> $apiRequestAttributes['locale'] ``` The route parameters are there as well, under `route_attributes`. ### What the bundle ships | Context | Resolver | Answers from | |----------|---------------------------------|----------------------------------------------------------------------------| | store | `ApiStoreContext` | the site of the route document, then `shop-store`, then the standard store | | cart | `ApiTokenValueBasedCartContext` | the token value of the cart | | customer | `ApiTokenBasedCustomerContext` | the authenticated token | | currency | `ApiStoreBasedCurrencyContext` | the store | | country | `ApiStoreBasedCountryContext` | the store | | locale | `ApiLocaleContext` | the request | > [!TIP] > `ecommerce_request_context` lists the resolvers of your installation in the order they are asked. > See [Development Tools](https://docs.opendxp.io/docs/bundles/headless/DevelopmentTools/). ### Adding a resolver Implement the interface of the one context you want to change, and tag the service. A store that follows the domain rather than the site looks like this: ```php final readonly class DomainBasedStoreContext implements ApiStoreContextInterface { public function __construct(private StoreRepositoryInterface $storeRepository) { } public function getStore(?RouteDocument $routeDocument, array $apiRequestAttributes): StoreInterface { $host = $apiRequestAttributes['route_attributes']['_host'] ?? null; $store = $host === null ? null : $this->storeRepository->findOneByHost($host); if ($store === null) { throw new StoreNotFoundException(); } return $store; } } ``` ```yaml services: App\Ecommerce\Context\DomainBasedStoreContext: tags: - { name: opendxp_headless_ecommerce.context.store, priority: 100 } ``` The tag decides which context the resolver belongs to, the priority decides when it is asked. The resolvers of the bundle sit at priority `0`, so anything above runs first and anything below is the fallback. > [!NOTE] > Replacing a resolver of the bundle is rarely what you want. Put yours in front of it and throw when > it does not apply. The shipped one then still answers everything you did not think of. --- ## Payment Provider #### PostFinance Checkout https://github.com/dachcom-digital/payum-postfinance-flex Override the lightbox view: ```yaml # config/packages/twig.yaml twig: paths: '%kernel.project_dir%/templates/bundles/PayumPostFinanceFlex': PayumPostFinanceFlex ``` ```twig # backend/app/templates/bundles/PayumPostFinanceFlex/action/lightbox.html.twig { "javascriptUrl": "{{ javascriptUrl }}", "transactionId": "{{ transactionId }}" } ``` ### Entity Lock If you want to use the entity lock feature (recommended), add the `OptimisticLockedInterface` to the order object! --- ## Factories #### Model Factory To redefine model attributes, set your own attributes like this (make sure to implement the corresponding interface): ```yaml opendxp_headless_ecommerce: model_factory: OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ProductPrice: App\Model\ProductPrice ``` ##### Supported Models - OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ProductPrice - OpenDxp\Bundle\HeadlessEcommerceBundle\Model\ShippingPrice #### Route Document Attribute Factory To redefine the route document attributes, set your own attributes like this: ```yaml opendxp_headless_ecommerce: route_document_attribute_factory: OpenDxp\Bundle\HeadlessEcommerceBundle\RouteDocument\Attribute\CustomerAttribute: App\Ecommerce\RouteDocument\Attribute\CustomerAttribute ``` ##### Supported Attributes - OpenDxp\Bundle\HeadlessEcommerceBundle\RouteDocument\Attribute\CartAttribute - OpenDxp\Bundle\HeadlessEcommerceBundle\RouteDocument\Attribute\CountryAttribute - OpenDxp\Bundle\HeadlessEcommerceBundle\RouteDocument\Attribute\CurrencyAttribute - OpenDxp\Bundle\HeadlessEcommerceBundle\RouteDocument\Attribute\CustomerAttribute - OpenDxp\Bundle\HeadlessEcommerceBundle\RouteDocument\Attribute\StoreAttribute *** --- ## Testing(Headless-ecommerce) The headless ecommerce bundle adds `ShopApi` to the test API of the headless bundle. It lives in `OpenDxp\Bundle\HeadlessEcommerceBundle\Test`. `ShopApi` works like `Api`, but it sends every request to a store. This page builds on [Testing of the headless bundle](https://docs.opendxp.io/docs/bundles/headless/Testing) and [Testing of the ecommerce bundle](https://docs.opendxp.io/docs/bundles/ecommerce/Getting_Started/Tests). ### Setup Set up your suite as the [headless bundle describes it](https://docs.opendxp.io/docs/bundles/headless/Testing#setup). The shop needs one addition to it. A customer signs in with a user of your API user class. Let your user factory extend `AbstractShopUserFactory` instead of `AbstractApiUserFactory`: ```php */ final class UserFactory extends AbstractShopUserFactory { public static function class(): string { return User::class; } } ``` Its state `forCustomer()` creates a user for a customer. The user and the customer then point to each other. Always create customers with `CustomerFactory::new()->guest()`. Without this state, the factory also creates a user of the `EcommerceUser` class, which a headless shop does not have. ### Sending a request Assume your project adds an endpoint `GET /shop/products/{id}/availability` that reports the stock of a product. The test creates the product, sends the request to the default store and compares the response: ```php withPrice(2000) ->inStock(5) ->create(); $path = sprintf('/shop/products/%d/availability', $product->getId()); $browser = ShopApi::start(InstalledShop::defaultStore())->get($path); $browser->assertStatus(200); expect($browser->json()->decoded())->toBe([ 'available' => true, 'onHand' => 5, ]); }); ``` Prices are in cents. `withPrice()` sets the price in the default store. ### Choosing the store Every request to a path below `/shop` or `/data-objects/ecommerce` needs a store. Otherwise the API returns status 400. Use `InstalledShop::defaultStore()` for the store that the installer of the ecommerce bundle creates: ```php use OpenDxp\Bundle\HeadlessEcommerceBundle\Test\ShopApi; use OpenDxp\Ecommerce\Test\Story\InstalledShop; $browser = ShopApi::start(InstalledShop::defaultStore())->get('/shop/countries'); ``` `ShopApi` accepts any store, so you may also pass a store that your test creates with `StoreFactory`. To check that your endpoint refuses a request without a store, send it with `Api` of the headless bundle: ```php use OpenDxp\Bundle\HeadlessBundle\Test\Api; Api::start()->get('/shop/countries')->assertStatus(400); ``` ### Authenticated customers Use `ShopApi::actingAs()` when your endpoint requires a signed-in customer. Create the customer first and then a user for it: ```php use App\Tests\Factory\UserFactory; use OpenDxp\Bundle\HeadlessEcommerceBundle\Test\ShopApi; use OpenDxp\Ecommerce\Test\Factory\AddressFactory; use OpenDxp\Ecommerce\Test\Factory\CustomerFactory; use OpenDxp\Ecommerce\Test\Story\InstalledShop; it('lists the addresses of the customer', function () { $user = UserFactory::new() ->forCustomer( CustomerFactory::new() ->guest() ->withAddresses(AddressFactory::new()) ->create(), ) ->create(); $browser = ShopApi::actingAs($user, InstalledShop::defaultStore())->get('/shop/addresses'); $browser->assertStatus(200); }); ``` `$user->getCustomer()` returns the customer when your test needs it later. ### Guests A guest has no user. The guest endpoints carry the token of the guest in the path instead: ```php use OpenDxp\Bundle\HeadlessEcommerceBundle\Test\ShopApi; use OpenDxp\Ecommerce\Test\Factory\CustomerFactory; use OpenDxp\Ecommerce\Test\Story\InstalledShop; $guest = CustomerFactory::new() ->guest() ->create(['token' => 'the-token-of-a-guest']); $browser = ShopApi::start(InstalledShop::defaultStore()) ->get(sprintf('/shop/guests/%s/addresses', $guest->getToken())); ``` The API returns status 401 for a token that belongs to no guest. ### Carts Use `OrderFactory` when your test needs a stored cart. `forCustomer()` assigns the cart to a customer, and `withItems()` adds one piece of each product: ```php use App\Tests\Factory\UserFactory; use OpenDxp\Bundle\HeadlessEcommerceBundle\Test\ShopApi; use OpenDxp\Ecommerce\Test\Factory\CustomerFactory; use OpenDxp\Ecommerce\Test\Factory\OrderFactory; use OpenDxp\Ecommerce\Test\Factory\ProductFactory; use OpenDxp\Ecommerce\Test\Story\InstalledShop; it('hides the cart of a customer from another customer', function () { $owner = UserFactory::new() ->forCustomer( CustomerFactory::new() ->guest() ->create(), ) ->create(); $cart = OrderFactory::new() ->forCustomer($owner->getCustomer()) ->withItems( ProductFactory::new() ->withPrice(2000) ->create(), ) ->create(); $other = UserFactory::new() ->forCustomer( CustomerFactory::new() ->guest() ->create(), ) ->create(); $browser = ShopApi::actingAs($other, InstalledShop::defaultStore()) ->get(sprintf('/shop/orders/%s', $cart->getToken())); $browser->assertStatus(404); }); ``` A cart without a customer is readable by anyone who knows its token. Leave out `forCustomer()` to test this case. When your test needs a cart that can be completed, add a carrier, the addresses and a payment provider: ```php use OpenDxp\Ecommerce\Test\Factory\AddressFactory; use OpenDxp\Ecommerce\Test\Factory\CarrierFactory; use OpenDxp\Ecommerce\Test\Factory\CustomerFactory; use OpenDxp\Ecommerce\Test\Factory\OrderFactory; use OpenDxp\Ecommerce\Test\Factory\PaymentProviderFactory; use OpenDxp\Ecommerce\Test\Factory\ProductFactory; $address = AddressFactory::createOne(); $cart = OrderFactory::new() ->forCustomer( CustomerFactory::new() ->guest() ->create(), ) ->withItems( ProductFactory::new() ->withPrice(2000) ->create(), ) ->shippedBy(CarrierFactory::createOne()) ->shippedTo($address) ->invoicedTo($address) ->paidWith(PaymentProviderFactory::createOne()) ->create(); ``` ### Sending other headers `ShopApi` takes the same options as `Api` of the headless bundle. Pass them when every request of a test needs a further header, for example a site: ```php use OpenDxp\Bundle\HeadlessEcommerceBundle\Test\ShopApi; use OpenDxp\Ecommerce\Test\Story\InstalledShop; use OpenDxp\Test\Factory\SiteFactory; use Zenstruck\Browser\HttpOptions; $site = SiteFactory::createOne(); $options = HttpOptions::create()->withHeader('X-OpenDxp-Api-Site', (string) $site->getId()); $browser = ShopApi::start(InstalledShop::defaultStore(), $options)->get('/shop/countries'); ``` ### Test API | Class or method | What it does | |----------------------------------------------|--------------------------------------------------------------------------------| | `ShopApi::start($store, $options)` | Sends requests without a user to the store. | | `ShopApi::actingAs($user, $store, $options)` | Sends requests to the store with the token of the user. | | `AbstractShopUserFactory` | The states of `AbstractApiUserFactory`, plus `forCustomer(CustomerInterface)`. | --- ## Changelog(Headless-ecommerce) ### 1.2.1 - [SECURITY] [OPENDXP-SA-2026-022] The catalog feed answers a language the system does not offer with 404, instead of building a feed and a cache file for it - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.2.0 - [CHORE] [OPT-IN] The development tools for AI agents run on Symfony AI Mate instead of `open-dxp/mcp-bundle`. The skill `mate-headless-ecommerce` takes the place of the two decisions, see the README 1. Only if your coding agents used the MCP tools of this bundle: run `composer require --dev open-dxp/mate-extension`. 2. Set up Mate as the [installation of `open-dxp/mate-extension`](https://github.com/open-dxp/mate-extension#installation) describes. - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [CHORE] Require `open-dxp/headless-bundle` ^1.4 - [CHORE] Require `open-dxp/ecommerce-bundle` ^1.2 - [NEW FEATURE] [HIGHLIGHT] `ShopApi` sends test requests to a store of the shop API, see [Testing](docs/30_Testing.md) > Test the shop API of your project. `ShopApi` sends test requests to a store. - [NEW FEATURE] `AbstractShopUserFactory` creates the user of a customer in a test, see [Testing](docs/30_Testing.md) - [ENHANCEMENT] [FOLLOW-UP] The shop API answers 404 for an address of another customer or guest, like for an address that does not exist. It answered 403 before 1. Only if your project overrides the form `ecommerce_address` or `ecommerce_guest_address`: set `form_data_resolver` to `AddressDataResolver`, `form_data_voter_status_code` to `404` and `form_data_voter_message` to `'address not found'`. - [BUGFIX] A shop request without the header `X-OpenDxp-Api-Shop-Store` answers 400. It answered 500 before - [BUGFIX] Adding a product to a cart answers 404 for an unknown or foreign cart and for an unknown product. Completing an unknown or foreign cart answers 404. Both answered 500 before - [BUGFIX] An unknown `addressType` for the address of a cart answers 400. It answered 500 before - [ENHANCEMENT] The guest routes require `ROLE_ECOMMERCE_GUEST`, so the API documentation lists their 401 and 403 - [BUGFIX] `ApiGuestUser::getLastname()` returns the last name. It returned the first name before - [DEPRECATION] `ApiGuestUser::eraseCredentials()`. The API keeps no session, so 2.0 removes the method - [ENHANCEMENT] The bundle registers the headless bundle itself and loads it first, whatever order `bundles.php` has - [ENHANCEMENT] The customer registration sets the locale of the user to the request locale - [ENHANCEMENT] The account update of the headless bundle is disabled, see [Account Update](docs/01_Configuration.md#account-update) ### 1.1.3 - [NEW FEATURE] **Matching Variants**: `matchingVariants=true` returns `matchingVariants` and `matchingVariantsTotal` per hit, see [Variants](docs/02_Variants.md#matching-variants) - [ENHANCEMENT] Entries in `variants` carry `position`, `isMainVariant`, `image` and `priceValues`, attributes carry `attributeGroupShowInList` - [ENHANCEMENT] `ProductDefinition::getVariantFieldMapping()` and `getVariantFieldValues()` add project fields to the entries in `variants` - [BUGFIX] A container is indexed again when one of its variants is added, saved or deleted - [ENHANCEMENT] [FOLLOW-UP] A simple product is now its own single entry in `variants`, the list is no longer empty 1. Run `bin/console dynamic-search:os:rebuild-index-mapping` and confirm. The command drops the index. 2. Run `bin/console dynamic-search:run`. ### 1.1.2 - [NEW FEATURE] OpenDXP MCP support: the `ecommerce_request_context` tool and two decisions about context resolution and order completion (requires `open-dxp/mcp-bundle`) - [ENHANCEMENT] **Variants**: `productType`, `mainVariant`, `containerProduct`, `variants`, `preFilter[productType]`, `filter[variantAttribute]` and a `variantAttribute` facet - [ENHANCEMENT] `attributeType` and `attributeColor` added to attribute and facet values - [ENHANCEMENT] `priceValues` added to `ProductSearchItem`, the price after price rules - [ENHANCEMENT] `ProductSearchItem` arrays typed and enums declared, generated clients no longer end up with `unknown` - [BUGFIX] `listAttributes` and `rangeAttributes` returned snake_case keys, `categories` returned an always empty `key` and swallowed `depth` - [BUGFIX] Price facet used `store_values`, filter and sort use `price_values` ### 1.1.1 - [ENHANCEMENT] Support Ecommerce Bundle 1.1.1 added - [ENHANCEMENT] Also list `variantAttributes` in `EcommerceProduct` - [BUGFIX] Fixed config path in storage list extension ### 1.1.0 - [ENHANCEMENT] [FOLLOW-UP] **Attributes Builder** Feature has been removed. It's a [Ecommerce Core Feature](https://github.com/open-dxp/ecommerce-bundle/pull/37) now. 1. Disable the flag `isVariantAware` of your `AttributeGroup` objects after the update to the latest `EcommerceBundle`. The Ecommerce Bundle treats every group as variant aware by default. 2. Replace `ProductAttributeSetAwareInterface` with `OpenDxp\Ecommerce\Component\Variant\Model\ProductVariantAwareInterface`. 3. Only if your system has the class `AttributeSet`: change the type of the field `attributeSet` from `manyToOneRelation` to `ecommerceRelation` with the stack `opendxp_ecommerce.attribute_set`. ### 1.0.7 - [BUGFIX] Change `PRE_SUBMIT` to `SUBMIT` event listeners in form extensions for address and gender handling - [ENHANCEMENT] Add `priority` attribute configuration for form fields (customer/guest/address) ### 1.0.6 - [ENHANCEMENT] Add `frontendPath` frontendPath property to `EcommerceOrderItemProduct` - [ENHANCEMENT] Improved OpenAPI support for configurable product options and extended API response handling - [ENHANCEMENT] Allow `null` as `addressIdentifier` in `AddressIdentifierFilter` ### 1.0.5 - [BUGFIX] Cast request attribute in AddressFormOptionsResolver - [ENHANCEMENT] Added support for configurable submit button behavior and introduced `SubmitTypeExtension` ### 1.0.4 - [BUGFIX] Ensure unique token generation for customers to prevent constraint violations - [BUGFIX] Decoupled store schema description logic - [ENHANCEMENT] Add Schema routes to `customer_create` and `guest_create` ### 1.0.3 - [BUGFIX] **Attributes Builder**: Fixed admin locale resolution to use `getContentLanguages()` instead of `getLanguage()` for correct mapping to localized field values - [BUGFIX] **Attributes Builder**: Fixed hardcoded `de` key when generating attribute key name — now uses first available locale instead - [ENHANCEMENT] Added `nelmio_api_doc` example schema for `EcommerceAttribute` to bundle config - [CHORE] Restructured Attributes Builder setup instructions, added Route Document Describer section ### 1.0.2 - [BUGFIX] Fixed `FieldSort` arguments order and also some minor phpstan issues ### 1.0.1 - [BUGFIX] Added `ProductAttributeSetAwareInterface` for enhanced attribute set handling [#5](https://github.com/open-dxp/headless-ecommerce-bundle/pull/5) - [BUGFIX] Updated event listener configuration to use `opendxp_headless` namespace for event tags - [BUGFIX] Fixed term query field name from `sub_type` to `subType` - [ENHANCEMENT] PHP 8.5 support added - [ENHANCEMENT] Registered thumbnail installation configuration for OpenDxpHeadlessEcommerceExtension - [ENHANCEMENT] Improved install documentation - [ENHANCEMENT] Refined configuration documentation: updated examples and corrected typos in storage list section - [ENHANCEMENT] Added example static route configurations for product details and category lists in documentation ### 1.0.0 - [NEW FEATURE] Initial Release --- ## Migrating to OpenDXP(Headless-ecommerce) ### Migrating from coreshop-headless #### Naming Changes - Namespace changed from `OpenDxp\Bundle\HeadlessEcommerceBundle\` to `OpenDxp\Bundle\HeadlessEccomerceBundle` - Root config changed from `core_shop_headless` to `opendxp_ecommerce_headless` - Tags changed from `headless.coreshop.` to `opendxp_headless_ecommerce.` - Validation groups changed from `coreshop_api` to `opendxp_ecommerce_api` - Form block prefixes changed from `coreshop_` to `opendxp_ecommerce_` - Form and translation labels prefix from `coreshop.` to `opendxp_ecommerce.` - Twig Extension changed from `coreshop_headless_product_price` to `headless_ecommerce_product_price` - Twig Extension changed from `coreshop_headless_shipping_price` to `headless_ecommerce_shipping_price` - Voter Identifier prefix changed from `CORE_SHOP_` to `ECOMMERCE_` - Headless Context name `coreshop` changed to `ecommerce` - Command `coreshop-headless:catalog-feed:generate` changed to `opendxp-headless-ecommerce:catalog-feed:generate` - OpenDxp Tag `coreShopProductAttributesBuilder` changed to `ecommerceProductAttributesBuilder` - Parameter `core_shop_headless.config` changed to `opendxp_headless_ecommerce.config` #### Security Changes You need to define a `guest_provider`: ```yaml security: providers: # [...] guest_provider: id: OpenDxp\Bundle\HeadlessEcommerceBundle\Security\GuestProvider ``` --- ## Headless Ecommerce Bundle ### Release Plan | Release | Supported Ecommerce Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|------------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.0` | `^7.4` | 2026 | Feature Branch | 1.x | ### Installation ```json "require": { "open-dxp/headless-ecommerce-bundle": "^1.0", } ``` Add Bundle to `bundles.php`: ```php return [ # add after OpenDxp\Bundle\HeadlessBundle\OpenDxpHeadlessBundle OpenDxp\Bundle\HeadlessEcommerceBundle\OpenDxpHeadlessEcommerceBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console ecommerce:install` - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\HeadlessEcommerceBundle\Migrations'` Optional: - Execute: `$ bin/console assets:install public --relative --symlink` #### Updating Ecommerce Bundle - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Ecommerce\Bundle\CoreBundle\Migrations'` #### Updating Ecommerce Headless Bundle - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\HeadlessEcommerceBundle\Migrations'` ### Disabled Services - RequestCartRecalculation - RequestCartAvailability - ShopUserLogoutHandler - CartBlamerListener - CustomerNewsletterConfirmListener *** ### Next Steps - [Setup, Configuration](docs/01_Configuration.md) - [Product / Variant Concept](docs/02_Variants.md) - [Request Context](docs/05_RequestContext.md) - [Payment Provider](docs/10_PaymentProvider.md) - [Factories](docs/20_Factories.md) - [Testing](docs/30_Testing.md) *** ### Development Tools With [Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html) and [open-dxp/mate-extension](https://github.com/open-dxp/mate-extension) installed, this bundle adds to them: - `ecommerce_request_context` lists the resolvers that decide the store, cart, customer, currency, locale and country of a request - the skill `mate-headless-ecommerce` says when to rely on the shipped resolvers, when to write one, and how to take part in completing an order Nothing of this is loaded without Mate. *** ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Configuration(Headless-toolbox) #### Config: Default Headless Frontend Base URL ```yaml opendxp_headless_toolbox: default_headless_frontend_base_url: 'https://my-application.ch' # the object preview opens it when the editor chooses no site ``` --- #### Config: Dynamic Admin CSP Header This bundle dynamically extends admin CSP handling (`Content-Security-Policy` response header of the admin). For each OpenDXP site that should be added to the CSP `frame-ancestors` directive, enable the **"Add Main Domain to CSP Header"** checkbox in the site's custom settings: > *Admin → Sites → [select site] → Custom Settings → Headless Toolbox → Add Domain to CSP* --- ## Normalizer ### Objective The primary goal of normalizers is to standardize API output across different endpoints and data structures. This ensures consistency whether data is returned within a brick (relation) or through a dedicated API endpoint (e.g., `/api/products`). ### General Rules - **If a brick returns data that is also available in other API endpoints**, you must create a normalizer that applies the appropriate headless transformers and denormalizers. - **If the data is unique to a specific context**, you can define the response directly within the `headlessAction`. To facilitate this, the toolbox provides built-in normalizers that can be applied automatically to specified types. *** ### Toolbox Normalizer Overrides Some normalizers in the Toolbox bundle are overridden by their headless counterparts: | Toolbox Normalizer | Overridden by | Assigned to Editable by Default | |----------------------------------------------------|--------------------------------------------------------------------|---------------------------------------------------| | `OpenDxp\Bundle\ToolboxBundle\Normalizer\LinkNormalizer` | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessLinkNormalizer` | `link` | | `OpenDxp\Bundle\ToolboxBundle\Normalizer\ImageEditableNormalizer` | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessImageEditableNormalizer` | None (used in Toolbox for certain image elements) | ### Additional Headless Toolbox Normalizers These normalizers are assigned by default to specific editable elements: | Normalizer | Assigned to Editable by Default | |----------------------------------------------------------------|---------------------------------| | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessInputNormalizer` | `input` | | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessTextareaNormalizer` | `textarea` | | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessWysiwygNormalizer` | `wysiwyg` | | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessThumbnailNormalizer` | `image` | | `OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessVideoNormalizer` | `vhs` | #### Default Normalizers These additional normalizers are automatically applied when the bundle is installed (see the config block below). To override them, simply define them within the same structure. ```yaml # toolbox-bundle-bundle/config/opendxp/config.yaml # this config block is available, if the toolbox headless bundle is installed # you don't have to redefine them again in your project as long you don't have to override something opendxp_toolbox: property_normalizer: default_type_mapping: image: OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessThumbnailNormalizer vhs: OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessVideoNormalizer link: OpenDxp\Bundle\ToolboxBundle\Normalizer\LinkNormalizer wysiwyg: OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessWysiwygNormalizer textarea: OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessTextareaNormalizer input: OpenDxp\Bundle\HeadlessToolboxBundle\Normalizer\HeadlessInputNormalizer ``` *** ### Custom Normalizers You can define and apply your own normalizers to transform specific brick elements. #### Transformer Normalizer A transformer normalizer is useful when converting structured data within a brick. ##### Configuration ```yaml opendxp_toolbox: areas: foo_bar: inline_config_elements: relation: type: table title: 'Table' property_normalizer: App\Toolbox\Normalizer\TableNormalizer ``` ##### Implementation ```php applyHeadlessTransformer( $value, MyTransformer::class, [] ); } } ``` #### Denormalizer A denormalizer is useful when transforming related objects (e.g., data objects) into response entities. ##### Configuration ```yaml opendxp_toolbox: areas: foo_bar: inline_config_elements: relation: type: relation title: 'My Entity' config: types: - object subtypes: object: - object classes: - MyEntity property_normalizer: App\Toolbox\Normalizer\MyEntityNormalizer ``` ##### Implementation ```php getElement(); if (!$myEntity instanceof DataObject\MyEntity) { return null; } return $this->applyDenormalizer($myEntity, MyEntityResponseEntity::class); } } ``` ### Summary - **Use normalizers** to unify API responses across bricks and endpoints. - **Default normalizers** are available and can be applied automatically to common data types. - **Custom normalizers** allow transformation and denormalization of specific data structures. - **Transformers** modify brick-specific structured data. - **Denormalizers** convert related objects into standardized response entities. By following these guidelines, you ensure a consistent and maintainable API response structure across your project. --- ## Additional Headless Toolbox Bricks #### Raw HTML Content - Name: `raw_html_content` - Description: Use it to pass raw content to api output --- ## Testing(Headless-toolbox) Frontend teams usually generate their API client from the OpenAPI documentation, for example with orval. When a brick returns JSON that the documentation does not describe, the generated types are wrong. The test API of this bundle catches these mistakes in the tests of your project. It lives under `OpenDxp\Bundle\HeadlessToolboxBundle\Test`. This page builds on [Testing of the headless bundle](https://docs.opendxp.io/docs/bundles/headless/Testing) and [Testing of the toolbox bundle](https://docs.opendxp.io/docs/bundles/toolbox/Testing). ### Setup Install the JSON Schema validator: ```bash composer require --dev opis/json-schema ``` Register the expectation in `tests/Pest.php`: ```php use OpenDxp\Bundle\HeadlessToolboxBundle\Test\Expectation\Schemas; Schemas::register(); ``` ### Testing a brick Say your project has an areabrick `opening_hours`. In the headless layout it has two inline config elements, the input `days` and the input `hours`. Your suite describes one instance of it with a brick class `OpeningHoursBrick`. [Fill a page with content](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing/Factories_and_Stories#fill-a-page-with-content) shows how you write such a class. The test creates a page for one of your headless documents with `HeadlessPageFactory`, places the brick in an areablock of the document and validates the JSON of the page: ```php use App\Tests\Brick\OpeningHoursBrick; use OpenDxp\Bundle\HeadlessToolboxBundle\Test\Factory\HeadlessPageFactory; use OpenDxp\TestFoundation\Browser; it('matches the API schema', function () { $page = HeadlessPageFactory::new() ->forDocument('landing_page') ->withBricks('content', OpeningHoursBrick::open('Monday to Friday', '8:00 to 17:00')) ->create(); $json = Browser::visit($page->getFullPath())->content(); expect($json)->toMatchOpenApiSchema('HeadlessDocumentLandingPage'); }); ``` `forDocument()` takes the name of a headless document from your configuration. `withBricks()` takes the name of one of its areablocks. The schema of a headless document is named after it: `landing_page` becomes `HeadlessDocumentLandingPage`. The bricks of the toolbox areabricks are ready to use in `OpenDxp\Bundle\ToolboxBundle\Test\Brick`. Call `forHeadless()` on them, because the headless layout reads some of their editables under other names: `HeadlineBrick::saying('Opening hours')->forHeadless()`. ### Describing additional data The bundle describes the editables of your areabrick from its configuration. The JSON and the schema read the same configuration, so they agree on every editable. You only add a description when the areabrick returns more than its editables: - Data that `headlessAction()` adds to the response: put an `#[OA\Schema]` on the areabrick class. - The output of a normalizer of your own: put an `#[OA\Schema]` on the normalizer class. ```php use OpenApi\Attributes as OA; #[OA\Schema( properties: [ new OA\Property(property: 'isOpenNow', type: 'boolean'), new OA\Property(property: 'nextOpening', type: 'string', nullable: true), ], type: 'object' )] final class OpeningHours extends AbstractAreabrick implements ToolboxHeadlessAwareBrickInterface { } ``` A value of `headlessAction()` replaces an editable under the same name, in the JSON and in the schema. Describe the value as the action returns it. When the action can return `null`, mark the property `nullable`. This also holds for an editable with `omit_data_output`: the JSON leaves out the editable, but not the value of the action. An areabrick or a normalizer that extends another one keeps its description, unless it has one of its own. The test validates against the whole API documentation, so it checks these descriptions too. ### Test API | Class | What it gives | |-----------------------|-----------------------------------------------------------------------------------------------------------| | `HeadlessPageFactory` | A page of a headless document. `forDocument()` names the document. | | `Schemas` | The expectation `toMatchOpenApiSchema()`, which validates JSON against a schema of the API documentation. | ### Failures The test fails when the JSON contains a property that the schema does not describe, when a value has the wrong type, or when a value is `null` but the schema does not allow it. The message lists the path of every property that fails. --- ## Changelog(Headless-toolbox) ### 1.3.1 - [BUGFIX] The object preview opens the site chosen in the preview ### 1.3.0 - [NEW FEATURE] [HIGHLIGHT] Test API to check headless JSON against the API schema [Read more](./docs/30_Testing.md) > A test API checks the headless JSON of your bricks against the API schema. - [ENHANCEMENT] The API schema uses the property names of the toolbox (`headless.camel_case_property_names`) - [ENHANCEMENT] The discriminator of a headless document follows the template name of the headless bundle, `_cmsTemplate` with camelCase - [ENHANCEMENT] The API schema of `HeadlessLinkNormalizer` references `OpenDxpLink` of the headless bundle - [BUGFIX] Correct the API schema of the gallery, iframe, image, link and video bricks - [BUGFIX] The API schema of `HeadlessVideoNormalizer` references `OpenDxpVideo` of the headless bundle. It describes the player parameters as a map and the converted videos as they are output - [BUGFIX] The API schema describes a value of a headless action instead of the element it replaces, like the `type` of the columns brick - [BUGFIX] The API schema describes a value of a headless action under the name of an element with `omit_data_output` - [BUGFIX] An areabrick or a normalizer that extends another one keeps its API schema - [BUGFIX] The API schema describes an editable in a block of a brick with the normalizer that the JSON uses - [BUGFIX] The API documentation is valid with a normalizer whose schema references a model, like `HeadlessThumbnailNormalizer` - [CHORE] Require `open-dxp/toolbox-bundle` ^1.2 and `open-dxp/headless-bundle` ^1.4 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.2.1 - [ENHANCEMENT] PHP 8.5 support added ### 1.2.0 - [NEW FEATURE] Add dynamic CSP header support for the OpenDXP admin: site domains can be individually allowed via a new "Add Domain to CSP" checkbox in site custom settings (`headless_toolbox` scope). ### 1.1.0 - [ENHANCEMENT] Add OpenAPI Annotations to Normalizer Classes and Introduce Default Toolbox Describer ### 1.0.0 - [NEW FEATURE] Initial Release --- ## Headless Toolbox Bundle [![Software License](https://img.shields.io/badge/license-GPLv3-brightgreen.svg?style=flat-square)](LICENSE.md) ### Release Plan | Release | Supported Toolbox Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.0` | `^7.4` | 2025 | Feature Branch | 1.x | ### Installation ```json "require": { "open-dxp/toolbox-bundle" : "~1.0.0" "open-dxp/headless-toolbox-bundle" : "^1.2" } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\ToolboxBundle\OpenDxpToolboxBundle::class => ['all' => true], OpenDxp\Bundle\HeadlessToolboxBundle\OpenDxpHeadlessToolboxBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpHeadlessToolboxBundle` *** ### Documentation - [Configuration](docs/00_Configuration.md) — bundle config, dynamic CSP header setup - [Normalizer (Overrides and Additional Normalizer)](docs/10_Normalizer.md) - [Additional Headless Toolbox Bricks (raw_html_content ...)](docs/20_HeadlessToolboxBricks.md) - [Testing](docs/30_Testing.md) *** ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Localize Documents **Q: Which documents do i need to translate within a zone?** A: Basically every "physically" document. For example we want to add a `product` page: ![Localized documents](./img/localize_documents.png) In this example there are several documents available: | Document | Locale | |:--------------------------|:-------| | `domain4/de/produkte` | de | | `domain4/en/products` | en | | `domain4/nl-nl/producten` | nl_NL | | `domain4/en-us/products` | en_US | | `domain5/produits` | fr | ### Localization Use the [localization service](https://docs.opendxp.io/docs/core-framework/Best_Practice/Multilanguage_Setup#localization-tool) to connect all available documents: - `domain4/de/produkte` - `domain4/en/products` - `domain4/nl-nl/producten` - `domain4/en-us/products` - `domain5/produits` If you're going to open one of those pages and check the source code you'll find the generated href-tags on top. Now let's check each element again: | Document | Description | |:--------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `domain4/de/produkte` | It's a real document. | | `domain4/en/products` | It's a real document. | | `domain4/nl-nl/producten` | It's a real document. | | `domain4/de-ch` | It's a hardlink. I18n Bundle will add this document automatically for you. That's the ["magic"](27_Countries.md#magic) we talked about earlier. | | `domain4/fr-ch` | Also a hardlink. I18n Bundle will add this document automatically for you. That's the ["magic"](27_Countries.md#magic) we talked about earlier. | | `domain4/en-us/products` | A hardlink! But now there is a dedicated document so you also need to add it to the translation service. If you want to hide it, skip the translation service and just disable it. | | `domain4/en_AU/products` | Also a hardlink. I18n Bundle will add this document automatically for you. That's the ["magic"](27_Countries.md#magic) we talked about earlier. | | `domain5/produits` | It's a real document. | | `domain6/it` | There is no product page, so no translation needed! | --- ## Geo Control > The Data provider is only required if you want to use the country detection! > Follow the [official instructions](https://dev.maxmind.com/geoip/geoipupdate/) for obtaining and updating the GeoIP database. Store the database file at the location of your choice, the default location used by _geoipupdate_ is `/usr/share/GeoIP/GeoLite2-City.mmdb` Set the path to the database file in your `config.yaml` to enable the geo support in OpenDXP: ```yaml opendxp.geoip.db_file: /usr/share/GeoIP/GeoLite2-City.mmdb ``` To keep the BC, I18n also will check the project path `var/config/GeoLite2-City.mmdb` for legacy reasons. --- ## Navigation Caching Every navigation has a default cache key. If you're using this bundle, your navigation links may change the url structure after switching the context (browsing from `/en` to `/en-us` for example). > Since `/en-us/` could be a hardlink, all underlying links need to be transformed (otherwise they would still point to `/en/xy`) So, always bind your navigation cache key to the current locale: ```twig {% set menu = opendxp_build_nav(page.document, page.document, null, app.request.locale) %} ``` --- ## User Detection Events The `UserHelper` dispatches two events that allow you to intercept and override the user's detected language list and country before the default detection logic runs. Calling `stopPropagation()` on the event skips the built-in detection entirely and uses the value you set instead. --- ### Override accepted languages **Event:** `i18n.user.languages` **Event class:** `OpenDxp\Bundle\I18nBundle\Event\UserLanguagesEvent` **Constant:** `I18nEvents::USER_LANGUAGES` Dispatched at the start of `UserHelper::getLanguagesAcceptedByUser()`, before the `Accept-Language` header is parsed. #### Use cases - Force a specific language for a user group (e.g. based on a session value or JWT claim) - Map custom language codes to OpenDXP-valid language codes - Return an empty list to suppress automatic language detection #### Example ```php 'onUserLanguages', ]; } public function onUserLanguages(UserLanguagesEvent $event): void { $session = $this->requestStack->getSession(); $language = $session->get('preferred_language'); if ($language !== null) { $event->setLanguages([$language]); $event->stopPropagation(); // skip Accept-Language header parsing } } } ``` --- ### Override detected country **Event:** `i18n.user.country` **Event class:** `OpenDxp\Bundle\I18nBundle\Event\UserCountryEvent` **Constant:** `I18nEvents::USER_COUNTRY` Dispatched at the start of `UserHelper::guessCountry()`, before the GeoIP database is consulted. #### Use cases - Override country detection via a session or cookie value - Use a custom IP-to-country resolver instead of GeoIP - Provide country detection when no GeoIP database is configured #### Example ```php 'onUserCountry', ]; } public function onUserCountry(UserCountryEvent $event): void { $session = $this->requestStack->getSession(); $country = $session->get('forced_country'); if ($country !== null) { $event->setCountry(strtoupper($country)); $event->stopPropagation(); // skip GeoIP lookup } } } ``` --- ### Registering listeners ```yaml # config/services.yaml services: App\EventListener\UserLanguagesListener: tags: - { name: kernel.event_subscriber } App\EventListener\UserCountryListener: tags: - { name: kernel.event_subscriber } ``` --- ### Passing `null` as country `setCountry(null)` is a valid override — it signals that the country is intentionally unknown. Only `stopPropagation()` determines whether the GeoIP lookup is skipped; the value itself may be `null`. --- ## Cookie settings If you want to change the Symfony default cookie settings, you have an option to do so. ### Set custom cookie settings The cookie redirector stores the page, the language and the country of a visitor in a cookie. You can change the settings of this cookie. Every setting you leave out keeps its default value. > Customizing the `raw` cookie parameter using this config is not implemented right now! ```yaml # config/packages/i18n.yaml opendxp_i18n: registry: redirector: cookie: config: cookie: path: '/yourpath/' domain: 'yourdomain.com' secure: true http_only: true same_site: strict ``` #### Default values ```yaml # config/packages/i18n.yaml opendxp_i18n: registry: redirector: cookie: config: cookie: path: '/' domain: null secure: false http_only: true same_site: lax expire: '+1 year' ``` #### Possible values for same_site `same_site` supports the following values: - none - lax - strict --- ## Development Tools(I18n) ### Mate [Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html) gives an AI agent tools that read the running application. This bundle adds its tool when Mate is installed. An agent reaches it through `open-dxp/mate-extension`. Set Mate up as the extension describes. `i18n_zones` shows each configured zone with its locales and the route keys without a translation. It also shows each site of the local database with its zone and its language pages, and the locales of each zone without a page. The skill `mate-i18n` tells the agent what a new language needs and how a test builds a site with a zone. --- ## I18n Workflow ![I18n workflow](./img/i18n_workflow.png) ### I18n Context I18n will generate a `I18nContextInterface` object at **every request** which is accessible via the resolver service `I18nContextResolverInterface`. Which means, that you're able to fetch the `I18nContextInterface` via `[DI] $contextResolver->getContext($request)` wherever a valid frontend-request is available! #### Locale Definition The I18n Context contains a `LocaleDefinitionInterface` object, which contains all locale information about the requested locale. #### Route Item The I18n Context contains a `RouteItemInterface` object, which terminates the right route process. - If the i18n context gets resolved via request, the route item will be generated depending on the request attributes (static route, symfony route, document) - If the i18n context gets resolved by a headless context generation or a simple `url(route_name, {})`, the route item will be generated depending on the route parameters (static route, symfony route, document) #### Zone The I18n Context contains a `ZoneInterface` object, which holds all active zone information (allowed/active locales, bounded domains) ##### Zone Site Each `ZoneInterface` object is able to contain one or more `ZoneSiteInterface` objects. Each Site contains dedicated information and also provides an `SiteRequestContext` object. The site request context holds some important information (like `host`, `port`) which are required when it comes to absolute URL generation! *** ### Router I18n will decorate the `router` service. This is required to provide a simple way generating URLs in different contexts (twig, API, command line). The I18nRouter automatically takes care about the correct router context. If you need absolute URLs for example, just set `UrlGeneratorInterface::ABSOLUTE_URL` and you're good to go. *** ### OpenDXP Link Generator Every LinkGenerator needs to implement the `I18nLinkGeneratorInterface` and should extend from the `AbstractRequestAwareLinkGenerator`! This is required to: - allow i18n to generate translatable static routes by itself. - prevent the request from being used - simplify the path construction ⚠️ You shouldn't use the `generate()` method anymore. If you're supporting/using Object-Links within WYSIWYG/Link-Elements, the `AbstractRequestAwareLinkGenerator` will do the job for you. However, like this class already implies it by its class name, it requires a valid request and therefor it only should be used for the generation of links inside WYSIWYG/Link-Elements. ```php getRouteParametersBag()->set('object_id', $object->getId()); return $linkGeneratorRouteItem; } // the generate() method is available via AbstractRequestAwareLinkGenerator // and should ONLY be used for links which are coming from WYSIWYG/Link-Elements. } ``` ### OpenDXP Preview Generator If you want to use the opendxp object preview, you may want to use the included generator. Just add the Service `@OpenDxp\Bundle\I18nBundle\PreviewGenerator\ObjectPreviewGenerator` in your class definition. ![Preview generator in the class definition](./img/preview_generator.png) This will add: - A locale selection (Default value: Current Admin-Users default locale. If not available, the first locale from the list will be selected) - A site selection (Only, if Sites are available. Default value: Current Host. If not available, the first site from the list will be selected) ![Locale and site selection in the preview](./img/preview_toolbar.png) *** ### Static Routes A static route pattern can use the route translations of i18n as container parameters. Define the translation in your configuration: ```yaml opendxp_i18n: translations: - key: 'myStaticRouteKey' values: de: 'meine-statische-route' en: 'my-static-route' ``` Use it in the static route in `var/config/staticroutes/my_static_route.yaml`: ```yaml opendxp_static_routes: definitions: my_static_route: name: my_static_route pattern: '/([a-zA-Z0-9-_]*)\/(?:%i18n.route.translations.myStaticRouteKey%)\/(.*?)$/' ## returns (meine-statische-route|my-static-route) reverse: '/{%%_locale}/@myStaticRouteKey/%%object_id' controller: App\Controller\DefaultController::staticRouteAction variables: '_locale,object_id' defaults: null siteId: { } methods: { } priority: 1 creationDate: 1634472684 modificationDate: 1634472684 ``` ### Symfony Routes I18n also supports (localized) symfony routes. You need to pass the `_i18n` default flag (can be an array or just a boolean flag). #### Localized Symfony Routes ```yaml my_symfony_route: path: de: /de/i18n/symfony-default-rut fr: /fr/i18n/symfony-default-ruteee de_CH: /de-ch/i18n/symfony-default-route-guetzli en: /en/i18n/symfony-default-route controller: App\Controller\DefaultController::symfonyRouteAction defaults: _i18n: true ``` #### I18n Localized Symfony Routes Every I18n translation key is available as a regex parameter (`i18n.route.translations.TRANSLATION_KEY_NAME`). This allows you to define translations at a global scope and is much cleaner to configure ```yaml # config/packages/i18n.yaml opendxp_i18n: translations: - key: 'mySymfonyRouteKey' values: de: 'meine-symfony-route' en: 'my-symfony-route' ``` ```yaml # config/routes.yaml my_symfony_route: path: /{_locale}/i18n/{matching_route_key} controller: App\Controller\DefaultController::symfonyRouteAction defaults: _i18n: translation_keys: matching_route_key: mySymfonyRouteKey requirements: matching_route_key: '(%i18n.route.translations.mySymfonyRouteKey%)' ## returns (meine-symfony-route|my-symfony-route) ``` ### Twig|PHP Route Generation - [Current Request Routes for Documents](./90_DocumentRoutes.md#generating-routes-in-current-request) - [Current Request Routes for Static Routes](./91_StaticRoutes.md#generating-routes-in-current-request) - [Current Request Routes for Symfony Routes](./92_SymfonyRoutes.md#generating-routes-in-current-request) - [Data Object Routes](./93_DataObjectRoutes.md#generating-routes) ### Command Line Route Generation Generating absolute URLs in CLI is easy! - [CLI Routes for Documents](./90_DocumentRoutes.md#generating-routes-in-cli) - [CLI Routes for Static Routes](./91_StaticRoutes.md#generating-routes-in-cli) - [CLI Routes for Symfony Routes](./92_SymfonyRoutes.md#generating-routes-in-cli) ### Non-I18n Routes I18n always requires the `_i18n` parameter node in `urlGenerator->generate`. If this node is not present, the default route generation will be triggered. ```php dump($router->generate('my_non_i18n_aware_symfony_route', ['_locale' => 'en'], UrlGeneratorInterface::ABSOLUTE_URL)); ``` ### Context I18n allows you to easily fetch the current context via a given request object. Read more about it [here](21_I18nContext.md). ### Custom Context Boot Generating a complete headless context object via twig or php api. Read more about it [here](21_I18nContext.md#custom-context-look-up). ### Code Examples Please check out the [code examples](./60_CodeExamples.md) doc section to learn more about accessing zone information. --- ## Zone Definitions ![Zones](./img/zones.png) By default, the i18nBundle works with the global settings (see example below). But you may need some more complex structures, so we implemented the zone manager. #### Default Configuration Options | Name | Description | |----------------|-------------------------------------------------| | locale_adapter | Locale Adapter (`system`, by default) | | default_locale | Define a default locale (like `de`, `en_US`) | | translations | [Static Route translations](91_StaticRoutes.md) | | zones | Array for complex Zones | #### Zone Configuration Options Basically there are the same options as in the default configuration, except that you can't define zones within zones. The translations of a zone add to the global translations. For a key and a locale in both, the zone wins. | Name | Description | |----------------|-------------------------------------------------| | locale_adapter | Locale Adapter (`system` by default) | | default_locale | Define a default locale (like `de`, `en_US`) | | translations | [Static Route translations](91_StaticRoutes.md) | #### Assigning a Site to a Zone Zones are assigned per site via the OpenDXP admin. After you've configured the zone (see config below), open the site settings in backoffice and select the desired zone from the **Zone** dropdown (under the `i18n` configuration scope). Once zones are configured, every site needs a zone. A request to a site without a zone fails, and so does a request to a domain without a site. #### Configuration ```yaml opendxp_i18n: # define a locale adapter (system|custom) locale_adapter: system # define a default locale - this value is optional default_locale: 'en' # define scheme request_scheme: 'http' # define port request_port: 80 # static route translations translations: ~ zones: # zone 1: language zone1: id: 1 config: locale_adapter: system translations: ~ # zone 2: language and country zone2: id: 2 config: locale_adapter: system translations: ~ # zone 3: no language switch. just a simple website. zone3: id: 3 config: locale_adapter: system translations: ~ ``` --- ## Current Context Fetch the current context to list linked languages for example: ```twig
i18n Current Context
{% set i18n_current_context = i18n_current_context() %} {{ dump(i18n_current_context) }} {{ dump(i18n_current_context.linkedLanguages) }}
    {% for link in i18n_current_context.linkedLanguages %}
  • {{ link.url }}
  • {% endfor %}
``` **PHP** ```php getContext($requestStack->getMainRequest()); $linkedLanguages = $i18nContext->getLinkedLanguages(); } } ``` ### Custom Context Look-Up In some cases, you want to retrieve all available links for a specific document or object. #### Boot Context in TWIG ```twig

I18n Context Look-Up (document)

{% set document_context = i18n_create_context_by_entity(opendxp_document(16), { _locale: 'en' }) %} {{ dump(document_context) }} {{ dump(document_context.linkedLanguages) }}

I18n Context Look-Up (object [will call correspondig link generator])

{% set object_context = i18n_create_context_by_entity(opendxp_object(16), { _locale: 'en' }) %} {{ dump(object_context) }} {{ dump(object_context.linkedLanguages) }}

I18n Context Look-Up (symfony route)

{% set object_context = i18n_create_context_by_symfony_route('my_symfony_route, { _locale: 'en' } }) %} {{ dump(object_context) }} {{ dump(object_context.linkedLanguages) }}

I18n Context Look-Up (static route)

{% set object_context = i18n_create_context_by_static_route('my_static_route', { _locale: 'fr', object_id: 16 } }) %} {{ dump(object_context) }} {{ dump(object_context.linkedLanguages) }} {# If you're using zones, you NEED to pass the site as context! #}

I18n Context Look-Up with Zones (document)

{% set zone_aware_document_context = i18n_create_context_by_entity(opendxp_document(16), { _locale: 'en' }, opendxp_site_by_domain('my-site.test')) %} {{ dump(zone_aware_document_context) }} {{ dump(zone_aware_document_context.linkedLanguages) }} ``` #### Boot Context in PHP ```php i18nContextManager = $i18nContextManager; } public function build(OpenDxp\DataObject $object, array $routeParameter) { ## I. no zones defined $parameters = [ 'routeParameters' => $routeParameter, 'entity' => $object ]; // third argument needs to be true to fully boot context (initialize linked zone sites) $i18nContext = $this->i18nContextManager->buildContextByParameters(RouteItemInterface::STATIC_ROUTE, $parameters, true); ## II. zones available ## You MUST pass the site as context! $zoneAwareParameters = [ 'routeParameters' => $routeParameter, 'entity' => $object, 'context' => [ 'site' => $site ] ]; $zoneAwareI18nContext = $this->i18nContextManager->buildContextByParameters(RouteItemInterface::STATIC_ROUTE, $zoneAwareParameters, true); dump($zoneAwareI18nContext); } } ``` ### Zone without a Request `buildZoneBySite()` builds the zone of a site the same way as a request does, with its sites and language pages. It does not use the zone cache. Without configured zones, pass `null` for an installation without sites. `buildZoneByIdentifier()` builds a configured zone with its locales, without its sites. Without configured zones, pass `null` to get the global zone. ```php $zone = $this->i18nContextManager->buildZoneBySite(Site::getByDomain('my-site.test')); foreach ($zone->getSites(true) as $zoneSite) { dump($zoneSite->getLocale(), $zoneSite->getUrl()); } ``` --- ## href-lang Tags ![href-lang tags](./img/hreflang.png) The i18nBundle will handle the href lang tags for you which are very important for search engines. ### Prearrangement It's very important that you connect your localized documents using the [opendxp localization service](https://docs.opendxp.io/docs/core-framework/Multi_Language_i18n/Localize_your_Documents). > **Note**: If you're **not** localizing your documents, no href lang tags will be generated, which will lead to a negative impact on your SEO strategies. There is, however, some magic if you're using the [country mode](27_Countries.md). **Localization Connector:** There's a [dedicated help document](100_LocalizeDocuments.md) we wrote for you to get all the knowledge for heroic document localization! ### X-Default i18n will generate a x-default link, based on default values: #### Default Locale Workflow - First, the i18nBundle will search for the `default_locale` config. - If not defined, the default system locale will be used - If not defined, NULL will be returned (which means, no x-default tag) > **Note**: It's possible to override the `getDefaultLocale()` method within a custom locale adapter. **Important:** Be sure that your defined default locale is valid (in current zone). Otherwise, no x-default tag will be generated. ### Static Routes If you're using static routes, please [read this](91_StaticRoutes.md) to enable href-lang tags for dynamic routes. --- ## Create a website with language context 1. [Enable all](https://docs.opendxp.io/docs/core-framework/Multi_Language_i18n/) required languages in opendxp backend. 2. [Localize your Documents](https://docs.opendxp.io/docs/core-framework/Multi_Language_i18n/Localize_your_Documents). 3. Connect them via the localization tool. **Localization Connector:** There is a [dedicated help document](100_LocalizeDocuments.md) we wrote for you to get all the knowledge for heroic document localization! > **Note:** Make sure that all your child documents are localized too. For multi-language sites (e.g. example.org/de and example.org/en): Please ensure that the site document (domain, e.g. example.org) does not have a defined language (Document => Tab "Navigation & Settings" => "Language" Dropdown: Select `None` and save). For singe-language sites you have to set the language on the site document. --- ## Create a website with country context This is only required if you're using i18n with a country adapter. There are two ways to implement a country page like `en-us`: 1. Copy and paste the `en` document tree and rename `en` to `en-us`. 2. Create a hardlink, call it `en-us` and set the reference to `en`. 3. Change language to `en_US`. > If you're using a hardlink, check out the [canonical information part](80_CanonicalLinks.md). ### Naming Convention You might be wondering why we named the hard link `en-us`. For default documents, that's not a problem. But you'll run into serious troubles if you need to build static routes with it. Read [this section](91_StaticRoutes.md) to solve this bravely. ### Preparation Localize your [documents first](26_Languages.md). ### Country Wrapper If you're using a hardlink for country specific data, create it. Otherwise just create a document as you would normally do. Read more about the [static route configuration](91_StaticRoutes.md). ### Magic All hardlink references will be generated automatically. So if you have have a page in `/en/about-us` the href-lang generator or context helper searches in all available hardlinks. If you're having a `/en-us` hardlink, a link to `/en-us/about-us` will be automatically generated (for href-lang and the `getLinkedLanguages` [context helper](60_CodeExamples.md) for example). In case, you don't want to have a `about-us` page in `/en-us`, just create the page `/en-us/about-us` and disable it. There is also some further magic you need to know about: If you have just one language but multiple countries, you're unable to link them via the localization tool. I81nBundle will then try to generate all hardlinks references automatically. --- ## Front Page Mapping Sometimes you want to clone a page and expand it with some [country](27_Countries.md) information. For example: ```text - /en - about-us - team - /en-us -> that's your hardlink with a en_US locale. ``` > Note: Learn how to implement a country site based on hardlinks by [clicking here](27_Countries.md). Now you have a brand new shiny website. If you open the `/en-us/team` page, it will automatically load the content from `/en/team`. That's nice. If you want to override the team content you just need to copy your `/en/team` into the `/en-us/` tree. Now you're good to go to add some additional content. But what if you want to override the front page content? That's a tricky one since `en-us` is just a hardlink. #### i18n to the rescue Just add a new (document) property named `front_page_map` to your hardlink and assign a custom document. Also disable the inheritance option for this property. You can leave the document unpublished, so it stays private. > This property should be available in your predefined properties since it gets automatically installed. Just navigate to `/en-us` front page again and you'll see the new content. --- ## Localized Error Documents Please use the OpenDXP default error document definition. These can be set globally via system settings and additionally via site configuration. --- ## Custom Locale Adapter In most cases there is no need of a custom adapter since both default adapters are sufficient for your daily business. If you're using complex zones, however, you may want to deliver different data for each zone. #### 1. Create a Service ```yaml # config/services.yaml App\Services\I18nBundle\LocaleAdapter\SpecialLocaleProvider: parent: I18nBundle\Adapter\LocaleProvider\AbstractLocale decorates: I18nBundle\Adapter\LocaleProvider\SystemLocaleProvider # use a decorator public: false arguments: - '@App\Services\I18nBundle\LocaleAdapter\SpecialLocaleProvider.inner' tags: - { name: i18n.adapter.locale, alias: special } ``` #### 2. Set Locale Adapter in your Configuration ```yaml # config/packages/i18n.yaml opendxp_i18n: locale_adapter: special ``` #### 3. Create a class Create a class, extend it from `AbstractLocale`. In this example, we'll remove some locales if we're in a different zone (example code below). We're also using the `system` adapter as a decorator, so we don't have to implement all methods again. ```php systemLocaleProvider = $systemLocaleProvider; } public function getDefaultLocale(array $zoneDefinition): ?string { return $this->systemLocaleProvider->getDefaultLocale($zoneDefinition); } public function getActiveLocales(array $zoneDefinition): array { // get default locales $validLocales = $this->systemLocaleProvider->getActiveLocales($zoneDefinition); // remove some locales in zone 4 if ($this->currentZoneId === 4) { unset($validLocales[0]); unset($validLocales[1]); } return $validLocales; } public function getLocaleData(array $zoneDefinition, $locale = '', $field = null, $keyIdentifier = 'locale'): mixed { return $this->systemLocaleProvider->getLocaleData($zoneDefinition, $locale, $field, $keyIdentifier); } public function getGlobalInfo(array $zoneDefinition): array { return $this->systemLocaleProvider->getGlobalInfo($zoneDefinition); } } ``` --- ## Redirector Adapter If a visitor enters your website, i18n tries to find a valid locale based on several conditions. There are three redirectors implemented. Every redirector triggers (based on priority) a `makeDecision` method. If the service is able to resolve the redirection, it will return the redirection url. If not, the next redirector gets applied. #### Cookie Redirector > Priority: `300` If enabled, visitor gets redirected to the last selected locale Configuration: ``` config: cookie: path: domain: secure: http_only: same_site: expire: ``` #### GEO Redirector > Priority: `200` If enabled, visitor gets redirected based on IP and browser language Configuration ``` config: rules: - { ignore_country: false, strict_country: true, strict_language: false } - { ignore_country: false, strict_country: false, strict_language: false } ... ``` #### Fallback Redirector > Priority: `100` If enabled, visitor gets redirected based on the `default_locale` setting defined in i18n settings (available in each zone) or by default locale defined in your opendxp system settings. ### Define Redirect Status Code By default, a redirect will be dispatched with code `302`. If you want to change it, you need to update your config: ```yaml # config/packages/i18n.yaml opendxp_i18n: redirect_status_code: 301 ``` ### Disable a Redirector ```yaml # config/packages/i18n.yaml opendxp_i18n: registry: redirector: cookie: enabled: false ``` ### Create a Custom Redirector #### 1. Create a Service ```yaml # config/services.yaml App\Services\I18nBundle\RedirectorAdapter\Website: parent: I18nBundle\Adapter\Redirector\AbstractRedirector public: false tags: # we want to trigger our redirector *before* the fallback comes in - { name: i18n.adapter.redirector, alias: website, priority: 110 } ``` #### 2. Enable you can also provide config for your redirector ```yaml # config/config.yaml opendxp_i18n: registry: redirector: website: enabled: true config: my_config_node: 'value' # etc ... ``` #### 3. Create a class Create a class, extend it from `AbstractRedirector`. ```php lastRedirectorWasSuccessful($redirectorBag) === true) { return; } // get custom config $myConfigValue = $this->config['my_config_node']; // get the last decision bag $lastDecisionBag = $redirectorBag->getLastRedirectorDecision(); // now, since the last decision was not successful: // we need to find a locale for redirect. $decisionName = $lastDecisionBag['name']; $decisionData = $lastDecisionBag['decision']; // last decision was "geo" as we prioritized our service explicitly. // if you're not sure, use the $decisionName to check the last redirector name // checkout the geo options: $redirectorOptions = $decisionData['redirectorOptions']; /* * This example assumes that you're on localhost: * - geoCountry is empty because the "geo" redirector couldn't resolve your country * * dump($redirectorOptions); * * returns an array: * Array ( * [geoLanguage] => [de, de_DE, ...] * [geoCountry] => false * ) * */ // get all valid zone domains // and check if there is something we can offer. $currentZoneId = $redirectorBag->getI18nContext()->getZone()->getId(); $zoneSites = $redirectorBag->getI18nContext()->getZone()->getSites(true); // only do something in zone 4. if($currentZoneId !== 4) { $this->setDecision(['valid' => false]); return; } // example: if geoCountry is empty, // we always want a redirection to "de_CH" if (empty($redirectorOptions['geoCountry'])) { $indexId = array_search('de_CH', array_map(static function (ZoneSiteInterface $site) { return $site->getLocale(); }, $zoneSites), true); // we found a valid locale if ($indexId !== false) { /** @var ZoneSiteInterface $zoneSite */ $zoneSite = $zoneSites[$indexId]; $this->setDecision([ 'valid' => true, 'locale' => $zoneSite->getLocale(), 'country' => $zoneSite->getCountryIso(), 'language' => $zoneSite->getLanguageIso(), 'url' => $zoneSite->getHomeUrl() ]); } else { // otherwise, we invalidate our decision // so the next redirector ("fallback" in our case) is allowed to find another route. $this->setDecision(['valid' => false]); } // otherwise, we invalidate our decision // so the next redirector ("fallback" in our case) is allowed to find another route. } else { $this->setDecision(['valid' => false]); } } protected function getConfigResolver(): ?OptionsResolver { $optionsResolver = new OptionsResolver(); // preare your options resolver $optionsResolver->setRequired('my_config_node'); $optionsResolver->setAllowedTypes('my_config_node', 'string'); // etc .. return $optionsResolver; } } ``` --- ## OpenDXP Redirects with I18n ![OpenDXP redirects](./img/redirects.png) If you want to implement the i18n redirect guesser, you need to add `{i18n_localized_target_page=4}` instead of the document path in the `target` section. ### Facts - Be sure that your documents are connected, otherwise the detection won`t work. - If you want to redirect an unknown host (Example A), be sure you set the redirect `priority` to `99`. ### Example #### Given Structure **Domain**: `mydomain.com` **Document Tree**: - de - kollektion - kampagne - en - collection - landingpage ### Example A: - Enter host `my-old-collection-domain.com` - i18n should redirect to `mydomain.com/de/kollektion` if user is german - i18n should redirect to `mydomain.com/en/collection` if user is english ### Example B: - Enter host `mydomain.com/landingpage` - i18n should redirect to `mydomain.com/de/kampagne` if user is german - i18n should redirect to `mydomain.com/en/landingpage` if user is english --- ## Code Examples ### I18n Context | Name | Description | |------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------| | getRouteItem | return `RouteItemInterface` | | getZone | returns `ZoneInterface` | | getLocaleDefinition | returns `LocaleDefinitionInterface` | | getCurrentZoneSite | returns `ZoneSiteInterface` | | getCurrentLocale | get current locale | | getCurrentLocaleInfo | get detailed information about active locale | | getLocaleInfo | get locale info of given locale from locale | | getZoneDefaultLocale | get default locale of zone | | getZoneActiveLocales | returns an array of all active/allowed locales in zone | | getZoneGlobalInfo | international state | | getCurrentCountryAndLanguage | get country and locale info | | getLinkedLanguages | get all (raw) linked documents of current route | | getActiveLanguages | helper method to list all active languages of current route (see [navigation code example](./60_CodeExamples.md#navigation-examples)) | | getActiveCountries | helper method to list all active countries and languages of current route (see [navigation code example](./60_CodeExamples.md#navigation-examples)) | | getLanguageNameByIsoCode | helper to get language name by iso code | | getCountryNameByIsoCode | helper to get country name by iso code | #### Fetch Context Data in Twig ```twig {# be careful, i18n_current_context is allowed to return null! #} {% set current_locale = i18n_current_context().localeDefinition.locale %} {% set current_language_iso = i18n_current_context().localeDefinition.languageIso %} {% set current_country_iso = i18n_current_context().localeDefinition.countryIso %} {{ dump(i18n_current_context().localeDefinition.locale) }} {{ dump(i18n_current_context().linkedLanguages) }} {{ dump(i18n_current_context().activeLanguages) }} {{ dump(i18n_current_context().activeCountries) }} {{ dump(i18n_current_context().languageNameByIsoCode(current_language_iso, current_locale)) }} {{ dump(i18n_current_context().countryNameByIsoCode(current_country_iso, current_locale)) }} {{ dump(i18n_current_context().zoneActiveLocales()) }} {{ dump(i18n_current_context().localeInfo('de', 'id')) }} ``` #### Fetch Context Data in PHP ```php getContext($requestStack->getMainRequest()); $LinkedLanguages = $i18nContext->getLinkedLanguages(); // get current locale $currentLocale = $i18nContext->getLocaleDefinition()->getLocale(); // get current language iso $currentLanguageIso = $i18nContext->getLocaleDefinition()->getLanguageIso(); // get linked languages $linkedLanguages = $i18nContext->getLinkedLanguages(); // get linked languages, but only rootDocuments $linkedLanguages = $i18nContext->getLinkedLanguages(true); // get language name by iso code $languageName = $i18nContext->getLanguageNameByIsoCode($currentLanguageIso, $currentLocale); // locale provider info $localProviderActiveLocales = $i18nContext->getZoneActiveLocales(); $localeProviderLocaleInfo = $i18nContext->getLocaleInfo('de', 'id'); } } ``` ### Zone The zone represents an instance of `I18nZoneInterface` which comes with some helper methods: | Name | Description | |---------------------|-----------------------------------------------------------------------------------------------------------------------| | getId | given zone id (null, if it no zones have been configured | | getName | given zone name (null, if no zones have been configured | | getDomains | all available domains for given zone. | | getTranslations | array, translations for dynamic routes | | isActiveZone | check if zone is active one | | getLocaleUrlMapping | For example: `de-ch`. Mostly used to build [static routes](./91_StaticRoutes.md#naming-convention-in-country-context) | | getGlobalInfo | international state | | getSites | get all corresponding sites | #### Fetch Zone Data in Twig ```twig {# be careful, i18n_current_context is allowed to return null! #} {{ dump(i18n_current_context().zone.sites) }} ``` #### Fetch Zone Data in PHP ```php getContext($requestStack->getMainRequest()); $zone = $i18nContext->getZone(); // list all zone sites $zoneSites = $zone->getSites(true); } } ``` #### Zone Current Site Information To retrieve data from an active site, you may want to use the `$i18nContext->getCurrentZoneSite()` method. Since the current site gets defined via the current locale, be sure that locale is always available. The current site represents an instance of `ZoneSiteInterface` which comes with some helper methods: | Name | Description | |-----------------------------------|------------------------------------------------------------------------------------------------------------------------------| | getSiteRequestContext | returns `SiteRequestContext` object | | SiteRequestContext::getScheme | For example: `http` | | SiteRequestContext::getHttpPort | For example: 80 | | SiteRequestContext::getHttpsPort | For example: 443 | | SiteRequestContext::getDomainUrl | For example: `https://opendxp-domain4.test` | | SiteRequestContext::getHost | For example: `www.opendxp-domain4.test` | | SiteRequestContext::getNone3wHost | For example: `opendxp-domain4.test` | | isRootDomain | bool | | getLocale | For example: `de_CH` | | getCountryIso | For example: `CH` | | getLanguageIso | For example: `de` | | getHrefLang | For example: `de-ch` | | getLocaleUrlMapping | For example: `de-ch`. Mostly used to build [static routes](../docs/91_StaticRoutes.md#naming-convention-in-country-context). | | getUrl | For example: `https://opendxp-domain4.test/de-ch` | | getHomeUrl | string | | getFullPath | For example: `domain4/de-ch` | | getType | For example: `hardlink` | | getSubSites | array | | hasSubSites | bool | #### Fetch Zone Site Data in Twig ```twig {# get current context info #} {{ dump(i18n_current_context().currentZoneSite.url) }} {{ dump(i18n_current_context().currentZoneSite.localeUrlMapping) }} ``` #### Fetch Zone Site Data in Twig ```php getContext($requestStack->getMainRequest()); $currentContextInfo = $i18nContext->getCurrentZoneSite()->getUrl(); $currentContextInfo = $i18nContext->getCurrentZoneSite()->getLocaleUrlMapping(); } } ``` ### Navigation Examples #### Language Selection ```twig {% set current_context = i18n_current_context() %} {% if current_context is not null %} {% set languages = current_context.activeLanguages %} {% if languages is iterable %} {% endif %} {% endif %} ``` #### Country Grouped Selection ```twig {% set current_context = i18n_current_context() %} {% if current_context is not null %} {% set countries = current_context.activeCountries %} {% if countries is iterable %} {% endif %} {% endif %} ``` #### Complex Country / Language Selection based on Current Zone ```twig ``` --- ## Context Switch Event This Event will help you to manage additional tasks if the zone/language/country gets changed. This feature is disabled by default, so you need to enable it first if you need it: ```yaml opendxp_i18n: enable_context_switch_detector: true ``` ### Use Case Example If you have a complex e-commerce environment for example, you may want to check the cart against new prices, stock and availability of products if the user changes the country and/or the language. ### Important Stuff to know - ContextSwitch only works in **same domain levels**. Since there is no way for simple cross-domain session ids, the zone switch will be sort of useless most of the time. - The ContextSwitchEvent **ignores** ajax request. If you're requesting data via ajax in a different language / country, no event will be triggered! ### Limitation This event is disabled if the opendxp full page cache feature is enable to prevent session interventions. *** ### Implementation Create a Service: ```yaml # config/services.yaml services: App\EventListener\I18nContextSwitchListener: public: false tags: - { name: kernel.event_subscriber } ``` Create a Listener: ```php 'checkContext' ]; } public function checkContext(ContextSwitchEvent $event): void { if($event->zoneHasSwitched()) { \OpenDxp\Logger::log( sprintf('switch zone: %s => %s', $event->zoneSwitchedFrom(), $event->zoneSwitchedTo() ) ); } if($event->countryHasSwitched()) { \OpenDxp\Logger::log( sprintf('switch country: %s => %s', $event->countrySwitchedFrom(), $event->countrySwitchedTo() ) ); } if($event->languageHasSwitched()) { \OpenDxp\Logger::log( sprintf('switch lang: %s => %s', $event->languageSwitchedFrom(), $event->languageSwitchedTo() ) ); } } } ``` --- ## Canonical Links If you're using hardlinks as country wrapper, there is something you need to know: OpenDXP automatically adds a canonical link to each request header, if a page is wrapped into a hardlink. ### Explanation ```markdown Document: `/en/news` HardLink: `/en-us` (source path would be `/en`) ``` Since the `news` document only exists in `/en`, opendxp adds a canonical link to avoid duplicate content - which is perfectly fine. So if you're going to check the page `/en-us/news`, there should be a canonical relation like this: ```markdown HTTP/2 200 link: ; rel="canonical" ``` But in this case, we want to remove the canonical link because we need country specific content and we'll tell search engines about the references via [href-lang tags](25_HrefLang.md) anyway. So the i18nBundle will remove this canonical tag automatically for you. If you check your http request after installing this bundle, the canonical link will be gone. ### Oh no! **But!** What if you have some hardlinks inside the country site? For Example: ```markdown Document: `/en-us/products/demo` HardLink: `/en-us/special-products` (source path would be `/en-us/products`) ``` Don't worry. Just check the header for `/en-us/special-products/demo`, the canonical relation is still available. The I18nBundle only checks hardlinks on root (`/`), since that's the only place where country based hardlinks makes sense. ```markdown HTTP/2 200 link: ; rel="canonical" ``` --- ## Document Routes ### Generating Routes in current request To create document paths/urls in **current request** via Twig or PHP API you may want to use the `_i18n` parameter builder: #### Twig ```twig {# relative #} {{ dump( i18n_entity_route(opendxp_document(46), {}, false) ) }} {# absolute #} {{ dump( i18n_entity_route(opendxp_document(46), {}, true) ) }} ``` #### PHP ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; public function myAction(Request $request) { $document = \OpenDxp\Model\Document::getById(20); $parameters = RouteParameterBuilder::buildForEntity($document); return $this->urlGenerator->generate('', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); } ``` ### Generating Routes in CLI To create document paths/urls in **headless** context: #### PHP ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; protected function execute(InputInterface $input, OutputInterface $output): int { $document = \OpenDxp\Model\Document::getById(20); $parameters = RouteParameterBuilder::buildForEntity($document); return $this->urlGenerator->generate('', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); } ``` --- ## Static Routes The I18nBundle will help you to create translatable static routes and will also help you to generate valid alternate links. ### Generating Routes in current request To create static route paths/urls in **current request** via Twig or PHP API you may want to use the `_i18n` parameter builder: #### Twig ```twig {# relative [by static route name] #} {{ dump( i18n_static_route('my_static_route', { news: 'my-attribute' }, true) ) }} {# absolute [by static route name] #} {{ dump( i18n_static_route('my_static_route', { news: 'my-attribute' }, true) ) }} {# relative [object with link generator] #} {{ dump( i18n_entity_route(opendxp_object(20), {}, false) ) }} {# absolute [object with link generator] #} {{ dump( i18n_entity_route(opendxp_object(20), {}, true) ) }} ``` #### PHP ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; public function myAction(Request $request) { // set object $object = \OpenDxp\Model\DataObject::getById(20); $parameters = RouteParameterBuilder::buildForEntity($object); $linkGeneratorStaticRoute = $this->urlGenerator->generate('', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); $parameters = RouteParameterBuilder::buildForStaticRoute( [ 'news' => 'my-attribute' ] ); $instantStaticRoute = $this->urlGenerator->generate('my_static_route', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); } ``` ### Generating Routes in CLI To create static route paths/urls in **headless** context: #### PHP ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; protected function execute(InputInterface $input, OutputInterface $output): int { $object = \OpenDxp\Model\DataObject::getById(20); $parameters = RouteParameterBuilder::buildForEntity( $object, [ '_locale' => 'en' ], [ 'site' => Site::getByDomain('test-domain1.test') ] ); $linkGeneratorStaticRoute = $this->urlGenerator->generate('', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); $parameters = RouteParameterBuilder::buildForStaticRoute( [ '_locale' => 'en', 'news' => 'my-attribute' ], [ 'site' => Site::getByDomain('test-domain1.test') ] ); $instantStaticRoute = $this->urlGenerator->generate('my_static_route', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); return 0; } ``` ### Translatable Fragments Creating translatable static routes are quite a challenge in opendxp. We'll show you how to create them based on our [OpenDXP News Bundle](https://github.com/open-dxp/news-bundle). #### Routing First you need to create a valid route. | Pattern | Reverse | |---------|-------------| | `/([a-zA-Z0-9-_]*)\/(?:news\|artikel)\/(.*?)$/` | `/{%_locale}/@news/%entry` | This static route allows structures like: - `domain.com/en-us/news/my-news` - `domain.com/en_US/news/my-news` - `domain.com/news/my-news` - `domain.com/artikel/mein-neuer-artikel` **Important:** This function is only available if you're having a `%_locale` element in your reverse section. Without it, it can't get translated! #### Translation Pattern In the reverse field you may have recognized the `@news` element. This element will get translated during the url generation. Please be sure that all translation keys are also available in the pattern section (`(?:news\|artikel|xy)` for example) Now we'll add some configuration to translate this fragment: ```yaml # config/packages/i18n.yaml opendxp_i18n: locale_adapter: system translations: - key: 'news' values: de: 'artikel' de_CH: 'artikel' en: 'news' en_AU: 'news' fr: 'nouvelles' # example static route opendxp: staticroutes: definitions: 60f02a5d-eb8f-4fb2-859a-0a3c77b472f9: name: my_static_route pattern: '/([a-zA-Z0-9-_]*)\/(?:%i18n.route.translations.news%)\/(.*?)$/' ## returns (artikel|news|nouvelles) reverse: '/{%%_locale}/@news/%%entry' controller: App\Controller\DefaultController::staticRouteAction variables: '_locale,entry' defaults: null siteId: null methods: null priority: 1 creationDate: 1634472684 modificationDate: 1634472684 ``` > **Info:** Why not using the default opendxp translation service you may asking? We also thought about that. > The reason is: It's quite dangerous to add routing translations to the backend since they could get changed by customers / translation services very easily which could lead to serious SEO problems. ### Optional Locale in Url The I18nBundle allows you to have domains without a locale fragment in url. For Example: - `domain.com/about-us` - `domain.com/news` To achieve that you just set the language property to the `domain.com` document which is also a opendxp site. That was easy! Now we need to check the static routes again - because the pattern always requires the locale part. OpenDXP allows [optional placeholders](https://docs.opendxp.io/docs/core-framework/MVC/Routing_and_URLs/Custom_Routes#building-urls-based-on-custom-routes) so instead of `%_locale` just add `{%_locale}` to your reverse element. If no locale has been found in your request url the fragment now gets excluded. ### Alternate Links Generator Then need to register an alternate listener and its corresponding service. ```html ``` ```yaml App\EventListener\I18nRoutesAlternateListener: autowire: true tags: - { name: kernel.event_subscriber } ``` ```php 'checkStaticRouteAlternate' ]; } public function checkStaticRouteAlternate(AlternateDynamicRouteEvent $event): void { // be careful here! Alternate requests are able to resolve two states: // I. non-headless: generate alternate links for a given request (main request) which will pass the request attributes // => you'll find your mapped data in $event->getCurrentRouteAttributes() // II. headless: requested by a standalone zone entity which passes will pass route parameters // => you'll find your mapped data in $event->getCurrentRouteParameters() $attributes = $event->isCurrentRouteHeadless() ? $event->getCurrentRouteParameters() : $event->getCurrentRouteAttributes(); // depending on given route, you may want to build different alternate route items if($event->getCurrentRouteName() !== 'test_route') { return; } $entryId = $attributes->get('entry'); $news = DataObject\NewsEntry::getByLocalizedfields('detailUrl', $entryId, $event->getCurrentLocale(), ['limit' => 1]); if (!$news instanceof DataObject\NewsEntry) { return; } $locale = $attributes->get('_locale'); foreach ($event->getAlternateRouteItems() as $alternateRouteItem) { $newsName = $news->getName($locale); if (empty($newsName)) { continue; } // Strategy I. (recommended) ############################ // Use link generator, only pass the object. // ###################################################### $alternateRouteItem->setEntity($news); // Strategy II. ######################################### // Default static route generation (no link generator) // ###################################################### //set the static route name (in this case it depends on the entry type. $alternateRouteItem->setRouteName($news->getEntryType() === 'news' ? 'news_detail' : 'blog_detail'); $alternateRouteItem->getRouteParametersBag()->add([ 'entry' => $news->getDetailUrl($locale) ]); } } } ``` ### Naming Convention in Country Context The static route configuration above will generate the locale fragment based on the `%_locale` element. So your i18n urls should look like this, otherwise symfony will not recognize the locale: - `www.domain.com/de/artikel/mein-artikel` - `www.domain.com/de_CH/artikel/mein-artikel` - `www.domain.com/en_US/news/my-news` This looks quite ugly. We want some nice looking urls: - `www.domain.com/de/artikel/mein-artikel` - `www.domain.com/de-ch/artikel/mein-artikel` - `www.domain.com/en-us/news/my-news` Yea - that's also possible. Just create your [country element](27_Countries.md) like described and set the document key to `en-us` instead of `en_US` for example. This Bundle will automatically transform your static routes locale fragment into valid ones. > **Note:** Of course it's still possible to use iso code formatted url structures if you really want to do that. :) --- ## Symfony Routes #### Routing First you need to create a valid route. Read more about the symfony route definitions [here](./1_I18n.md#symfony-routes). ```yaml # config/packages/i18n.yaml opendxp_i18n: translations: - key: 'mySymfonyRouteKey' values: de: 'meine-symfony-route' en: 'my-symfony-route' ``` ```yaml # config/routes.yaml i18n_symfony_route: path: /{_locale}/i18n/{matching_route_key} controller: App\Controller\DefaultController::symfonyRouteAction defaults: _i18n: translation_keys: matching_route_key: mySymfonyRouteKey requirements: matching_route_key: '(%i18n.route.translations.mySymfonyRouteKey%)' ## returns (meine-symfony-route|my-symfony-route) ``` ### Generating Routes in current request To create symfony paths/urls in **current request** via Twig or PHP API you may want to use the `_i18n` parameter builder: #### Twig ```twig {# relative #} {{ dump( i18n_symfony_route('i18n_symfony_route', {foo: bar}, false) ) }} {# absolute #} {{ dump( i18n_symfony_route('i18n_symfony_route', {foo: bar}, true) ) }} ``` #### PHP ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; public function myAction(Request $request) { $parameters = RouteParameterBuilder::buildForSymfonyRoute( [ 'foo' => 'bar' ] ); $symfonyRoute = $this->urlGenerator->generate('i18n_symfony_route', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); } ``` ### Generating Routes in CLI To create symfony paths/urls in **headless** context: #### PHP ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; protected function execute(InputInterface $input, OutputInterface $output): int { $parameters = RouteParameterBuilder::buildForSymfonyRoute( [ 'foo' => 'bar' ], [ 'site' => Site::getByDomain('test-domain1.test') ] ); $symfonyRoute = $this->urlGenerator->generate('i18n_symfony_route', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); return 0; } ``` ### Alternate Links Then need to register an alternate listener and its corresponding service. ```yaml App\EventListener\I18nRoutesAlternateListener: autowire: true tags: - { name: kernel.event_subscriber } ``` ```php 'checkSymfonyRouteAlternate', ]; } public function checkSymfonyRouteAlternate(AlternateDynamicRouteEvent $event): void { if($event->getCurrentRouteName() !== 'i18n_symfony_route') { return; } foreach ($event->getAlternateRouteItems() as $alternateRouteItem) { $alternateRouteItem->setRouteName('i18n_symfony_route'); } } } ``` --- ## Data Object Routes OpenDXP routes a request to a data object when the path matches a URL slug field of the object. The I18nBundle builds the hreflang tags and the language links of such a page from the slugs of the object. Nothing needs to be configured. Like a document, a slug needs a document with a `language` property above its path. ### Hreflang Each language of the zone gets the slug of the object in that language. The slug of the site wins over the fallback slug. A language without a slug of its own gets no hreflang tag, also when it falls back to another language. | Language | Slug | Hreflang | |----------|---------------------|----------------------------------------| | en | `/en/news/harbour` | `https://example.com/en/news/harbour` | | de | `/de/beitrag/hafen` | `https://example.com/de/beitrag/hafen` | A slug field that is not localized gives every language the same slug. Only a slug field of the object or of its localized fields counts. A slug in a field collection or an object brick gets no hreflang tag. ### Generating Routes `RouteParameterBuilder::buildForEntity()` links a data object through its slug. The Twig functions `i18n_entity_route` and `i18n_create_context_by_entity` do the same. This applies when the class has a URL slug field and no link generator that implements `I18nLinkGeneratorInterface`. An object with such a link generator keeps its [static route](91_StaticRoutes.md). ```php use OpenDxp\Bundle\I18nBundle\Builder\RouteParameterBuilder; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; $parameters = RouteParameterBuilder::buildForEntity($object, ['_locale' => 'de'], ['site' => $site]); $url = $this->urlGenerator->generate('', $parameters, UrlGeneratorInterface::ABSOLUTE_URL); ``` Name the field in the context key `urlSlugField` when the class has several URL slug fields. ### Slug Generator A slug generator of a `URL slug field` builds the prefix of a slug. The language tree and the route translations of the prefix depend on the zone. `UrlSlugPrefixHelper` resolves both for the language and the site the generator is asked for. The rest of the pattern stays with the generator. | Method | Returns | |-------------------------|--------------------------------------------------------------------------------------------------------| | `findLocaleUrlFragment` | The key of the language tree, for example `de-ch`. `null` when the site document carries the language. | | `translateRouteKey` | The [route translation](91_StaticRoutes.md) of a key in the zone. | ```php use OpenDxp\Bundle\I18nBundle\Helper\UrlSlugPrefixHelper; use OpenDxp\Model\DataObject\ClassDefinition\UrlSlugContext; use OpenDxp\Model\DataObject\ClassDefinition\UrlSlugGeneratorInterface; use Symfony\Component\String\Slugger\AsciiSlugger; final readonly class ProductSlugGenerator implements UrlSlugGeneratorInterface { public function __construct(private UrlSlugPrefixHelper $urlSlugPrefixHelper) { } public function getPrefix(UrlSlugContext $context): string { $fragments = [ $this->urlSlugPrefixHelper->findLocaleUrlFragment($context), $this->urlSlugPrefixHelper->translateRouteKey('product', $context), ]; return '/' . implode('/', array_filter($fragments)); } public function formatSlug(string $text, UrlSlugContext $context): string { return (new AsciiSlugger($context->language))->slug($text)->lower()->toString(); } public function getDefaultSlug(UrlSlugContext $context): ?string { return $context->object->get('name', $context->language); } } ``` The prefix needs a language, so the slug field has to be localized. #### Sites and Languages A slug field offers a language only on the sites that have it. With zones, a site has the languages of its zone. A language that no site has gets no slug. #### Fallback Slug The fallback slug belongs to no site, so the helper asks the sites of the language. Usually they all give the same prefix. When they differ, name the zone that gives the fallback slug its prefix: ```yaml opendxp_i18n: fallback_slug_zone: shop ``` A site with another prefix then gets a slug of its own. Without this setting, the slug field shows an error. --- ## Changelog(I18n) ### 1.2.3 - [NEW FEATURE] Mate skill `mate-i18n` explains what a new language needs. See [Development Tools](docs/130_DevelopmentTools.md) - [NEW FEATURE] Mate tool `i18n_zones` shows the zones, the sites with their language pages and the missing route translations. See [Development Tools](docs/130_DevelopmentTools.md) - [ENHANCEMENT] `I18nContextManager` builds the zone of a site or a configured zone without a request. See [Zone without a Request](docs/21_I18nContext.md#zone-without-a-request) - [BUGFIX] A route key translated in a zone wins over the global translation, in routes and in slug prefixes - [BUGFIX] `%i18n.route.translations.%` matches the translations of every zone ### 1.2.2 - [BUGFIX] The core object preview shows the selected site, also when zones are configured - [BUGFIX] A stored slug of a language that the zone of the site does not have returns 404 - [CHORE] Require `open-dxp/opendxp` 1.5.2 or newer ### 1.2.1 - [ENHANCEMENT] Data objects with a URL slug get hreflang tags and language links. See [Data Object Routes](docs/93_DataObjectRoutes.md) - [ENHANCEMENT] A slug field offers a language only on the sites that have it - [ENHANCEMENT] `UrlSlugPrefixHelper` gives a slug generator the language tree and the route translations of the zone. See [Slug Generator](docs/93_DataObjectRoutes.md#slug-generator) - [ENHANCEMENT] `fallback_slug_zone` names the zone that gives the fallback slug its prefix. See [Fallback Slug](docs/93_DataObjectRoutes.md#fallback-slug) - [ENHANCEMENT] A zone that has a language on several pages throws `AmbiguousZoneSiteException`. It extends `ZoneSiteNotFoundException`, which is no longer final - [CHORE] Require `open-dxp/opendxp` ^1.5.1 ### 1.2.0 - [BUGFIX] A redirect of a site with priority 99 now sends visitors to the language version of its `{i18n_localized_target_page}` target. The redirect check runs after the core resolved the site. - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.1.5 - [ENHANCEMENT] Add `RemoteRouteModifier` and support for `REMOTE_ROUTE` type ### 1.1.4 - [BUGFIX] Fixed uninitialized `ZoneSite::$opendxpSite` after deserialization ### 1.1.3 - [ENHANCEMENT] PHP 8.5 Support added ### 1.1.2 - [ENHANCEMENT] Override language and country detection via events. [Docs](docs/11_UserDetectionEvents.md) ### 1.1.1 - [BUGFIX] Fixed country guess if multiple proxy servers ### 1.1.0 - [DEPRECATION] `opendxp_i18n.zones..domains` is deprecated and will be removed in 2.0. Assign sites to zones via the OpenDXP admin site settings instead. See [Zone Definitions](docs/20_Zones.md) for details. ### 1.0.1 - [CHORE] Update branding names [#4](https://github.com/open-dxp/i18n-bundle/pull/4) - [CHORE] Replace references to "Pimcore" with "OpenDXP" across docs and code examples [#3](https://github.com/open-dxp/i18n-bundle/pull/3) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix doc paths [#2](https://github.com/open-dxp/i18n-bundle/pull/2) - [CHORE] Fix Tests [#1](https://github.com/open-dxp/i18n-bundle/pull/1) --- ## Migrating to OpenDXP(I18n) ### Migrating from `dachcom-digital/i18n` to `open-dxp/i18n-bundle` 1. Replace `dachcom-digital/i18n` with `open-dxp/i18n-bundle` in your `composer.json`. 2. Replace the namespace `I18nBundle\` with `OpenDxp\Bundle\I18nBundle\`. 3. Replace `I18nBundle\I18nBundle` with `OpenDxp\Bundle\I18nBundle\OpenDxpI18nBundle` in `config/bundles.php`. 4. Rename the configuration node `i18n` to `opendxp_i18n`. --- ## I18n Bundle ### Introduction OpenDXP already comes with some great features to build internationalized websites. But there are some gaps we have to handle by ourselves: search engine guidelines, geo based redirects, dynamic link handling for internal documents and of course: full qualified URLs for and in every context. This bundle helps you to master this challenges and gives you the freedom to elaborate complex URL building and (country) based localization strategies. **Please read the [I18n overview page](./docs/1_I18n.md) before starting!** #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `^7.4` | 2025 | Feature Branch | 1.x | #### Installation ```json "require" : { "open-dxp/i18n-bundle" : "~1.1.0" } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\I18nBundle\OpenDxpI18nBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpI18nBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\I18nBundle'` ### Features - Generate fully qualified URLs in any context with symfony's default router - Geo redirects (read more about the redirector adapter [here](docs/51_RedirectorAdapter.md)) - Thanks to the hardlink element, you can create copies of webpages with additional country information without adding and maintaining duplicate content - Manage [href-lang](docs/25_HrefLang.md) tags - Domain mapping (`domain.com`) and/or language slug (`/en`) strategies - [front page mapping](docs/30_FrontPageMapping.md) for hardlink trees #### Before you start When using this bundle, you should: - **not** using any router but the default `RouterInterface` object. - **not** using `opendxp_url` or `$staticRoute->assemble()` but using the default `RouterInterface` instead - extend your `LinkGeneratorInterface` objects with the `I18nLinkGeneratorInterface` and adjust dem accordingly - **read** the [How I18nBundle works](./docs/1_I18n.md) section #### Preparation - If you're using `system` as your `locale_adapter`, which is the default, you need to enable all required locales in opendxp system settings - Always be sure that every document translation is connected via the [localization tool](https://www.opendxp.io/docs/5.0.0/Multi_Language_i18n/Localize_your_Documents.html). - If you're using the country detection, you need a valid maxmind geo ip [data provider](docs/10_GeoControl.md) ### Further Information - [I18n Overview Page](./docs/1_I18n.md): Learn all about the i18n principals. - [Geo IP/Control](docs/10_GeoControl.md): Enable GeoIP Data Provider. - [User Detection Events](docs/11_UserDetectionEvents.md): Override language and country detection via events. - [Zone Definitions](docs/20_Zones.md): Learn more about i18n zone definitions and how to manage them. - [Custom I18n Context Look-Up](docs/21_I18nContext.md) - [Href-Lang](docs/25_HrefLang.md): Find out more about the href-lang tag generator. - [Language Configuration](docs/26_Languages.md): Configure languages. - [Country Configuration](docs/27_Countries.md): Configure countries. - Route and Alternate Links Generation - [Document Routes](docs/90_DocumentRoutes.md): Build document routes - [Static Routes](docs/91_StaticRoutes.md): Build translatable static routes and implement href-lang tags. - [Symfony Route](docs/92_SymfonyRoutes.md): Build translatable symfony routes and implement href-lang tags. - [Data Object Routes](docs/93_DataObjectRoutes.md): Implement hreflang tags for data objects with a URL slug field. - [Front Page Mapping](docs/30_FrontPageMapping.md): Learn how to map a custom front page. - [Localized Error Documents](docs/40_LocaleErrorDocument.md): Learn how to create localized error documents. - [Custom Locale Adapter](docs/50_CustomLocaleAdapter.md): Learn how to create a custom locale adapter. - [Redirector Adapter](docs/51_RedirectorAdapter.md): Learn more about redirector adapter and how to implement a custom one. - [OpenDXP Redirects with I18n](docs/52_OpenDXPRedirects.md): Learn how to create localized opendxp redirects. - [Code Examples](docs/60_CodeExamples.md): See some examples. - [Context Switch Event](docs/70_ContextSwitch.md): Detect zone/language/country switches. - [Canonical Links](docs/80_CanonicalLinks.md): Canonical links in hardlinks. - [Navigation Caching](docs/110_NavigationCaching.md): Cache your navigation right! - [Cookie Settings](docs/120_CookieSettings.md): Change Symfony default cookie settings. - [Development Tools](docs/130_DevelopmentTools.md): Let an AI agent read the zones of the installation. ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Setup(Jobs) After you have enabled this Bundle, there are some global steps to define. #### I. Data Class If you don't have any opendxp data object to manage your jobs you need to create it first. After that, you need to tell JobsBundle about it: ```yaml # config/packages/jobs.yaml jobs: data_class: MyJobDataClass ``` #### II. Data Class Context Field Add the "Jobs Connector Context" field to your data class. Open the class editor, choose `Add Data Component`, then the group `Jobs` and the field `Jobs Connector Context`. It would be good practice if it's placed in a dedicated tab. Name it (Field "name") `jobConnectorContext`. You can check the Health state by visiting the Jobs Menu `"Settings"` => `"Jobs Configuration"`. The panel shows `Data Class Configuration: Ready.` when your data class has the field. Otherwise it shows `Not Ready.` and names the class that needs the "ConnectorContext" field. #### III. Define Feed Host Some connectors require an interface from which they can fetch the data. For certain connectors, the path even has to be submitted first (Like Facebook). This forces us to define a global feed host. ```yaml # config/packages/jobs.yaml jobs: data_class: MyJobDataClass feed_host: 'http://www.my-company.com' ``` There can be only one host per instance. But no worries, you're still able to publish jobs for multisites by using the context definitions, which we gonna checkout next. #### IV. Context Definitions Context definitions determine which jobs should get published on which portal with a given `locale` and `host`. Since an object can live in multiple ways, we need to make things certain. For Example facebook does not have any possibilities to publish jobs in multiple locales. But within the google context it's possible for sure. The `Context Definitions` list in the `Jobs Configuration` panel has the columns `Id`, `Locale` and `Host`. Click on the `Add` button to create your first Context Definition: | Name | Description | |----------|------------------------------------------------------------------------| | `Host` | Define your host. This is required to generate absolute links | | `Locale` | Set a locale. The Job Object should get transformed within this locale | The link generator of your job class builds the absolute link of each job from these two values: ![Context definitions feeding the link generator that builds the job URLs](./img/jobs_new_context_definition.png) You can add as many Context Definitions as you want. However, please note that some Connectors do not allow multiple definitions (Like Facebook). #### V. Link Generator Your Job Object needs a valid Link Generator. If you already have created a Link Generator make sure that you're respecting the host value. > [!NOTE] > If you're using the I18n Bundle, you don't have to build such a complex link generator. > JobsBundle will automatically send all required data to the link generator instead. A Link Generator could look like this: ```php getContextDefinition(); } $mainRequest = \OpenDxp::getContainer()->get('request_stack')->getMainRequest(); $baseLocale = isset($params['_locale']) ? $params['_locale'] : $mainRequest->getLocale(); $baseHost = isset($params['host']) ? $params['host'] : null; $locale = $connectorContextConfig !== null ? $connectorContextConfig->getLocale() : $baseLocale; $host = $connectorContextConfig !== null ? $connectorContextConfig->getHost() : $baseHost; $path = $staticRoute->assemble(['object_id' => $object->getId(), '_locale' => $locale]); if ($host !== null) { return sprintf('%s%s', $host, $path); } return $path; } } ``` #### VI. The Connector Configuration This is the final step: Set up your Connectors. Each connector has its own configuration and strategies. Lets checkout the [Connector](./10_Connectors.md) Guide to learn how to use and install them. *** ### Available Connector - [Google For Jobs](./Connectors/01_GoogleForJobs.md) - [Facebook Jobs](./Connectors/02_FacebookJobs.md) --- ## Connectors ![Connector stages Install, Enable and Connect](./img/jobs_connector_stages.png) Every connector has at least two stages: `Install` and `Enabled`. ### Installation After pressing the Install button, the JobsBundle will generate a Database entry, a so called "Connector Engine". It will provide a unique Token and optionally a configuration Class (Depends on Connector) > **Warning:** If you want to uninstall a connector, all related data will be lost! ### Enabling/Disabling Enable or disable a connector. There is no data loss if a connector gets disabled. ### Connect Not every Connector does have Connection Feature. The [Facebook Connector](./Connectors/02_FacebookJobs.md) for example, requires a valid access token which will be created, after you hit this button. *** ### Setup Connector Let's setup the [Google Connector](./Connectors/01_GoogleForJobs.md) to complete your configuration. *** ### Available Connector - [Google For Jobs](./Connectors/01_GoogleForJobs.md) - [Facebook Jobs](./Connectors/02_FacebookJobs.md) --- ## Feeds ![Feed URL built from feed host, connector name, connector token and feed ID](./img/jobs_feeds.png) Some Connectors (Facebook for example) require a valid Feed-Url. Each connector is allowed to generated them within its own logic but the will end up with a structured route: ```bash GET [FEED_HOST]/jobs/[CONNECTOR_NAME]/[CONNECTOR_TOKEN]/feed/[FEED_ID] ``` Click on `Add Feed` to start the feed generating process. --- ## Object Context After you have created some [context definitions](./00_Setup.md#iv-context-definitions) you're ready to setup your Job object. The `Jobs Connector Context` field of your Job object has one tab per connector. Each tab lists the context definitions with the columns `Id`, `Locale`, `Host` and `Active`. Enable a context by selecting the "Active" Checkbox. --- ## Available Items Resolver Items Resolver are required to determinate items in a unknown context. After resolving them, they need to return an array with `ResolvedItem`. ### Dynamic Route Request Resolver | Name | Description | |-----------------------------|-----------------------------------------------------------------------------------------| | `route_name` | Determinates, on which route the job object is available | | `route_request_identifier` | Which request fragment owns the object identifier (For Example `/?id=123` would be `id` | | `route_object_identifier` | Determinates, on which object attribute the request identifier should get applied on | | `is_localized_field` | If true, the object fetcher will look up with `getByLocalizedfields` | | `must_match_request_locale` | If true, the current request locale must match with the context definition locale | #### Usage ````yaml jobs: available_connectors: - connector_name: google connector_items_resolver: - type: dynamic_route_request config: route_namee: 'my_object_route' route_request_identifier: 'object_id' route_object_identifier: 'id' must_match_request_locale: true ```` ### OpenDXP Object Resolver No Configuration available. #### Usage ````yaml jobs: available_connectors: - connector_name: google connector_items_resolver: - type: opendxp_object ```` ### Seo Queue Resolver No Configuration available. #### Usage ````yaml jobs: available_connectors: - connector_name: google connector_items_resolver: - type: seo_queue ```` ### Feed Resolver No Configuration available. #### Usage ````yaml jobs: available_connectors: - connector_name: facebook connector_items_resolver: - type: feed ```` ### Custom Items Resolver If you're planing to create your own connector (or override an existing one), checkout this [guide](21_CustomItemsResolver.md). --- ## Custom Items Resolver > **Warning**: Creating a custom Item Resolver is only required if you're planning to create your custom connector. ```yaml services: App\Context\Resolver\MyCustomResolverResolver: tags: - { name: jobs.context.items_resolver, identifier: my_custom_resolver } ``` #### Service ```php connectorContextManager = $connectorContextManager; } public function setEnvironment(EnvironmentServiceInterface $environmentService): void { $this->environmentService = $environmentService; } public function setConfiguration(array $resolverConfiguration): void { $this->configuration = $resolverConfiguration; } public function configureContextParameter(OptionsResolver $resolver): void { $resolver->setDefaults([ 'my_option' => null ]); $resolver->setRequired(['my_option']); } public function resolve(ConnectorDefinitionInterface $connectorDefinition, array $contextParameter): array { // all context items matching with "my_connector". $connectorContextItems = $this->connectorContextManager->getForConnectorEngine($connectorDefinition->getConnectorEngine()->getId()); $resolvedItems = []; foreach ($connectorContextItems as $contextItem) { /** @var DataObject\Concrete $object */ $object = DataObject::getById($contextItem->getObjectId()); $resolvedItems[] = new ResolvedItem($contextItem, $object, []); } return $resolvedItems; } } ``` ### Usage ```yaml jobs: data_class: MyJobClass available_connectors: - connector_name: my_connector connector_items_resolver: - type: my_custom_resolver config: my_option: test ``` --- ## Logging Jobs Bundle comes with a dedicated log table. The `Logs` panel of the `Jobs Connector Context` field shows the columns `Type`, `Message` and `Date` for each connector. ### Clean Up Task Logs will be removed after `30 days`. Change the expiration via configuration: ```yaml jobs: log_expiration_days: 10 ``` ### Custom Clean-Up #### Object Every Log-panel comes with a "Cleanup" button. It will remove logs bounded to given connector **and** object only! #### Global Flush There is also a global log flush workflow. Go to the global jobs config panel and hit the "Flush all logs" button at the left top corner. > Be aware this will truncate the logs tables and can't be undone! ### Add Log ```php $log = $this->logManager->createNewForConnector('your_connnector'); $log->setType('success'); $log->setMessage('My Message'); $log->setObjectId(667); $this->logManager->update($log); ``` --- ## Changelog(Jobs) ### 1.1.1 - [BUGFIX] Facebook connector label reads "The URL of your organization's website" - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix tests & workflows [#1](https://github.com/open-dxp/jobs-bundle/pull/1) --- ## Google For Jobs Connector This Connector allows you to push your Job Changes to the Google Index API in realtime also generating a schema block the detail page of your job object. Before you start be sure you've checked out the [Setup Instructions](../00_Setup.md). ### Requirements First things first. To use this connector, you have to install some dependencies: - [open-dxp/advanced-seo-bundle](https://github.com/open-dxp/advanced-seo-bundle) - [open-dxp/schema-bundle](https://github.com/open-dxp/schema-bundle) ### Dependencies Configuration Make sure the `opendxp_element_watcher.enabled: true` for the AdvancedSeoBundle is enabled. Otherwise no object will be transmitted to the Google Index API after modification/deletion. ### Example Configuration This is a example Configuration. Each Connector needs some `Items Resolver` (Find the right object for the right context) and a single `Item Transformer` (Transform your object into a valid schema block in this case). ```yaml jobs: data_class: Job available_connectors: - connector_name: google connector_item_transformer: App\Transformer\GoogleItemTransformer connector_items_resolver: - type: seo_queue - type: opendxp_object ``` ### Item Resolver The Google For Jobs Workflow is a tricky one. We need multiple resolver because there are two endpoints within its workflow. The first one (`seo_queue`) needs to submit the object (Multiple times, based selected context definitions) to the google index api. The second one (`opendxp_object`) on the other hand only allows a single object - but may has to match with the given locale / host. Some items resolver does have some configurable options. Read more about all items resolver [here](../20_AvailableItemsResolver.md). ### Item Transformer In our example we have a service class called `App\Transformer\GoogleItemTransformer`. Every Item Transformer has its own logic as you can see here: ```php getSubject(); /** @var Graph $graph */ $graph = $itemTransformerDefinition->getGraph(); $contextDefinition = $item->getContextItem()->getContextDefinition(); $locale = $contextDefinition->getLocale(); $graph ->jobPosting() ->datePosted(Carbon::createFromTimestamp($subject->getCreationDate())) ->description($subject->getName()) ->jobLocation($this->getJobLocation($subject)) ->title($subject->getName()) ->employmentType($subject->EmplymentType()); } protected function getJobLocation(MyJobClass $job): Place { return Schema::place() ->name('Bregenz') ->address(Schema::postalAddress() ->addressCountry('Austria') ->addressRegion('Vorarlberg') ->addressLocality('Bregenz') ->postalCode('6900') ); } } ``` ### Done! You're done. Go to your job object and enable all required [context definitions](../12_ObjectContext.md). --- ## Facebook Jobs Connector **Warning**: The Facebook Jobs XML Feed is still experimental! This Connector allows you to publish your Jobs on a xml output feed which will be parsed from the facebook company. To use this connector you need to provide fully configured Facebook App! Before you start be sure you've checked out the [Setup Instructions](../00_Setup.md). ### Requirements First things first. To use this connector, you have to install the [league/oauth2-facebook](https://github.com/thephpleague/oauth2-facebook): ```bash composer require league/oauth2-facebook:^2.0 ``` ### Example Configuration Each Connector needs some `Items Resolver` (Find the right object for the right context) and a single `Item Transformer` (Transform your object into a valid Facebook xml block in this case [full feed specification](https://developers.facebook.com/docs/pages/jobs-xml/getting-started#company-info)). ```yaml jobs: data_class: Job available_connectors: - connector_name: facebook connector_item_transformer: App\Transformer\FacebookItemTransformer connector_items_resolver: - type: feed ``` ### Connector Configuration Now head back to the backend (`Settings` => `Jobs Configuration`) and checkout the facebook tab. - Click on `Install` - Click on `Enable` - Before you hit the `Connect` button, you need to fill you out the Connector Configuration. After that, click "Save". - Click `Connect` The `Connector Configuration` has these required fields: | Label | Description | |-------------------------------------------|-----------------------------------| | `App ID` | The id of your Facebook App | | `App Secret` | The secret of your Facebook App | | `The name of your organization` | Name of the publisher in the feed | | `The URL of your organization's website` | URL of the publisher in the feed | | `Photo Url` | URL of the photo of your company | | `Data Policy Url` | URL of your data policy | ### Connection The `Facebook Connect Service` dialog guides you through the facebook token generation. After hitting the "Connect" button, a new window will open. After a access token has been successfully generated, you can close the window. Click on "Check & Apply Connection" to finalize the connection state. ### Feed Generator This Connector requires a fully registered feed. Click on "Add Feed" and start the generation process. First, it will generate a `Recruiting Manager Id` which is required by facebook. If this step was successful, a second call will generate the feed itself. If this was successful too, your connector is fully configured and ready to use. ### Item Transformer In our example we have a service class called `App\Transformer\FacebookItemTransformer`. Every Item Transformer has its own logic as you can see here: ```php getSubject(); $contextDefinition = $item->getContextItem()->getContextDefinition(); $locale = $contextDefinition->getLocale(); $itemTransformerDefinition->setTitle($subject->getTitle()); $itemTransformerDefinition->setSalary($subject->getSalary()); } } ``` ### Item Resolver There is only a simple items resolver required since the facebook connector will output its data via a [data feed](../11_Feeds.md). ### Done! You're done. Go to your job object and enable all required [context definitions](../12_ObjectContext.md). --- ## Migrating to OpenDXP(Jobs) ### Migrating from `dachcom-digital/jobs` to `open-dxp/jobs-bundle` 1. Replace `dachcom-digital/jobs` with `open-dxp/jobs-bundle` in your `composer.json`. 2. Replace the namespace `JobsBundle\` with `OpenDxp\Bundle\JobsBundle\`. 3. Replace `JobsBundle\JobsBundle` with `OpenDxp\Bundle\JobsBundle\OpenDxpJobsBundle` in `config/bundles.php`. 4. Rename the configuration node `jobs` to `opendxp_jobs`. --- ## Jobs Bundle This Bundle allows you to synchronise your job offers with various connectors like [facebook jobs](https://developers.facebook.com/docs/pages/jobs-xml) or [google for jobs](https://developers.google.com/search/docs/data-types/job-posting). ![Jobs Bundle flow from the data class through context definitions and a connector to a job portal](./docs/img/jobs_configuration.png) #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 01.2026 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/jobs-bundle" : "~1.0.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\JobsBundle\OpenDxpJobsBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpJobsBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\JobsBundle\Migrations'` ### Usage This Bundle needs some preparation. Please check out the [Setup](docs/00_Setup.md) guide first. ### Further Information - [Setup](docs/00_Setup.md) - [Connectors](./docs/10_Connectors.md) - [Google For Jobs](./docs/Connectors/01_GoogleForJobs.md) - [Facebook Jobs](./docs/Connectors/02_FacebookJobs.md) - [Feeds](docs/11_Feeds.md) - [Object Context](docs/12_ObjectContext.md) - [Available Items Resolver](docs/20_AvailableItemsResolver.md) - [Custom Items Resolver](docs/21_CustomItemsResolver.md) (Expert) - [Logging](docs/22_Logging.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Mailpit) ### 1.2.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [BUGFIX] The Mailpit main menu works without the `SimpleBackendSearchBundle` - [ENHANCEMENT] Removed hardcoded `production` gate. Symfony configuration is the only source of truth - [CHORE] [FOLLOW-UP] The `mail_pit_config` route and `MailpitController` are removed. `config/routing.yaml` is empty 1. Only if your `config/routes.yaml` imports `@OpenDxpMailpitBundle/config/routing.yaml`: remove the import. - [DEPRECATION] `@OpenDxpMailpitBundle/config/routing.yaml`. 2.0 removes the file ### 1.1.1 - [ENHANCEMENT] PHP 8.5 Support added ### 1.1.0 - [NEW FEATURE] The Mailpit URL can now be configured via a Website Setting (`mailpit_uri`) - [NEW FEATURE] The Mailpit URL is now automatically added to the CSP `frame-src` directive. Manual entry in `admin_csp_header` is no longer required. ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Unify test infrastructure across bundles [#1](https://github.com/open-dxp/mailpit-bundle/pull/1) --- ## Migrating to OpenDXP(Mailpit) ### Migrating from `dachcom/pimcore-mailpit:3.x` to `open-dxpr/mailpit-bundle:1.0` * Moved Bundle to new namespace: `OpenDxp\Bundle\MailpitBundle` * Renamed Bundle to `OpenDxpMailpitBundle` * Change top-level config node to `opendxp_mailpit` --- ## Mailpit Bundle This bundle requires [mailpit](https://github.com/axllent/mailpit) #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 2025 | Feature Branch | 1.x | ### Installation #### I. Add Dependency ```json "require": { "open-dxp/mailpit-bundle": "^1.1", } ``` #### II. Add to bundles.php ```php OpenDxp\Bundle\MailpitBundle\OpenDxpMailpitBundle::class => ['all' => true], ``` #### III. Define Mailpit URI The Mailpit URL can be set via bundle config or via a Website Setting — see [General Instructions](./docs/general.md#site-config-website-settings). #### Admin CSP Header The Mailpit URL is automatically added to the CSP `frame-src` directive — see [General Instructions](./docs/general.md#content-security-policy-csp). ### Docs - Installation Guide - [General Instructions](./docs/general.md) - [Hetzner](./docs/hetzner.md) - [nine.ch](./docs/nine.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## General ### General Instruction - Change env variable `MAILER_DSN` to `smtp://127.0.0.1:1025` - Check that the `framework.mailer.transports` config is correct! - Configure bundle according to your needs ```yaml # config/packages/opendxp_mailpit.yaml opendxp_mailpit: enabled: false ``` ```yaml # config/packages/staging/opendxp_mailpit.yaml opendxp_mailpit: enabled: true path: 'https://mailpit.mydomain.ch' # optional, also configurable via website settings ``` ### Site Config (Website Settings) The Mailpit URL can optionally be configured via a OpenDXP **Website Setting** named `mailpit_uri`. If this setting exists and has a value, it takes precedence over the `path` defined in the bundle config. This allows overriding the Mailpit URL per environment or site directly from the OpenDXP Admin UI, without requiring a code or config change. ### Content Security Policy (CSP) The bundle automatically adds the configured Mailpit URL to the `frame-src` directive of the `admin_csp_header`. **No manual entry in the CSP config is required.** This works as long as `admin_csp_header.enabled` is `true` in your OpenDXP Admin Bundle configuration and the bundle is enabled (`mailpit.enabled: true`). --- ## Hetzner ### Installation on Hetzner Demo: http://mailpit.zaunteam.ch/ > Hetzner needs to add a custom virtual host for that, so you must contact hetzner support to achive this. **** #### Prerequisite - Add port `8025` to hetzner port whitelist - Create `mailpit.yourdomain.com` subdomain (you may need to request some dns entries) - Ask hetzner support to append vhost configuration: ```apacheconf #-----------------%<----------------- ProxyPass / http://localhost:8025/ ProxyPassReverse / http://localhost:8025/ RewriteEngine on RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteCond %{HTTP:Connection} upgrade [NC] RewriteRule ^/?(.*) "ws://localhost:8025/$1" [P,L] #----------------->%----------------- ``` *** #### Binary Go to you project bin dir (`/usr/www/users/YOUR_USER/bin`) - `wget https://github.com/axllent/mailpit/releases/download/v1.9.8/mailpit-linux-amd64.tar.gz` - `tar -xvzf mailpit-linux-amd64.tar.gz mailpit` #### Add mailpit to supervisor Go to `~/.config/supervisor` - create a `mailpit.ini` configuration file and add: ```ini [program:mailpit] command=/usr/www/users/YOUR_USER/bin/mailpit user=YOUR_USER numprocs=1 startsecs=0 autostart=true autorestart=true startretries=10 process_name=%(program_name)s_%(process_num)02d ``` - (re)start supervisor service - exec `supervisorctl status` to check if program is running --- ## Nine ### Installation on Nine Demo: http://mailpit.neovac.ch/ > Nine needs a separate virtual host with the `proxy` template to achive this. This can be set up by the DevOps team. **** #### Prerequisite - Create `mailpit.yourdomain.com` subdomain (you may need to request some dns entries) - Create a new virtual host with the `proxy` template: ```shell sudo nine-manage-vhosts virtual-host create mailpit.yourdomain.com --template=proxy_letsencrypt_https_redirect_auth --template-variable=AUTHBASICPATH=/home/www-USER/.htpasswd --template-variable=PROXYPORT=8025 ``` - If not already present, create a `.htpasswd` file with the following command: ```shell htpasswd -c /home/www-USER/.htpasswd dachcom digital ``` > **Important:** Shared Hostings (e.g. dc9, dc11, ...) still need to be evaluated since multiple smtp relays which listen on the same port are not possible. *** #### Binary Go to you project bin dir (`/home/www-USER/bin`) - `wget https://github.com/axllent/mailpit/releases/download/v1.9.8/mailpit-linux-amd64.tar.gz` - `tar -xvzf mailpit-linux-amd64.tar.gz mailpit` #### Add mailpit to systemd Go to `~/.config/systemd/user` - create a `mailpit.service` configuration file and add: ```ini [Unit] Description=Mailpit After=network.target [Service] Type=simple ExecStart=/home/www-USER/bin/mailpit Restart=always RestartSec=5s StartLimitInterval=0 StartLimitBurst=10 [Install] WantedBy=default.target ``` - (re)start systemd service - `systemctl --user daemon-reload` - `systemctl --user enable mailpit` - `systemctl --user start mailpit` - exec `systemctl --user status` to check if program is running --- ## Auth identifier By default, MembersBundle will use the `username` field from your Users entity. If you want to use the `email` field instead, you need to tell it like this: ```yaml opendxp_members: user: auth_identifier: 'email' # can be "username" (default) or "email" ``` ### Auth Identifier only for registration You're able to define if your registration form should only contain the `auth_identifier` field (optional). If `only_auth_identifier_registration` is set to `true` (`false` by default) and `opendxp_members.user.auth_identifier` is set to `email` for example, the registration form type will only show up with `email` and `password` fields. By default `email`, `password` and `password` fields are required for registration form. > Attention! If you're using `username` as only registration field, your user entity won't provide an email address! > Keep that in mind when it comes to confirming users profile! ```yaml opendxp_members: user: only_auth_identifier_registration: true ``` --- ## Restrictions The Restriction Feature is disabled by default. ```yaml opendxp_members: restriction: enabled: true ``` > Note: You need to create some groups before you can enable the restrictions. ### Enable Document Restriction Once activated, you'll see a restriction tab in every document. #### Document Inheritance If your enable the inheritance checkbox, all child objects will inherit the restriction. > If you're adding a new child element to an inheritable document, it will automatically adopt the restriction. ### Enable Object Restriction If you want to restrict object, you need to define them in the members configuration first: ```yaml opendxp_members: restriction: enabled: true allowed_objects: - 'NewsEntry' - 'YourObjectName' ``` Now you should see a restriction tab in all of those defined objects. #### Object Inheritance If your enable the inheritance checkbox, all child objects will inherit the restriction. > If you're adding a new child element to an inheritable object, it will automatically adopt the restriction. ### Asset Restriction After you've activated the restriction globally, you're able to restrict assets. **Important:** Only Assets within the `/restricted-assets` folder are able to be restricted! #### Assets Inheritance Since assets can't have child assets you need to create a folder first. Open the folder, and you'll see the inheritance checkbox. If you activate it, all assets will inherit all the restriction information from this folder. > If you're adding a new asset into an inheritable folder, it will automatically adopt the restriction. #### Public Assets Path Protection Out of the box, Members **can't protect** asset thumbnails of all kinds which are located inside the `/restricted-assets` folder. This can be an issue if you want to show document thumbnails or video thumbnails directly on the webpage. On the other hand, it's also not possible to stream raw video assets in frontend (since the folder itself is protected by htaccess rules). If you want to ensure 100% safe asset processing, you may want to enable the public asset path protection. This feature is disabled by default and requires modifications of your global `.htaccess` file if you want to use it. ```yaml opendxp_members: restriction: enabled: true enable_public_asset_path_protection: true ``` ```apacheconf # add this at the top in public/.htaccess RewriteEngine On RewriteCond %{HTTP_HOST}==%{HTTP_REFERER} !^(.*?)==https?://\1/admin/ [OR] RewriteCond %{HTTP_COOKIE} !^.*opendxp_admin_sid.*$ [NC] RewriteRule ^restricted-assets/.* - [F,L] RewriteRule ^var/.*/restricted-assets(.*) - [F,L] RewriteRule ^cache-buster\-[\d]+/restricted-assets(.*) - [F,L] ``` ### Global Restriction Check Helper To get current restriction information about a document, object or asset, just call the restriction manager: ```php container->get(RestrictionManager::class)->getElementRestrictionStatus($element); //get restriction group ids echo $restriction->getRestrictionGroups(); //get section echo $restriction->getSection(); //get state echo $restriction->getState(); ``` --- ## Class Customization #### Custom classes If you want to use different data object classes, you need to modify the default configuration. Add those lines to your `config/config.yaml`: ```yaml opendxp_members: # for the user class user: adapter: class_name: 'MyCustomer' # default was 'MembersUser' # for the group class group: adapter: class_name: 'MyGroup' # default was 'MembersGroup' # for the sso identity class # only available if you're using the SSO feature sso: adapter: class_name: 'MySsoIdentity' # default was 'SsoIdentity' ``` > **Tip:** Add this to a separate config file. #### Custom object keys You can define a form field (from the registration form) whose value is used to generate the key of the OpenDXP object. ```yaml opendxp_members: user: adapter: object_key_form_field: 'username' # default was 'email' ``` > **Important:** Choose a unique field to prevent naming conflicts within OpenDXP #### Username field > [!NOTE] > Installations created before 1.1.1 have the field `userName`, newer installations use `username`. > A class with the field `userName` keeps working because PHP methods and MySQL columns are case-insensitive. --- ## Restricted Navigation Now - since you have restricted some documents to certain groups, you need to manipulate the opendxp navigation renderer. **Navigation:** Do **not** use the default nav builder extension (`opendxp_build_nav`). Just use the `members_build_nav` to build secure menus. Otherwise, your restricted pages will show up. This twig extension will also handle your navigation cache strategy. ### Usage ```twig {% set nav = members_build_nav({ active: currentDoc, root: documentRootDoc }) %} {{ opendxp_render_nav(nav, 'menu', 'renderMenu', { maxDepth: 2 }) }} ``` #### Page callback parameter The `pageCallback` parameter is 'merged' with the Members bundle restriction access callback, allowing you to set custom data to the navigation document. Note that the `ElementRestriction` argument is also passed on to the callback function. ```twig {% set nav = members_build_nav({ active: document, root: rootPage, pageCallback: navigation_callback() }) %} ``` As you cannot use closures directly within Twig templates, create a function to return one. ```php setCustomSetting('key', $page->getKey()); } }; } } ``` To retrieve the setting in the template: ```twig {{ page.getCustomSetting('key') }} ``` --- ## Restricted Routing The MembersBundle tries to protect your documents by default. For that an event listener will watch every request. 1. If the route is not protected, the restriction will be skipped 2. If the route is protected and the user is not logged in and not allowed to open the page, he will get redirected via the `members_user_security_login` route. 3. If the route is protected and the user is logged in but has not the right privileges, he will get redirected via the `members_user_restriction_refused` route. ### StaticRoute Routing In some cases, objects are bounded to the view. For example a news, blog or a product object. In that case you probably added a static route (www.site.com/news/your-news). Even if the object has a restriction, the view will not notice it and the user would be able to open the view. Because Members cannot detect the related object based on a static route, you need to take care about that. There is simple event listener you need to call: `StaticRouteEvent` #### 1. Service First, create a service in your `config/services.yaml`: ```yaml App\EventListener\MembersStaticRouteListener: tags: - { name: kernel.event_subscriber } ``` #### 2. Listener Second, create an event listener: ```php 'checkStaticRoute' ]; } public function checkStaticRoute(StaticRouteEvent $event): void { $request = $event->getRequest(); if($event->getRouteName() === 'news_detail') { $newsObject = News::getById($request->attributes->get('newsId')); if($newsObject instanceof News) { //bind your object to the event. that's it. $event->setStaticRouteObject($newsObject); } } } } ``` --- ## Restricted Listing Unfortunately it's impossible to inject some global sql additions into document/asset/object listing queries. Because of that, you need to take care about that by yourself. There are two ways to check a element restriction ### 1. Listing Query Injection This is the recommended way. ```php onCreateQueryBuilder(function (QueryBuilder $query) use ($restrictionQuery, $listing) { $restrictionQuery->addRestrictionInjection($query, $listing); }); dump($listing->getObjects()); # Documents $listing = new Model\Document\Listing(); $listing->setLimit(10); $listing->onCreateQueryBuilder(function (QueryBuilder $query) use ($listing, $restrictionQuery) { $restrictionQuery->addRestrictionInjection($query, $listing, 'id'); }); dump($listing->getDocuments()); # Assets $listing = new Model\Asset\Listing(); $listing->setLimit(10); $listing->onCreateQueryBuilder(function (QueryBuilder $query) use ($listing, $restrictionQuery) { $restrictionQuery->addRestrictionInjection($query, $listing, 'id'); }); dump($listing->getAssets()); } ``` ### 2. Statements If you can't or won't modify the sql query, you can use these statements to check the restriction: ```php container->get(RestrictionManager::class)->getElementRestrictionStatus($element); if($restriction->getSection() === RestrictionManager::RESTRICTION_SECTION_ALLOWED) { //allowed! } ``` --- ## Asset Protection #### Single Asset Generate protected asset download urls: ```php restrictionUri = \MembersBundle\Security\RestrictionUri $restrictionUri; //this asset needs to be a protected one! $download = \OpenDxp\Model\Asset::getById(1); $downloadLink = $this->restrictionUri->generateAssetUrl($download); //$downloadLink: domain.com/members/request-data/W3siZiI6NiwicCI6ZmFsc2V9XQ?_hash=... ``` #### Package If you want to get multiple downloads at once, you can use the generateAssetPackageUrl() method. This will create a temporary zip file containing all requested files! >**Important:** Since we need to fetch all assets via stream by flysystem, it is no longer possible to push the zip file to the client on the fly. > Therefor we need to store the archive in `OPENDXP_SYSTEM_TEMP_DIRECTORY` until the file has been downloaded. > > Depending on your system and archive size, this can temporarily consume a lot of space and memory! ```php restrictionUri = \MembersBundle\Security\RestrictionUri $restrictionUri; //these assets need to be protected! $download1 = \OpenDxp\Model\Asset::getById(1); $download2 = \OpenDxp\Model\Asset::getById(2); $packageData = [ ['asset' => $download1], ['asset' => $download2] ]; $downloadLink = $this->restrictionUri->generateAssetPackageUrl($packageData, true); //since the second argument is set to TRUE, the link will only available if the current user is correctly authenticated. //$downloadLink for users with same group restrictions: 'domain.com/members/request-data/W3siZiI6NiwicCI6ZmFsc2V9XQ?_hash=...' //$downloadLink for guest users: '' ``` ### Twig Extension If you want to generate protected urls in twig, use these extensions to generate some: #### Single Asset ```twig {# generate link #} download protected file {# generate protected link only if content is available for current user #} {{ dump(members_generate_asset_url(12, true)) }} ``` #### Package ```twig {# generate link #} download protected package {# generate protected link only if content is available for current user #} {{ dump(members_generate_asset_package_url([12,40], true)) }} ``` > **Note:** Don't worry if you skip the second argument (default is false), since every download link will check for a valid user restriction! --- ## Using Members with the OpenDXP Customer Data Framework The CMF is fully supported by Members. ### About Customer Management Framework The Customer Management Framework (CMF) for OpenDXP adds additional functionality for customer data management, segmentation, personalization and marketing automation. So it allows to aggregate customer data and user profiles, enrich data, link social profiles, build audience segments, trigger events, personalize experience, execute marketing automation and much more. Read more about the CMF [here](https://github.com/open-dxp/customer-data-framework). ### Configuration 1. [Install CMF](https://github.com/open-dxp/customer-data-framework/blob/1.x/doc/02_Installation.md) 2. Install the [Customer Class](https://github.com/open-dxp/customer-data-framework/tree/1.x/install/class_source/optional) 3. Change the parent class of this class to `OpenDxp\Bundle\MembersBundle\Adapter\User\AbstractCustomerUser` 4. Add all the required [members fields](https://github.com/open-dxp/members-bundle#class-installation). 5. Define the class name for the CMF customer (assuming that your class name is called `MembersCustomer`): ```yaml opendxp_customer_management_framework: general: customerOpenDxpClass: MembersCustomer ``` 6. Define the class name for members: ```yaml opendxp_members: user: adapter: class_name: 'MembersCustomer' ``` 7. Install OpenDXP Members --- ## Frontend Routes and Views #### Auth Prefix: `/{_locale}/members` | Route name | Path | View | Methods | |------------------------------|--------------|----------------------|-----------| | members_user_security_login | /login | Auth/login.html.twig | GET, POST | | members_user_security_check | /login_check | -- | POST | | members_user_security_logout | /logout | -- | GET, POST | #### Registration Prefix: `/{_locale}/members/register` | Route name | Path | View | Methods | |---------------------------------------|--------------------|------------------------------------|-----------| | members_user_registration_register | / | Registration/show.html.twig | GET, POST | | members_user_registration_check_email | /check-email | Registration/check_email.html.twig | GET | | members_user_registration_check_admin | /check-admin | Registration/check_admin.html.twig | GET | | members_user_registration_confirm | /confirm/\{token\} | -- | GET | | members_user_registration_confirmed | /confirmed | Registration/confirmed.html.twig | GET | #### Change Password Prefix: `/{_locale}/members/profile` | Route name | Path | View | Methods | |------------------------------|------------------|------------------------------------------|-----------| | members_user_change_password | /change-password | ChangePassword/change_password.html.twig | GET, POST | #### Profile Prefix: `/{_locale}/members/profile` | Route name | Path | View | Methods | |----------------------------------|----------|---------------------------|-----------| | members_user_profile_show | / | Profile/show.html.twig | GET | | members_user_profile_edit | /edit | Profile/edit.html.twig | GET, POST | | members_user_restriction_refused | /refused | Profile/refused.html.twig | GET | #### Resetting Prefix: `/{_locale}/members/resetting` | Route name | Path | View | Methods | |------------------------------------|------------------|---------------------------------|-----------| | members_user_resetting_request | /request | Resetting/request.html.twig | GET | | members_user_resetting_send_email | /send-email | -- | POST | | members_user_resetting_check_email | /check-email | Resetting/check_email.html.twig | GET | | members_user_resetting_reset | /reset/\{token\} | Resetting/reset.html.twig | GET, POST | #### Delete Account Prefix: `/{_locale}/members/profile` | Route name | Path | View | Methods | |-----------------------------|-----------------|----------------------------------------|-----------| | members_user_delete_account | /delete-account | deleteAccount/delete_account.html.twig | GET, POST | --- ## Testing(Members) The bundle ships the classes to test a project with members, under `OpenDxp\Bundle\MembersBundle\Test`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Setup The factories create the classes `MembersUser`, `MembersGroup` and `SsoIdentity` of the project. ### Logging in a member ```php use OpenDxp\Bundle\MembersBundle\Test\Brick\LoginBrick; use OpenDxp\Bundle\MembersBundle\Test\Factory\MembersGroupFactory; use OpenDxp\Bundle\MembersBundle\Test\Factory\MembersUserFactory; use OpenDxp\Bundle\MembersBundle\Test\Frontend\MembersArea; use OpenDxp\Test\Factory\DocumentPageFactory; $sales = MembersGroupFactory::createOne(['name' => 'Sales']); MembersUserFactory::new() ->inGroups($sales) ->withPassword('secret-password') ->create(['username' => 'anna']); $page = DocumentPageFactory::new() ->withBricks('content', LoginBrick::new()->hidingWhenLoggedIn()) ->create(); MembersArea::inLocale('en') ->login() ->logIn('anna', 'secret-password'); ``` ### The login brick `LoginBrick` places the login form on a page or a snippet, through the page and snippet factories of OpenDXP. `hidingWhenLoggedIn()`, `redirectingTo()` and `showingWhenLoggedIn()` set what an editor chooses in the dialog of the brick. ### The pages of the bundle `MembersArea::inLocale('en')` opens the pages the bundle routes to, in one language. Each page is a class that fills in its form by the labels and presses its buttons, the way a member does: | Method | Page | Actions | |--------------------------|------------------------|-----------------------------------------------------------------| | `login()` | `Login` | `logIn()` | | `registration()` | `Registration` | `register()` | | `profile()` | `Profile` | `username()`, `email()` | | `profileEdit()` | `ProfileEdit` | `update()` | | `passwordChange()` | `PasswordChange` | `change()` | | `accountDeletion()` | `AccountDeletion` | `delete()`, `deleteSsoAccount()`, `deleteWithoutConfirmation()` | | `passwordResetRequest()` | `PasswordResetRequest` | `request()` | `loggedInMember()` returns the username of the member who is logged in, or null. `MembersArea::openMailLink()` opens the link of a mail the bundle sends. `PasswordReset` sets the new password on the page that the link in a reset mail opens. `Login` also fills in the form of the login brick on any page. The forms of the bundle expect the English labels of `config/install/translations/frontend.csv`. ### Test API | Factory | Creates | |-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------| | `MembersUserFactory` | A confirmed member, saved through the user manager as a registration does. `unconfirmed()`, `inGroups()`, `withPassword()`, `withoutPassword()`. | | `MembersGroupFactory` | A group. `withRoles()`. | | `SsoIdentityFactory` | A single sign on identity. `forMember()` stores it below the member and adds it to the identities of the member. | --- ## Events(Members) #### members.restriction.staticroute | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESTRICTION_CHECK_STATICROUTE` | | **name** | `members.restriction.staticroute` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\StaticRouteEvent` | | **description** | The RESTRICTION_CHECK_STATICROUTE event occurs when a frontend request is in a staticroute context | *** #### members.entity.restriction.create | Type | Reference | |:----------------|:--------------------------------------------------------------------------------| | **const** | `\MembersEvent:ENTITY_CREATE_RESTRICTION` | | **name** | `members.entity.restriction.create` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\RestrictionEvent` | | **description** | The ENTITY_CREATE_RESTRICTION event occurs after a restriction has been created | *** #### members.entity.restriction.update | Type | Reference | |:----------------|:----------------------------------------------------------------------------| | **const** | `\MembersEvent:ENTITY_UPDATE_RESTRICTION` | | **name** | `members.entity.restriction.update` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\RestrictionEvent` | | **description** | ENTITY_UPDATE_RESTRICTION event occurs after a restriction has been updated | *** #### members.entity.restriction.delete | Type | Reference | |:----------------|:--------------------------------------------------------------------------------| | **const** | `\MembersEvent:ENTITY_DELETE_RESTRICTION` | | **name** | `members.entity.restriction.delete` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\RestrictionEvent` | | **description** | The ENTITY_DELETE_RESTRICTION event occurs after a restriction has been deleted | *** #### members.change_password.edit.initialize | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:CHANGE_PASSWORD_INITIALIZE` | | **name** | `members.change_password.edit.initialize` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The CHANGE_PASSWORD_INITIALIZE event occurs when the change password process is initialized. This event allows you to modify the default values of the user before binding the form. | #### members.change_password.edit.success | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:CHANGE_PASSWORD_SUCCESS` | | **name** | `members.change_password.edit.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The CHANGE_PASSWORD_SUCCESS event occurs when the change password form is submitted successfully. This event allows you to set the response instead of using the default one. | #### members.change_password.edit.completed | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:CHANGE_PASSWORD_COMPLETED` | | **name** | `members.change_password.edit.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The CHANGE_PASSWORD_COMPLETED event occurs after saving the user in the change password process. This event allows you to access the response which will be sent. | *** #### members.profile.edit.initialize | Type | Reference | |:----------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:PROFILE_EDIT_INITIALIZE` | | **name** | `members.change_password.edit.initialize` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The PROFILE_EDIT_INITIALIZE event occurs when the profile editing process is initialized. This event allows you to modify the default values of the user before binding the form. | #### members.profile.edit.success | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:PROFILE_EDIT_SUCCESS` | | **name** | `members.change_password.edit.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The PROFILE_EDIT_SUCCESS event occurs when the profile edit form is submitted successfully. This event allows you to set the response instead of using the default one. | #### members.profile.edit.completed | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:PROFILE_EDIT_COMPLETED` | | **name** | `members.profile.edit.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The PROFILE_EDIT_COMPLETED event occurs after saving the user in the profile edit process. This event allows you to access the response which will be sent. | *** #### members.registration.initialize | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:REGISTRATION_INITIALIZE` | | **name** | `members.registration.initialize` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\UserEvent` | | **description** | The REGISTRATION_INITIALIZE event occurs when the registration process is initialized. This event allows you to modify the default values of the user before binding the form. | #### members.registration.success | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:REGISTRATION_SUCCESS` | | **name** | `members.registration.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The REGISTRATION_SUCCESS event occurs when the registration form is submitted successfully. This event allows you to set the response instead of using the default one. | #### members.registration.failure | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:REGISTRATION_FAILURE` | | **name** | `members.registration.failure` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The REGISTRATION_FAILURE event occurs when the registration form is not valid. This event allows you to set the response instead of using the default one. The event listener method receives a OpenDxp\Bundle\MembersBundle\Event\FormEvent instance. | #### members.registration.completed | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:REGISTRATION_COMPLETED` | | **name** | `members.registration.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The REGISTRATION_COMPLETED event occurs after saving the user in the registration process. This event allows you to access the response which will be sent. | #### members.registration.confirm | Type | Reference | |:----------------|:--------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:REGISTRATION_CONFIRM` | | **name** | `members.registration.confirm` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The REGISTRATION_CONFIRM event occurs just before confirming the account. This event allows you to access the user which will be confirmed. | #### members.registration.confirmed | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:REGISTRATION_CONFIRMED` | | **name** | `members.registration.confirmed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The REGISTRATION_CONFIRMED event occurs after confirming the account. This event allows you to access the response which will be sent. | *** #### members.resetting.reset.request | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_RESET_REQUEST` | | **name** | `members.resetting.reset.request` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The RESETTING_RESET_REQUEST event occurs when a user requests a password reset of the account. This event allows you to check if a user is locked out before requesting a password. The event listener method receives a OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent instance. | #### members.resetting.reset.initialize | Type | Reference | |:----------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_RESET_INITIALIZE` | | **name** | `members.resetting.reset.initialize` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The RESETTING_RESET_INITIALIZE event occurs when the resetting process is initialized. This event allows you to set the response to bypass the processing. | #### members.resetting.reset.success | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_RESET_SUCCESS` | | **name** | `members.resetting.reset.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The RESETTING_RESET_SUCCESS event occurs when the resetting form is submitted successfully. This event allows you to set the response instead of using the default one. | #### members.resetting.reset.completed | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_RESET_COMPLETED` | | **name** | `members.resetting.reset.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The RESETTING_RESET_COMPLETED event occurs after saving the user in the resetting process. This event allows you to access the response which will be sent. | #### members.resetting.send_email.initialize | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_SEND_EMAIL_INITIALIZE` | | **name** | `members.resetting.send_email.initialize` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseNullableUserEvent` | | **description** | The RESETTING_SEND_EMAIL_INITIALIZE event occurs when the send email process is initialized. This event allows you to set the response to bypass the email confirmation processing. The event listener method receives a OpenDxp\Bundle\MembersBundle\Event\GetResponseNullableUserEvent instance. | #### members.resetting.send_email.confirm | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_SEND_EMAIL_CONFIRM` | | **name** | `members.resetting.send_email.confirm` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The RESETTING_SEND_EMAIL_CONFIRM event occurs when all prerequisites to send email are confirmed and before the mail is sent. This event allows you to set the response to bypass the email sending. The event listener method receives a OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent instance. | #### members.resetting.send_email.completed | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:RESETTING_SEND_EMAIL_COMPLETED` | | **name** | `members.resetting.send_email.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The RESETTING_SEND_EMAIL_COMPLETED event occurs after the email is sent. This event allows you to set the response to bypass the the redirection after the email is sent. The event listener method receives a OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent instance. | *** #### members.security.implicit_login | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:SECURITY_IMPLICIT_LOGIN` | | **name** | `members.security.implicit_login` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\UserEvent` | | **description** | The SECURITY_IMPLICIT_LOGIN event occurs when the user is logged in programmatically. This event allows you to access the response which will be sent. | *** #### members.delete_account.confirm.initialize | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:DELETE_ACCOUNT_INITIALIZE` | | **name** | `members.delete_account.confirm.initialize` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\GetResponseUserEvent` | | **description** | The DELETE_ACCOUNT_INITIALIZE event occurs when the delete account process is initialized. This event allows you to set the response to bypass the processing. | #### members.delete_account.confirm.success | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:DELETE_ACCOUNT_SUCCESS` | | **name** | `members.delete_account.confirm.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The DELETE_ACCOUNT_SUCCESS event occurs when the delete account form is submitted successfully. This event allows you to delete additional data objects from the system. | #### members.delete_account.confirm.completed | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:DELETE_ACCOUNT_COMPLETED` | | **name** | `members.delete_account.confirm.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The DELETE_ACCOUNT_COMPLETED event occurs after deleting the user object in the delete account process. This event allows you to access the response which will be sent. | *** #### members.oauth.sso_instance.complete_profile.success | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_SSO_INSTANCE_COMPLETE_PROFILE_SUCCESS` | | **name** | `members.oauth.sso_instance.complete_profile.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The OAUTH_SSO_INSTANCE_COMPLETE_PROFILE_SUCCESS event occurs when the complete-profile form is submitted successfully. This event allows you to set the response instead of using the default one. | #### members.oauth.sso_instance.complete_profile.completed | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_SSO_INSTANCE_COMPLETE_PROFILE_COMPLETED` | | **name** | `members.oauth.sso_instance.complete_profile.completed` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FilterUserResponseEvent` | | **description** | The OAUTH_SSO_INSTANCE_COMPLETE_PROFILE_COMPLETED event occurs after saving the user in the complete-profile process. This event allows you to access the response which will be sent. | #### members.oauth.sso_instance.complete_profile.failure | Type | Reference | |:----------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_SSO_INSTANCE_COMPLETE_PROFILE_FAILURE` | | **name** | `members.oauth.sso_instance.complete_profile.failure` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\FormEvent` | | **description** | The OAUTH_SSO_INSTANCE_COMPLETE_PROFILE_FAILURE event occurs when the complete-profile form is not valid. This event allows you to set the response instead of using the default one. | *** #### members.oauth.connection.success | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_PROFILE_CONNECTION_SUCCESS` | | **name** | `members.oauth.connection.success` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\OAuth\OAuthResponseEvent` | | **description** | The OAUTH_PROFILE_CONNECTION_SUCCESS event occurs after a existing user has been successfully connected to a provider. This event allows you to access the oauth response. | #### members.oauth.resource_mapping.profile | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_RESOURCE_MAPPING_PROFILE` | | **name** | `members.oauth.resource_mapping.profile` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\OAuth\OAuthResourceEvent` | | **description** | The OAUTH_RESOURCE_MAPPING_PROFILE event occurs before a sso identity gets assigned to given user profile. This event allows you to map resource data (e.g. google) to your user identity. | #### members.oauth.resource_mapping.registration | Type | Reference | |:----------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_RESOURCE_MAPPING_REGISTRATION` | | **name** | `members.oauth.resource_mapping.registration` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\OAuth\OAuthResourceEvent` | | **description** | The OAUTH_RESOURCE_MAPPING_REGISTRATION event occurs before the registration form gets rendered. This event allows you to map resource data (e.g. google) to your registration form. | #### members.oauth.resource_mapping.refresh | Type | Reference | |:----------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_RESOURCE_MAPPING_REFRESH` | | **name** | `members.oauth.resource_mapping.refresh` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\OAuth\OAuthResourceRefreshEvent` | | **description** | TThe OAUTH_RESOURCE_MAPPING_REFRESH event occurs after an existing sso identity has been found. This event allows you to map resource data (e.g. google) to your existing user identity. | *** #### members.oauth.identity_status.profile_completion | Type | Reference | |:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_IDENTITY_STATUS_PROFILE_COMPLETION` | | **name** | `members.oauth.identity_status.profile_completion` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\OAuth\OAuthIdentityEvent` | | **description** | The OAUTH_IDENTITY_STATUS_PROFILE_COMPLETION event occurs before a user enters the profile completion step. This event allows you to overrule the termination if a user is able to complete is profile or not. | #### members.oauth.identity_status.deletion | Type | Reference | |:----------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **const** | `\MembersEvent:OAUTH_IDENTITY_STATUS_DELETION` | | **name** | `members.oauth.identity_status.deletion` | | **class** | `\OpenDxp\Bundle\MembersBundle\Event\OAuth\OAuthIdentityEvent` | | **description** | The OAUTH_IDENTITY_STATUS_DELETION event occurs before a identity gets deleted. This event allows you to overrule the termination if a identity can be deleted (after sso identity has been deleted). | --- ## Custom Form Types The default form types only have some few elements. Within a registration you may want to know some more information about the user like first name, street etc. ### Create a Custom Form Type Just create your own form type and override the default value in your `config/config.yaml`: ```yaml opendxp_members: relations: login: form: type: OpenDxp\Bundle\MembersBundle\Form\Type\LoginFormType name: members_user_login_form validation_groups: [Login, Default] # or instance of \MembersBundle\Validation\ValidationGroupResolverInterface profile: form: type: OpenDxp\Bundle\MembersBundle\Form\Type\ProfileFormType name: members_user_profile_form validation_groups: [Profile, Default] # or instance of \MembersBundle\Validation\ValidationGroupResolverInterface change_password: form: type: OpenDxp\Bundle\MembersBundle\Form\Type\ChangePasswordFormType name: members_user_change_password_form validation_groups: [ChangePassword, Default] # or instance of \MembersBundle\Validation\ValidationGroupResolverInterface registration: token_ttl: 604800 form: type: App\Form\Type\RegistrationFormType name: members_user_registration_form validation_groups: [Registration, Default] # UsernameOnlyRegistration, EmailOnlyRegistration, or instance of \MembersBundle\Validation\ValidationGroupResolverInterface resetting_request: form: type: OpenDxp\Bundle\MembersBundle\Form\Type\ResettingRequestFormType name: members_user_resetting_request_form validation_groups: [ResetPassword, Default] # or instance of \MembersBundle\Validation\ValidationGroupResolverInterface resetting: token_ttl: 86400 form: type: OpenDxp\Bundle\MembersBundle\Form\Type\ResettingFormType name: members_user_resetting_form validation_groups: [ResetPassword, Default] # or instance of \MembersBundle\Validation\ValidationGroupResolverInterface delete_account: form: type: OpenDxp\Bundle\MembersBundle\Form\Type\DeleteAccountFormType name: members_user_delete_account_form validation_groups: [DeleteAccount, Default] # or instance of \MembersBundle\Validation\ValidationGroupResolverInterface ``` --- ## Registration Types You can choose between three types of registration completion: #### Confirm by Mail Name: `confirm_by_mail` > This is the default value. After registration the user will receive a confirmation mail with a confirmation url. By clicking on that link the user gets automatically activated. If `send_admin_mail_after_register` is enabled, the system will send a notification mail to a defined admin. ##### Email prefetching > [!IMPORTANT] > Some email providers have spam detection or security features that prefetch URLs from incoming emails > (e.g., Safe Links in Microsoft Defender for Office 365). To prevent unintended automatic activations, you can enable a "preview confirmation" page. This requires users to manually confirm their registration by clicking an additional button. This feature is disabled by default. To enable it, update your configuration as follows: ```yaml opendxp_members: enable_preview_confirmation: true # default is false ``` When enabled, users will first be redirected to /confirm-preview/\{token\}, where they must confirm their registration manually. *** #### Confirm By Admin Name: `confirm_by_admin` After registration the user has to wait until a authorized admin activates the user in backend. If `send_user_mail_after_confirmed` is enabled, the system will send a notification mail to user. *** #### Confirm Instant Name: `confirm_instant` After registration the user gets automatically logged in without any further actions. *** ### Configuration Add those lines to your `config/config.yaml`: ```yaml opendxp_members: # choose between 'confirm_by_mail', 'confirm_by_admin', 'confirm_instant' post_register_type: 'confirm_by_mail' #optional: see "Confirm by Mail" send_admin_mail_after_register: false #optional: see "Confirm By Admin" send_user_mail_after_confirmed: false ``` *** ### Registration Types with SSO If you're using the [SSO feature](./SSO/10_Overview.md), you may want to define some independent mail workflows. If Members detects an SSO registration process, you're able to define the registration type via the `post_register_type_oauth` flag. > **Attention*: SSO registration types only works if `activation_type` has been set to `complete_profile`. They work the same as above, however `confirm_instant` is the default value: ```yaml opendxp_members: # choose between 'confirm_by_mail', 'confirm_by_admin', 'confirm_instant' post_register_type_oauth: 'confirm_instant' ``` *** ### Disable Registration Set `enabled` to `false` to disable the registration. The registration form returns 404, and a login with an unknown SSO identity creates no member. Confirmation links that were sent before keep working. ```yaml opendxp_members: relations: registration: enabled: false # default is true ``` --- ## Email Configuration(Members) Members will install some emails for you by default. But you may need some more complex implementation. You'll find the default mails in `/email/`. #### Default Paths Feel free to move the mails to a different location and define it in your configuration: ```yaml opendxp_members: emails: default: register_confirm: '/email/register-confirm' register_confirmed: '/email/register-confirmed' register_password_resetting: '/email/password-reset' admin_register_notification: '/email/admin-register-notification' ``` #### Mail Localization If you have a multiple languages, you may want to use the `{_locale}` fragment in your paths: ```yaml opendxp_members: emails: default: register_confirm: '/{_locale}/email/register-confirm' register_confirmed: '/{_locale}/email/register-confirmed' register_password_resetting: '/{_locale}/email/password-reset' admin_register_notification: '/{_locale}/email/admin-register-notification' ``` #### Site based Mail Templates If you have multiple sites, you have to define them like this: ```yaml opendxp_members: emails: # if no site gets found, the default stays as fallback. default: register_confirm: '/{_locale}/email/register-confirm' register_confirmed: '/{_locale}/email/register-confirmed' register_password_resetting: '/{_locale}/email/password-reset' admin_register_notification: '/{_locale}/email/admin-register-notification' sites: - main_domain: 'your-domain1' emails: register_confirm: '/domain1/email/register-confirm' register_confirmed: '/domain1/email/register-confirmed' register_password_resetting: '/domain1/email/password-reset' admin_register_notification: '/domain1/email/admin-register-notification' - main_domain: 'your-domain2' emails: register_confirm: '/domain2/{_locale}/email/register-confirm' register_confirmed: '/domain2/{_locale}/email/register-confirmed' register_password_resetting: '/domain2/{_locale}/email/password-reset' admin_register_notification: '/domain2/{_locale}/email/admin-register-notification' ``` #### Locale Mapping Since Members allows activating users through backend, the locale definition may gets lost. If a user gets registered, Members will append two properties to the user object: - `_site_domain`: optional, if the registration happens in a site request, the main domain gets stored. - `_user_locale`: the registration request locale. --- ## Groups ### Add Default Groups to new User If you want to add some groups to a new user after a successfully registration, you need to extend the configuration. ```yaml opendxp_members: user: initial_groups: - 'Group 1' # via group name - 22 # via id ``` --- ## Roles Every Group is connected with the `ROLE_USER` role by default. ### Add Roles Adding Roles is quite simple. Add this to your `config/config.yaml`: ```yaml security: role_hierarchy: ROLE_MEMBERS_MODERATOR: [ROLE_USER] ``` Open your group object, select `ROLE_MEMBERS_MODERATOR` and save group. > Note: Make sure that your user is connected with this group. ### Example Check the Role in a controller ```php denyAccessUnlessGranted('ROLE_MEMBERS_MODERATOR', null, 'Unable to access this page!'); } } ``` --- ## Rate Limiting Members limits the attempts from one IP address with the [Symfony rate limiter](https://symfony.com/doc/current/rate_limiter.html). A visitor who uses up the attempts sees the error "Too many attempts. Please try again later." in the form. | Limiter | Form | Default | |-----------------------------|------------------------|--------------------| | `members_registration` | Registration | 5 per hour | | `members_resetting_request` | Password reset request | 5 per 5 minutes | Change a limit in your `config/config.yaml`: ```yaml framework: rate_limiter: members_registration: limit: 10 interval: '1 hour' ``` The policy `no_limit` turns a limiter off: ```yaml framework: rate_limiter: members_resetting_request: policy: 'no_limit' ``` ### Login The login runs through your firewall. Symfony throttles it with `login_throttling`: ```yaml security: firewalls: members_fe: login_throttling: max_attempts: 3 interval: '5 minutes' ``` The [example configuration](../config/install/packages/security_auth_manager.yaml) contains it. --- ## Security Log Members writes security events to the Monolog channel `members`. The handler `members` stores them in `var/log/members-.log` and deletes a file after 30 days. | Event | Level | Context | |-------------------------------------------|-----------|-------------------------------------------| | A login in the members firewall failed | `warning` | `username` | | A member requested a password reset | `info` | `member` | | A member reset the password | `info` | `member` | | The groups of a member changed | `info` | `member`, `groups_before`, `groups_after` | | A member connected an SSO identity | `info` | `member`, `provider` | | A member was deleted | `info` | `member` | | The restriction of an element changed | `info` | `element`, `type`, `groups` | | The restriction of an element was removed | `info` | `element`, `type` | Every entry also contains the IP address of the request as `ip` and the id of the editor as `editor`. `editor` is empty outside of the OpenDXP backend. ### Personal data The log contains IP addresses and usernames. Mention it in your privacy policy. The purpose is the detection and the investigation of attacks on member accounts. Change the retention in your `config/config.yaml`: ```yaml monolog: handlers: members: max_files: 14 ``` ### Disable the log ```yaml opendxp_members: security_log: enabled: false ``` --- ## Changelog(Members) ### 1.1.1 - [SECURITY] [FOLLOW-UP] [OPENDXP-SA-2026-012] A protected asset and its thumbnails are delivered only to a member who may access the asset. Asset links from before the update no longer work 1. Run `bin/console opendxp:cache:clear`. - [SECURITY] [OPENDXP-SA-2026-013] The login through a provider redirects only to a path of the same site - [SECURITY] [FOLLOW-UP] [MIGRATION] [OPENDXP-SA-2026-014] Members store their confirmation tokens as hashes. A token of a password reset no longer confirms a registration. A confirmation link expires after `relations.registration.token_ttl`, 7 days by default 1. Run `bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\MembersBundle\Migrations'`. - [SECURITY] [OPENDXP-SA-2026-014] A password reset no longer publishes an unpublished member - [SECURITY] [OPENDXP-SA-2026-015] A password change ends the other sessions of the member - [ENHANCEMENT] The password reset request checks the CSRF token of the form - [ENHANCEMENT] [FOLLOW-UP] Logout links of the bundle carry the CSRF token of the members firewall 1. Remove `hide_user_not_found: false` from your security configuration. 2. Set `logout.invalidate_session: true` and `logout.enable_csrf: true` in the members firewall. 3. Use `logout_path('members_fe')` for the logout links in your templates. - [SECURITY] [OPENDXP-SA-2026-016] The restriction of an element changes only through POST and only for an editor who may save the element. Reading a restriction needs the right to view the element - [ENHANCEMENT] `oauth.store_profile_data: false` keeps the profile of the provider out of a new single sign on identity. See [Installation](docs/SSO/20_Installation.md#enable-feature) - [BUGFIX] The clean-up of expired identities works with `oauth.expired_tokens_ttl` - [BUGFIX] The clean-up of expired identities removes a member without a password once its last identity is gone - [BUGFIX] Members who log in only through single sign on can delete their account - [ENHANCEMENT] `relations.registration.enabled: false` disables the registration, also through single sign on. See [Registration Types](docs/60_RegistrationTypes.md#disable-registration) - [ENHANCEMENT] A new password needs at least 12 characters and must not appear in a known data leak - [NEW FEATURE] Members logs failed logins, password resets, group changes, SSO connections, deletions and restriction changes to `members.log`. See [Security Log](docs/96_SecurityLog.md) - [NEW FEATURE] [FOLLOW-UP] Registrations and password reset requests are rate limited per IP address. See [Rate Limiting](docs/95_RateLimiting.md) 1. Add `login_throttling` to the members firewall. - [BUGFIX] A member who left a reset link unused can request a new one - [BUGFIX] With `enable_public_asset_path_protection`, links to the original files of protected assets work - [BUGFIX] Saving the groups of a restriction is atomic - [BUGFIX] `members:oauth:setup` names the configuration key `opendxp_members` when OAuth is disabled - [ENHANCEMENT] New installations name the user field `username` - [ENHANCEMENT] Subclasses of `UserTrait` can extend the roles - [ENHANCEMENT] Installed classes have fixed ids: `members_user`, `members_group`, `members_sso_identity` ### 1.1.0 - [SECURITY] [OPENDXP-SA-2026-002] A member no longer carries the plain password into the session after a registration or a password reset - [DEPRECATION] `eraseCredentials()` of the member is deprecated. The plain password is left out whenever a member is serialized - [ENHANCEMENT] Add classes to test projects with members, see [Tests](docs/400_Tests.md) - [BUGFIX] Finding the member of a single sign on identity also checks the field `ssoIdentities` - [BUGFIX] Registration and password reset work when the class editor saved an empty default for the confirmation token - [BUGFIX] The logout link of the login brick shows the translation `members.layout.logout` - [ENHANCEMENT] Flash messages carry `role="status"` - [BUGFIX] The documentation and `config:dump-reference` show the configuration key `opendxp_members` - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.3 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.2 - [ENHANCEMENT] Update composer dependency to support Doctrine ORM 2.15 ### 1.0.1 - [CHORE] Fix doc paths - [CHORE] Migrate data from upstream ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix test infrastructure [#1](https://github.com/open-dxp/members-bundle/pull/1) --- ## Migrating to OpenDXP(Members) ### Migrating from `dachcom-digital/members` to `open-dxp/members-bundle` 1. Replace `dachcom-digital/members` with `open-dxp/members-bundle` in your `composer.json`. 2. Replace the namespace `MembersBundle\` with `OpenDxp\Bundle\MembersBundle\`. 3. Replace `MembersBundle\MembersBundle` with `OpenDxp\Bundle\MembersBundle\OpenDxpMembersBundle` in `config/bundles.php`. 4. Rename the configuration node `members` to `opendxp_members`. --- ## Members Bundle Add frontend user authentication and document restriction to opendxp. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 2025 | Feature Branch | 1.x | ### Features * Create Members in backend * Allow Members to register in frontend * Restrict documents, objects and assets to specific user roles *** ### Installation Please read the installation instructions before going deep with Members! #### Composer Installation 1. Add code below to your `composer.json` ```json "require": { "open-dxp/members-bundle" : "~1.0.0" } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\MembersBundle\OpenDxpMembersBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpMembersBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\MembersBundle'` ##### Optional: Class Installation > Read more about the required classes [below](./README.md#class-installation)). ```bash bin/console members:install:class ``` #### Security Installation It is not possible to merge security configurations from multiple locations, including bundles. Instead, you have to move them to one single config file, e.g. `config/packages/security.yaml`. Please adopt [security_auth_manager.yaml](./config/install/packages/security_auth_manager.yaml) and merge your own firewall configuration into one single file. #### Route Installation MembersBundle does not include any routes per default. Otherwise, it would be hard for you to change or override included routes. **Include all Routes** ```yaml # config/routes.yaml app: resource: '@OpenDxpMembersBundle/config/opendxp/routing/all.yaml' ``` **Just include some Routes** ```yaml # config/routes.yaml members_auth: resource: '@OpenDxpMembersBundle/config/opendxp/routing/auth.yaml' prefix: /{_locale}/members #change your prefix if you have to. ``` #### Class Installation Since Members should be the one and only frontend authentication bundle, we need to add the most flexibility as possible. But no worries, it's still simple to integrate. > There is also a class installer command. If you're not using any special class configuration, feel free to use this command: `$ bin/console members:install:class` > Use the `-o` argument to also install the SsoIdentity Class You need two classes: User and Group. So let's create it: *User* 1. Create a class and call it `MembersUser` 2. Add parent class: `\OpenDxp\Bundle\MembersBundle\Adapter\User\AbstractUser` 3. Add fields: | Name | Field Type | Comment | |---------------------|-------------|-----------------------------------------------------------------------------------------------------------------| | username | Input | | | email | Input | **Note:** Do not add this field if you're using the [CMF](docs/20_ClassCustomization.md). | | confirmationToken | Input | must set to it read only | | lastLogin | Date & Time | must set to it read only | | password | Password | Hide it, if you want. **Note:** Do not add this field if you're using the [CMF](docs/20_ClassCustomization.md). | | passwordRequestedAt | Date & Time | must set to it read only | | groups | User Group | This field comes with Members | > `membersUser` is the default name, you may want to change it. Read [here](docs/20_ClassCustomization.md) how to achieve that. ##### Customer Data Framework If you want to use the [Customer Data Framework](https://github.com/open-dxp/customer-data-framework) you need to do some further work. Read more about it [here](docs/300_CustomerDataFw.md). ##### SSO Login You want to enable the SSO Feature in Members? Read more about it [here](./docs/SSO/20_Installation.md). *Group* 1. Create a class and call it `MembersGroup` 2. Add parent class: `\OpenDxp\Bundle\MembersBundle\Adapter\Group\AbstractGroup` 3. Add fields: | Name | Field Type | Comment | |-------|----------------|----------------------------------------------------------------------------------------------------------------------------| | name | Input | | | roles | Multiselection | Set "Options Provider Class or Service Name" to `@OpenDxp\Bundle\MembersBundle\CoreExtension\Provider\RoleOptionsProvider` | > `membersGroup` is the default name, you may want to change it. Read [here](docs/20_ClassCustomization.md) how to achieve that. Feel free to add additional fields since those are just the required ones. That's it. Members will use those classes to manage authentication and group management. #### Email Configuration You're almost there, just check the [email configuration](docs/70_EmailConfiguration.md) and you're good to go. *** #### User Management: Further Information - [Auth Identifier](docs/10_AuthIdentifier.md) Use `email` instead of `username` for authentication - [Custom Class Names](docs/20_ClassCustomization.md) - [Frontend Routes & Views](docs/30_FrontendRoutes.md) - [Available Events](docs/40_Events.md) - [Custom Form Types](docs/50_CustomFormTypes.md) - [Registration Types](docs/60_RegistrationTypes.md) - [Email Configuration](docs/70_EmailConfiguration.md) - [Groups](docs/80_Groups.md) - [Roles](docs/90_Roles.md) - [Rate Limiting](docs/95_RateLimiting.md) - [Security Log](docs/96_SecurityLog.md) - [Use the OpenDXP Customer Framework with Members](docs/300_CustomerDataFw.md) *** ### Restrictions Learn more about the Members Restriction feature: - [Brief Overview](docs/200_Restrictions.md) - [Restricted Navigation](docs/210_RestrictedNavigation.md) - [Restricted Routing](docs/220_RestrictedRouting.md) - [Restricted Listing](docs/230_RestrictListing.md) - [Protected Asset Downloader](docs/240_AssetProtection.md) *** ### Single Sign On (SSO) with OAuth2 - [Overview](./docs/SSO/10_Overview.md) - [Integration Types](./docs/SSO/11_IntegrationTypes.md) - [Resource Mapping](./docs/SSO/12_ResourceMapping.md) - [Installation](./docs/SSO/20_Installation.md) - [Twig Extensions](./docs/SSO/30_TwigExtensions.md) ### Tests - [Testing](docs/400_Tests.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Single Sign On (SSO) Members supports integration with third-party services for single sign on. Services like Google, Facebook etc. can be integrated and used as SSO providers for user registration and user login while Members will act as SSO client. ![Members as SSO client between the login page and the providers](./img/sso_overview.png) ### Dependencies We're using the [KnpUOAuth2ClientBundle](https://github.com/knpuniversity/oauth2-client-bundle) which relies on [league/oauth2-client](https://oauth2-client.thephpleague.com). ### Integration Types There are two integration types: "*Login*" and "*Connect*". The login type comes with two sub workflows: "*complete_profile*" and "*instant*" Read more about the integration types [here](./11_IntegrationTypes.md) ### Downsides Currently, there is no oAuth1 Support. ### Clean expired identities By default, no identities get deleted after its expiration. However, you may want to enable the [clean up listener](./31_Listener.md). --- ## Integration Types There are two basic integration types: ### I. Login Triggers, if a new user want's to connect. That said, there are two ways to complete users registration: #### I.I Instant Login A successfully connected users gets logged in instantly. ```yaml opendxp_members: oauth: enabled: true activation_type: 'instant' ``` ##### Delayed Profile Completion ![Profile page with a button to complete the profile](./img/sso_delayed_profile_completion.png) It's possible to complete this "unknown" users profile in later step which uses a dedicated form type (`Form/Type/Sso/CompleteProfileFormType.php`). By default, this completion is possible, as long the instant created SSO identity has no given password. If you want to change that, use the [status event](./32_IdentityStatusListener.md#oauth_identity_status_profile_completion). #### I.II Login via Profile Completion After the request was successful, the user gets redirected to the registration form. There is no need to enter a password. Some fields may already be pre-filled (Read more about it [here](./12_ResourceMapping.md). > **Attention**: The `validation_group` of `RegistrationFormType` changes to `SSO` while registration is in `complete_profile` mode. ```yaml opendxp_members: oauth: enabled: true activation_type: 'complete_profile' ``` *** ### II. Connect Triggers, if an existing user want's to connect a profile with a given provider (e.g. Google). A list of all possible connectors are available in user's profile (There are some [twig extensions](./30_TwigExtensions.md)). --- ## Resource Mapping If a user successfully gets connected via a given provider, you're able to map some data to your user entity. For example, if you're using a Google client, there are some properties you may want to use (`email`, `name`). Since every client may vary in naming of properties, you also may want to adjust the mapping. Just use a EventListener to do so. ### Default Mapping If there is no registered event listener, Members tries to map some default fields by guessing all properties by `method_exists()`. There are some invalid properties: 'lastLogin', 'password', 'confirmationToken', 'passwordRequestedAt', 'groups', 'ssoIdentities'. However, if you're adding your own EventListener, the mapping is totally up to you. There are two different types of mapping events: #### OAUTH_RESOURCE_MAPPING_PROFILE The `OAUTH_RESOURCE_MAPPING_PROFILE` event occurs before a SSO Identity gets assigned to given user profile. This Event fires shortly before the SSO Identity gets applied to the user. > **Attention**: This event also fires after an existing user gets connected to a client. You may don't want to override existing values! #### OAUTH_RESOURCE_MAPPING_REGISTRATION The `OAUTH_RESOURCE_MAPPING_REGISTRATION` event occurs before the registration form gets rendered (Only available if integration type is `complete_profile`). ### Adding EventListener First, add your service: ```php 'onProfileMapping', MembersEvents::OAUTH_RESOURCE_MAPPING_REGISTRATION => 'onRegistrationMapping', MembersEvents::OAUTH_RESOURCE_MAPPING_REFRESH => 'onRegistrationRefresh', ]; } public function onProfileMapping(OAuthResourceEvent $event): void { $user = $event->getUser(); $resourceOwner = $event->getResourceOwner(); $ownerDetails = $resourceOwner->toArray(); $this->mapData($user, $ownerDetails); } public function onRegistrationMapping(OAuthResourceEvent $event): void { $user = $event->getUser(); $resourceOwner = $event->getResourceOwner(); $ownerDetails = $resourceOwner->toArray(); $this->mapData($user, $ownerDetails); } public function onRegistrationRefresh(OAuthResourceRefreshEvent $event): void { $user = $event->getUser(); $resourceOwner = $event->getResourceOwner(); $ownerDetails = $resourceOwner->toArray(); $user->setUserName($ownerDetails['name']); // ATTENTION! You need to inform event about changes! $event->setHasChanged(true); } protected function mapData(UserInterface $user, array $ownerDetails): void { if (empty($user->getEmail()) && isset($ownerDetails['email'])) { $user->setEmail($ownerDetails['email']); } if (empty($user->getUserName()) && isset($ownerDetails['name'])) { $user->setUserName($ownerDetails['name']); } } } ``` Then, register it: ```yaml App\EventListener\MembersResourceMappingListener: autowire: true tags: - { name: kernel.event_subscriber } ``` --- ## Installation(SSO) The sso connector is disabled by default for flexibility reasons. But it's quite easy to enable it. Use our helper command, which guides you through the installation process: ### Helper Command ![Output of the OAuth setup command](./img/sso_setup_command.png) ```bash $ bin/console members:oauth:setup ``` If you don't want to use it, you need to check several steps which we're going to explain to you right now: ### Install Classes You need an additional Class for the SSO Identity. Every provider (e.g. Google or Facebook) creates an `SsoIdentity` entity, which gets appended to a user object. If you're using all the default Members Classes, you can simply re-run the command: ````bash $ bin/console members:install:class -o ```` By adding the `-o` argument, this command will install the `SsoIdentity`. Already installed classes will be skipped. If you want to use a different name, just create the class and import it from `src/MembersBundle/config/install/classes/class_SsoIdentity_export.json`. Read more about changing the default class name [here](../20_ClassCustomization.md). ### Add SSO Identity Relation Field **Important!** This step is only required if you're updating an existing installation! If you have installed Members from scratch via the class installer, this field is already available! Add this to your `var/classes/definition_YOUR_USER_CLASS_NAME.php` (right after the `group` section): ```json { "fieldtype": "manyToManyObjectRelation", "width": "", "height": "", "maxItems": "", "queryColumnType": "text", "phpdocType": "array", "relationType": true, "visibleFields": "key", "optimizedAdminLoading": false, "visibleFieldDefinitions": [], "lazyLoading": true, "classes": [ { "classes": "SsoIdentity" } ], "pathFormatterClass": "", "name": "ssoIdentities", "title": "SSO Identities", "tooltip": "", "mandatory": false, "noteditable": false, "index": false, "locked": false, "style": "", "permissions": null, "datatype": "data", "invisible": false, "visibleGridView": false, "visibleSearch": false } ``` ### Add SSO IdentityAwareInterface ![Parent PHP class AbstractSsoAwareUser in the class settings](./img/sso_user_class.png) You need to change the parent class of your existing user class to `\OpenDxp\Bundle\MembersBundle\Adapter\User\AbstractSsoAwareUser`. ### Install Dependencies Install the [KnpUOAuth2ClientBundle](https://github.com/knpuniversity/oauth2-client-bundle): ```bash $ composer require knpuniversity/oauth2-client-bundle:^2.0 ``` You also need to add some providers. There is a [list of all available provider](https://github.com/knpuniversity/oauth2-client-bundle#step-1-download-the-client-library). In this example, we're going to install the google client: ```bash $ composer require league/oauth2-google:^3.0 ``` ### Set Cookie SameSite to Lax Otherwise, the oauth connection won't work. > If you have any hints to allow processing an oauth connection within `strict` mode, > please [tell us](https://github.com/open-dxp/members-bundle/issues). ```yaml framework: session: cookie_samesite: 'lax' ``` ### Enable Feature Read more about the `activation_type` [here](./11_IntegrationTypes.md). ```yaml opendxp_members: oauth: enabled: true activation_type: 'complete_profile' # choose between "complete_profile" and "instant" ``` An identity stores the whole profile of the provider in `profileData`. The profile contains personal data like the name and the email. Members does not read it. Set `store_profile_data` to `false` to keep the field empty: ```yaml opendxp_members: oauth: store_profile_data: false # default is true ``` ### Configure Firewall If your using a different name for your firewall than `members_fe` you need to configure the container parameter: ```yaml parameters: members.firewall_name: your_fw_name ``` ### Configure Client Every provider comes with its own configuration. In this example, we're going to setup the google client: **Attention:** Always use the `members_user_security_oauth_check` route in `redirect_route`. > There is also a full list of all [configurations](https://github.com/knpuniversity/oauth2-client-bundle#configuration) ```yaml knpu_oauth2_client: clients: google: type: google client_id: 'YOUR_CLIENT_ID' client_secret: 'YOUR_CLIENT_SECRET' redirect_route: members_user_security_oauth_check redirect_params: {} ``` ### Configure Client Scope If you need a special scope definition, you can add them in the Members configuration. Just add your client (`google`in your example) to the `scopes` node. Value needs to be an `array`. > If there is no configured scope, the oauth2 client will trigger `getDefaultScopes()` (see [documentation](https://github.com/thephpleague/oauth2-client/blob/master/docs/providers/implementing.md#implementing-a-provider). > Default scope values vary from client to client. ```yaml opendxp_members: oauth: scopes: google: ['email'] ``` ### Registration Types Finally, checkout the registration type for SSO [here](../60_RegistrationTypes.md#registration-types-with-sso). --- ## Twig Extension > **Note:** Always call `members_system_oauth_enabled()` first, the oauth extension could be unavailable! ### members_system_oauth_enabled Check if oauth has been enabled: ```twig {% if members_system_oauth_enabled() == true %} {# oauth is enabled #} {% endif %} ``` ### members_oauth_social_links List all available social connectors: ```twig {% if members_system_oauth_enabled() == true %} {% set social_route_name = 'members_user_security_oauth_login' %} {% set skip_connected_identities = false %} {% dump(members_oauth_social_links(social_route_name, skip_connected_identities)) %} {% endif %} ``` ### members_oauth_can_complete_profile Check if a new registered SSO user can enter the profile completion route: ```twig {% if members_system_oauth_enabled() == true %} {% if members_oauth_can_complete_profile() == true %} {# do something funky #} {% endif %} {% endif %} ``` --- ## Listeners ### Clean Up expired Identities There two ways to clean up expired identities. > **Note:** This feature is not enabled by default! #### Important Notes This Clean-Up task also removes the related user within some default exceptions: - The user will **not be deleted** if the given user has other SSO identities - The user will **not be deleted** if a password has been defined (not empty rule) You're able to change the default exceptions by alter the `OAUTH_IDENTITY_STATUS_DELETION` event. Read more about it [here](./32_IdentityStatusListener.md). #### I. Expired Date Use the `clean_up_expired_tokens` configuration flag to enable the clean-up. In this example, all identities, older than `expiresAt` will be removed. ```yaml opendxp_members: oauth: clean_up_expired_tokens: true ``` SQL Explanation: ```mysql SELECT entites WHERE expiresAt IS NOT NULL AND expiresAt < NOW(); ``` #### II. Expired By TTL Use the `clean_up_expired_tokens` configuration flag to enable the clean-up. Use the `expired_tokens_ttl` configuration flag to define a ttl in seconds. In this example, all identities, older than 24h will be removed. ```yaml opendxp_members: oauth: clean_up_expired_tokens: true expired_tokens_ttl: 86400 ``` SQL Explanation: ```mysql SELECT entites WHERE o_creationDate < (UNIX_TIMESTAMP() - $TTL); ``` --- ## SSO Identity Listeners If you need to hook into core decisions, you may want to use som identity state listener: ### OAUTH_IDENTITY_STATUS_DELETION Use this event to change the deletion status of a SSO Identity. This event triggers, if you have enabled the [identity clean-up task](./31_Listener.md). ```php 'onDispatch' ]; } public function onDispatch(OAuthIdentityEvent $event): void { $user = $event->getIdentity(); // this is just an example if (!empty($user->getLastLogin())) { // this will prevent the user deletion $event->setIdentityDispatchStatus(false); } } } ``` ### OAUTH_IDENTITY_STATUS_PROFILE_COMPLETION Use this event to change the status definition if a sso only user is able to call the completion profile route. By default, an instantly logged in user can complete his profile afterwards in his profile (`/en/members/profile/`, **if no password** has been set. If you want to change that, use the `OAUTH_IDENTITY_STATUS_PROFILE_COMPLETION` event: ```php 'onDispatch' ]; } public function onDispatch(OAuthIdentityEvent $event): void { $user = $event->getIdentity(); // this is just an example if (!empty($user->getUsername())) { // this will prevent the user deletion $event->setIdentityDispatchStatus(false); } } } ``` --- ## Changelog(Monitoring) ### 1.1.1 - [BUGFIX] Skip user folders in `UserCheck` ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [CHORE] Fix composer.json formatting [#3](https://github.com/open-dxp/monitoring-bundle/pull/3) ### 1.0.1 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.0 - [NEW FEATURE] Initial release --- ## Migrating to OpenDXP(Monitoring) ### Migrating from `dachcom-digital/monitoring` to `open-dxp/monitoring-bundle` 1. Replace `dachcom-digital/monitoring` with `open-dxp/monitoring-bundle` in your `composer.json`. 2. Replace the namespace `MonitoringBundle\` with `OpenDxp\Bundle\MonitoringBundle\`. 3. Replace `MonitoringBundle\MonitoringBundle` with `OpenDxp\Bundle\MonitoringBundle\OpenDxpMonitoringBundle` in `config/bundles.php`. 4. Rename the configuration node `monitoring` to `opendxp_monitoring`. --- ## Monitoring Bundle Fetch health state of your opendxp installation. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.0` | `7.4` | 2025 | Feature Branch | 1.x | ### Installation ```json "require": { "open-dxp/monitoring-bundle" : "~1.0.0" } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\MonitoringBundle\OpenDxpMonitoringBundle::class => ['all' => true], ]; ``` #### Install Routes ```yaml # config/routes.yaml monitoring: resource: '@OpenDxpMonitoringBundle/config/routing.yaml' ``` #### Configuration ```yaml # config/packages/opendxp_monitoring.yaml opendxp_monitoring: api_code: 'YOUR_API_CODE' ``` ### Fetch Data ```bash curl --data "apiCode=YOUR_API_CODE" https://www.your-domain.tld/monitoring/fetch ``` ### Fetch Data By Check ```bash curl --data "apiCode=YOUR_API_CODE" https://www.your-domain.tld/monitoring/fetch?filter=core,heartbeat ``` ### Create Custom Check Create a tagged `opendxp.monitoring.check` service and implement the `CheckInterface` interface. ### Available Checks - OpenDXP version and revision - PHP (version, memory_limit and more) - Kernel (environment, debug) - Installed Bundles - Installed AreaBricks - Available Users *** ### Modules #### Email Log Module ```bash opendxp_monitoring: modules: email_log: true # disabled by default ``` ```bash curl --data "apiCode=YOUR_API_CODE" https://www.your-domain.tld/monitoring/fetch-email-log ``` ##### Params - `onlyErrors`: only fetch logs with errors (Default `false`) - `startingFrom`: only fetch logs newer than `Y-m-d H:i:s` (Default `null`) - `limit`: limit log response (Default `100`) #### Heartbeat Module This module provides a lightweight "heartbeat" mechanism to monitor the execution of periodic maintenance tasks. It helps verify that both the system **cronjob** and the **Symfony Messenger queue** are functioning correctly. This heartbeat check: - Confirms that the cronjob is triggering as expected. - Confirms that the Messenger worker is actively processing jobs. - Optionally indicates the **duration or load** of the maintenance task by analyzing time deltas between executions. ```bash opendxp_monitoring: modules: heartbeat: true # disabled by default ``` This will also add a check `hearbeat`. *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Head Meta Generator The Head Meta Generator creates some additional meta information for the news detail page (like head title, meta description and some open graph elements). ### Create a custom Generator Just override the build in generator: ```yaml news: relations: OpenDxp\Bundle\NewsBundle\Generator\HeadMetaGenerator: App\Generator\AppHeadMetaGenerator ``` And set up your new class: ```php linkGenerator->generateDetailLink($entry); $params = ['your_meta_tag_name' => $href]; return $params; } } ``` --- ## Link Generator The Link Generator creates a valid detail and back link for each entry. ## OpenDXP Link Generator If you want to use the default OpenDXP [Link Generator](https://docs.opendxp.io/docs/core-framework/Objects/Object_Classes/Class_Settings/Link_Generator), just implement it like described in the link. If no default Link Generator Service has been defined, the News Bundle will proceed with the internal Class. ### Create a custom generator Just override the build in generator: ```yaml news: relations: OpenDxp\Bundle\NewsBundle\Generator\LinkGenerator: App\Generator\AppLinkGenerator ``` And set up your new class: ```php info = $info; } /** * This method needs to return a key value array. * * @return array */ public function getViewParams(): array { // this is just an example, // just return any parameter you need in your view $list = NewsEntry::getList(); $list->setLimit(5); $paginator = new Paginator($list); $paginator->setCurrentPageNumber(1); $paginator->setItemCountPerPage(2); return [ 'paginator' => $paginator ]; } } ``` ### Twig View Add a view file to `templates/OpenDxpNewsBundle/list/preset/special.html.twig`: > **Note:** The view name has to be the same as your defined service. > **Note:** All your parameters are stored in the `preset` variable. ```twig

My Special View

{% for news in preset.paginator %}

{{ news.getName }}

{% endfor %} {# paginator example #} {% include '@OpenDxpNews/List/Block/paginator.html.twig' with { paginator: preset.paginator } only %} ``` --- ## Custom Configuration If the available configurability is not sufficient, you can now extend the configuration with your own fields. #### Eventlistener Create an eventlistener that listens to the ``NewsEvents::NEWS_BRICK_QUERY_BUILD`` event ```php tagRenderer = $tagRenderer; } /** * @return array */ public static function getSubscribedEvents() { return [ NewsEvents::NEWS_BRICK_QUERY_BUILD => 'modifyBrick' ]; } /** * @param NewsBrickEvent $event */ public function modifyBrick(NewsBrickEvent $event) { $querySettings = $event->getQuerySettings(); $document = $event->getInfo()->getDocument(); $configuration = $this->getDocumentTag($document, '', ''); # crucial: check properly if (!$configuration instanceof Relations) { return; } $elements = $configuration->getElements(); // or whatever Method applies to your Class $querySettings[''] = $elements; $event->setQuerySettings($querySettings); } /** * @param PageSnippet $document * @param string $type * @param string $inputName * @param array $options * * @return \OpenDxp\Model\Document\Tag|null */ protected function getDocumentTag(PageSnippet $document, $type, $inputName, array $options = []) { return $this->tagRenderer->getTag($document, $type, $inputName, $options); } } ``` #### Service registration ```yaml services: App\EventListener\NewsBrickModifierListener: autowire: true autoconfigure: true public: false tags: - { name: kernel.event_subscriber } ``` #### TWIG Create a new File in your app-resource-directory: templates/OpenDxpNewsBundle/areas/news/edit_custom.html.twig and use common opendxp-methods to add your configuration: ```twig
{{ opendxp_your_property_type('', { 'types' : ['object', 'folder'], 'width' : '510px', 'height' : '150px', ... }) }}
``` #### Modify Listing Create a class that extends `\OpenDxp\Bundle\NewsBundle\Model\Entry` and add this method to use your new configuration-values ```php /** * @param DataObject\NewsEntry\Listing $listing * @param array $settings */ protected static function modifyListing($listing, $settings = []) { # for example, add a condition $listing->addConditionParam(''); } ``` --- ## Changelog(News) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [BUGFIX] Handle an empty string `entryType` value like `null` to avoid a false "no permission" error when opening or creating untyped news entries as a non-admin user [#5](https://github.com/open-dxp/news-bundle/pull/5) ### 1.0.1 - [BUGFIX] Fix template namespaces to new structure ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update workflow files [#1](https://github.com/open-dxp/news-bundle/pull/1) --- ## Migrating to OpenDXP(News) ### Migrating from `dachcom-digital/news` to `open-dxp/news-bundle` * **Important:** If you installed `dachcom-digital/news` prior to version 4.0.0, it is highly recommended to update your `NewsEntry` class definition and set `entryType.defaultValue` from `null` to an empty string (`''`). * The default value for this field was changed in [128b355](https://github.com/dachcom-digital/pimcore-news/commit/128b355b48fc0ad94cc87d2ff16859484416b1f9) and can break your application since PHP's strict typing requires this value to be a string (see [EntryTypeManager:getTypeInfo()](../src/Manager/EntryTypeManager.php#L109)) * Renamed Bundle to `OpenDxpNewsBundle` * Changed namespace from `NewsBundle` to `OpenDxp\Bundle\NewsBundle` * Refactored bundle directory structe to match Symfony standard. This includes: * Renaming template directory-/file-structure to be snake_case (rename your extends/overrides!) * Rename your bundle config directory (`var/bundles/NewsBundle`) to `OpenDxpNewsBundle` * Also if there is an existing `config.yml` file in that directory, rename it to `config.yaml` --- ## News Bundle OpenDXP News Bundle. Generate simple [custom entry types](docs/20_EntryTypes.md) like Events, Press or Event. ### Requirements ⚠️⚠️ This extension has reached its end of life and only receives compatibility update. It will not be developed further. ### Installation ```json "require" : { "open-dxp/news-bundle" : "~1.0.0", } ``` Add to bundles.php: ```php // config/bundles.php return [ // ... OpenDxp\NewsBundle\OpenDxpNewsBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpNewsBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\NewsBundle\Migrations'` ### Important to know - The detail url is based on the title for each language. If the detail url field is empty, the title will be transformed to a valid url slug. - The News Bundle will install two classes (`NewsEntry` and `NewsCategory`). If you're going to modify them, please make sure that you're follow our [changelog](CHANGELOG.md) in case we're changing the class structure. Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### Good to know - News can be placed at any place on your website through the news area element. Use it as list, latest or even as a custom layout. - The detail page always stays the same (see static route), no matter where you placed the area element. - It's possible to override the detail url in the news object. ### Extending Entry Object - *Meta Information* Tab: Extend Entries with [classification store](https://docs.opendxp.io/docs/core-framework/Objects/Object_Classes/Data_Types/Classification_Store) data. - *Relations & Settings* Tab: Extend Entries with [Object Bricks](https://docs.opendxp.io/docs/core-framework/Objects/Object_Classes/Data_Types/Object_Bricks). - Configure additional configuration fields with an [eventlistener and twig](./docs/40_CustomConfiguration.md) #### Further Information - [Head Meta Generator](./docs/10_HeadMetaGenerator.md) - [Link Generator](./docs/11_LinkGenerator.md) - [Related Entries Generator](./docs/12_RelatedEntriesGenerator.md) - [The Amazing Entry Types](./docs/20_EntryTypes.md) - [Presets](./docs/30_Presets.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Scheduler) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.1 - [BUGFIX] Fix wrong type for values in settings store ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Unify test infrastructure across bundles [#1](https://github.com/open-dxp/scheduler-bundle/pull/1) --- ## Scheduler Bundle Push scheduled tasks to messenger. ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.0` | `^7.4` | 2025 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/scheduler-bundle": "^1.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\SchedulerBundle\OpenDxpSchedulerBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpSchedulerBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\SchedulerBundle\Migrations'` ### Register Task ```yaml App\Scheduler\MyScheduledTask: tags: - { name: scheduler.task, type: my_scheduled_task } ``` ```php [!NOTE] > this is the recommended way! This bundle detects automatically if you have installed the SEO Bundle. If so, it will disable the request event listener to keep things straight and prevent strategy mixes! Please read [more about seo bundle configuration](./01_SeoBundleUsage.md) and how to configure this bundle if you're using this bundle in combination with the SEO Bundle. ### Standalone Usage Please read [more about standalone configuration](./02_StandaloneUsage.md) and how to configure this bundle if you're using this bundle as a standalone version. --- ## Usage with SEO Bundle ### Bootstrap If the [SEO Bundle](https://github.com/open-dxp/advanced-seo-bundle) has been installed, the Schema Bundle will implement a MetaData Middleware by default. This allows you to create schema blocks within the SEO Workflow. ### I. Simple Usage Example ```yml App\MetaData\Extractor\SchemaDataExtractor: tags: - { name: seo.meta_data.extractor, identifier: my_schema_data_extractor } ``` #### Service ```php getMiddleware('schema_graph'); $graphMiddleware->addTask(function (SeoMetaDataInterface $seoMetadata, Graph $graph) { /** @var Organization $organisation */ $organisation = $graph->getOrCreate(Organization::class); $organisation->name('My Organisation'); $organisation->description('My Organisation Description'); }); } } ``` #### Adding Schema Data As you can see, you don't need to add any data to the SeoMetaData Object. This task will be dispatched by the middleware class itself. After all extractors have been dispatched, a schema block will be added to your meta block. This allows you to add multiple schema information within multiple extractors but only one schema block will be generated! *** ### II. Twig Usage #### Render json-ld data directly in twig templates You're able to render json-ld data in your markup. For this you need to make use of the `json_ld_fragment` twig extension. #### Register Service ```yml App\Schema\Generator\ProductFragmentGenerator: autowire: true tags: - { name: schema.fragment_generator, alias: product } ``` #### Build Service ```php name($product->getName()) ->sku($product->getSku()); } } ``` #### Add Filter to Object ```twig

json ld fragment for object

{% set object = opendxp_object(41) %} {{ object|json_ld_fragment }}
``` #### Notes Create a simple symfony service if you need to do things twice! --- ## Standalone Usage > [!NOTE] > This does not work if you have installed the [SEO Bundle](https://github.com/open-dxp/advanced-seo-bundle)! > Read more about it [here](./00_Usage.md)! *** ### Bootstrap The Schema Bundles allows you to build schema blocks in two sections: - based on request: add ld+json data to head based on request - based on element: add ld+json data to your markup by using the `json_ld` twig helper based on given element ### I. Simple Usage Example ```yml App\Schema\Generator\KnowledgeGraphGenerator: autowire: true tags: - { name: schema.generator, alias: knowledge_graph } ``` #### Service ```php 'My Business Name', 'email' => 'info@mybusiness.com' ]; $graph ->organization() ->name($myBusiness['name']); } public function generateForElement($element): ?BaseType { return null; } } ``` *** ### II. Extended Usage Example Use the `Graph` Element to join multiple services. #### Register Service ```yml App\Schema\Generator\OrganizationGenerator: autowire: true tags: - { name: schema.generator, alias: organization } App\Schema\Generator\ProductGenerator: autowire: true tags: - { name: schema.generator, alias: product } ``` #### Build Services ##### OrganizationGenerator ```php organization() ->name('My awesome Company'); } public function generateForElement($element): ?BaseType { // return null since we do not support requests return null; } } ``` ##### ProductGenerator ```php attributes->has('product-id'); } public function supportsElement($element): bool { return false; } public function generateForRequest(Graph $graph, Request $request, array &$schemaBlocks): void { $graph ->product() ->name('My cool Product') ->brand($graph->organization()); } public function generateForElement($element): ?BaseType { // return null since we do not support requests return null; } } ``` *** ### III. Twig Usage Example #### Render json-ld data directly in twig templates You're able to render json-ld data in your markup. For this you need to make use of the `json_ld` twig extension. #### Register Service ```yml App\Schema\Generator\ProductGenerator: autowire: true tags: - { name: schema.generator, alias: product } ``` #### Build Service ```php name($product->getName()) ->sku($product->getSku()); } } ``` #### Add Filter to Object ```twig

json ld for object

{% set object = opendxp_object(41) %} {{ object|json_ld }}
``` --- ## Changelog(Schema) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [BUGFIX] Update extension check in `OpenDxpSchemaExtension` to `opendxp_advanced_seo`. [#2](https://github.com/open-dxp/schema-bundle/pull/2) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update/Fix workflows [#1](https://github.com/open-dxp/schema-bundle/pull/1) --- ## Migrating to OpenDXP(Schema) ### Migrating from `dachcom-digital/schema` to `open-dxp/schema-bundle` * Renamed bundle to `OpenDxpSchemaBundle` * Moved bundle to new namespace: `OpenDxp\Bundle\SchemaBundle` * Renamed top-level config node to `opendxp_schema` --- ## Schema Bundle Schema.org type builder and ld+json generator for opendxp. This bundle requires the `spatie/schema-org` package. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 09.02.2026 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/schema-bundle" : "~1.0.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\SchemaBundle\OpenDxpSchemaBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpSchemaBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\SchemaBundle\Migrations'` ### Output ![Schema generators printing ld+json in the head, in the SEO meta block and in a template](./docs/img/schema_output.png) > [!NOTE] > Test your output on https://search.google.com/structured-data/testing-tool ### Further Information - [Usage](docs/00_Usage.md) - [Use it with SEO Bundle](docs/01_SeoBundleUsage.md) (Recommended) - [Use it in Standalone Mode](docs/02_StandaloneUsage.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Setup(Social-data) After you have enabled this Bundle, there are some global steps to define. #### I. Data Class If you don't have any opendxp data object to manage your social posts, you need to create it first. After that, you need to tell SocialDataBundle about it: ```yaml # config/packages/social_data.yaml opendxp_social_data: social_post_data_class: SocialPost ``` The Data Class needs to provide some predefined fields and needs to implement the `SocialPostInterface`. Just import the preconfigured [SocialPost Definition](https://github.com/open-dxp/social-data-bundle/blob/1.x/config/install/class/SocialPost.class.json) to kickstart your data class. You can check the Health state by visiting the Social Data Menu `"Settings"` => `"Social Data"` => `"Connector Configuration"`. Watch out for this information: ![The setup has five steps, from the data class to the walls](./img/setup_steps.png) #### II. The Connector Configuration This is the final step: Setup your Connectors. Each connector has its own configuration and strategies. Lets checkout the [Connector](./10_Connectors.md) Guide to learn how to use and install them. #### III. Enable dynamic Fetch Mode ##### Via CronJob To crawl periodically your newest social data, you need to install a new cron task. In this example we dispatch our processor every six hours. You can of course adjust this to your needs, but you should always keep in mind that limit-timeouts may occur if the crawl intervals are very short. ```bash 0 */6 * * * /usr/bin/php PATH/TO/bin/console social-data:fetch:social-posts ``` ##### Via Maintenance If you don't want to install additional cronjobs, you may want to enable the import process via maintenance task. This task is **disabled by default**, so you need to enable it first: ```yaml # config/packages/social_data.yaml opendxp_social_data: maintenance: fetch_social_post: enabled: true # enable task, default false interval_in_hours: 3 # dispatch every 3 hours, default 6 ``` #### IV. Optional: Clean up old posts Sometimes you may want to remove outdated posts. It's possible to delete posts (and optionally also the poster) by maintenance task. This task is **disabled by default**, so you need to enable it first: ```yaml # config/packages/social_data.yaml opendxp_social_data: maintenance: clean_up_old_posts: enabled: true # enable task, default false expiration_days: 10 # delete posts older than 10 days, default 150 delete_poster: true # also deletes poster asset if given, default false ``` #### V. Configure some Walls and Feeds After you have successfully configured your required connectors you're now able to finally add some walls. Ready? Read more about it [here](./11_WallsAndFeeds.md) *** ### Available Connector - [Facebook](https://github.com/open-dxp/social-data-facebook-connector) - [Instagram](https://github.com/open-dxp/social-data-instagram-connector) - [Youtube](https://github.com/open-dxp/social-data-youtube-connector) --- ## Connectors(Social-data) ![A connector is installed, enabled and connected in three stages](./img/connector_stages.png) ### Note! This bundle **does not** provide any connectors by default. You need to install them separately! Checkout all available connectors in the [list below](#available-connectors) to learn how to install them. *** Every connector has at least two stages: `Install` and `Enabled`. ### Installation After pressing the Install button, the SocialDataBundle will generate a database entry, a so called "Connector Engine". This engine stores additional configuration fields, depending on each connector. > **Warning:** If you want to uninstall a connector, all related data will be lost! ### Enabling/Disabling Enable or disable a connector. There is no data loss if a connector gets disabled. ### Connect Not every Connector requires the connection feature. The [Facebook Connector](https://github.com/open-dxp/social-data-facebook-connector) for example, requires a valid access token which will be created, after you hit this button. *** ### Available Connectors - [Facebook](https://github.com/open-dxp/social-data-facebook-connector) - [Instagram](https://github.com/open-dxp/social-data-instagram-connector) - [Youtube](https://github.com/open-dxp/social-data-youtube-connector) --- ## Walls and Feeds ![Social post import filling a wall with two feeds](./img/walls_and_feeds.png) ### Walls Each Wall represents a set of feeds. You can add one or more wall and each wall can hold one or more feeds. #### Configuration | Name | Description | |----------------------|------------------------------------------------------------------------------------------------------------| | `name` | Set a Name for your Wall | | `Wall Tags` | Set some tags to use them later in your frontend query. | | `Data Storage Path` | Add a DataObject-Folder via Drag'n'Drop to define a storage folder. New social posts will be stored there | | `Asset Storage Path` | Add a Asset-Folder via Drag'n'Drop to define a storage folder. New social post assets will be stored there | | `Statistics` | Get some statistics about wall-related social posts | | `Logs` | All related logs will be stored there | | `Feeds` | Add at least one feed | #### Dispatch Processor There are two ways to execute the import process. ##### Command To dispatch all wall builds at once, use this command: ```bash php bin/console social-data:fetch:social-posts ``` To dispatch a specific wall build only, use this command (723 would be the wallId): ```bash php bin/console social-data:fetch:social-posts -w 723 ``` ##### Manually On each wall panel you'll find a button in the top right corner: `"Dispatch Social Post Import for this Wall"`. Click on it to execute the build process for this very specific wall only. *** ### Feeds Every Feed contains some system fields but also a connector related configuration section. #### Configuration | Name | Description | |-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------| | `Feed Tags` | Set some tags to use them later in your frontend query. | | `Store Media as Assets` | If checked, the SocialDataBundle will store a poster assets which needs to be pre-populated by each connector (`posterUrl`) | | `Immediately publish Social Post` | If checked, every new imported post will be published instantly | --- ## Events(Social-data) ### Available Events ##### SOCIAL_POST_BUILDER_FETCH_CONFIGURE Use this event to interact with a given `fetch` configuration by using the `SocialPostBuildConfigureEvent` event object. ##### SOCIAL_POST_BUILDER_FETCH_POST Use this event to interact with `fetched` data by using the `SocialPostBuildEvent` event object. ##### SOCIAL_POST_BUILDER_FILTER_CONFIGURE Use this event to interact with a given `filter` configuration by using the `SocialPostBuildConfigureEvent` event object. ##### SOCIAL_POST_BUILDER_FILTER_POST Use this event to interact with `filtered` data by using the `SocialPostBuildEvent` event object. ##### SOCIAL_POST_BUILDER_TRANSFORM_CONFIGURE Use this event to interact with a given `transform` configuration by using the `SocialPostBuildConfigureEvent` event object. ##### ### SOCIAL_POST_BUILDER_TRANSFORM_POST Use this event to interact with `transformed` data by using the `SocialPostBuildEvent` event object. *** ### Example Event Handling ```yaml services: App\EventListener\SocialDataListener: autowire: true tags: - { name: kernel.event_subscriber } ``` ```php 'onFetchConfigure', SocialDataEvents::SOCIAL_POST_BUILDER_FETCH_POST => 'onFetchPost', SocialDataEvents::SOCIAL_POST_BUILDER_FILTER_CONFIGURE => 'onFilterConfigure', SocialDataEvents::SOCIAL_POST_BUILDER_FILTER_POST => 'onFilterPost', SocialDataEvents::SOCIAL_POST_BUILDER_TRANSFORM_CONFIGURE => 'onTransformConfigure', SocialDataEvents::SOCIAL_POST_BUILDER_TRANSFORM_POST => 'onTransformPost', ]; } public function onFetchConfigure(SocialPostBuildConfigureEvent $event) { $options = $event->getOptions(); $event->setOption('aConnectorDefinedOptionToOverwrite', 'NEW VALUE'); } public function onFetchPost(SocialPostBuildEvent $event) { /** @var FetchData $data */ $data = $event->getData(); //$data->setFetchedEntities([]); } public function onFilterConfigure(SocialPostBuildConfigureEvent $event) { $options = $event->getOptions(); } public function onFilterPost(SocialPostBuildEvent $event) { $data = $event->getData(); } public function onTransformConfigure(SocialPostBuildConfigureEvent $event) { $options = $event->getOptions(); } public function onTransformPost(SocialPostBuildEvent $event) { $data = $event->getData(); $transferredData = $data->getTransferredData(); $transformedElement = $data->getTransformedElement(); } } ``` --- ## Frontend Usage Basically, this is the easiest part because you're dealing with opendxp objects and that's something you may already know. ### Simple Queries There are some simple queries to fetch social posts by known ids which are helpful but are limited in their flexibility. For example, if a feed gets deleted and re-added, your id based query won't work anymore. ### Example A There are several fetch methods available: ```php socialPostRepository = $socialPostRepository; } public function defaultAction(Request $request): Response { // get posts by feed id $posts = $this->socialPostRepository->findBySocialType('facebook', false); // get posts by wall id $posts = $this->socialPostRepository->findByWallId(9, false); // get posts by feed id $posts = $this->socialPostRepository->findByFeedId(89, false); // get posts by social type and wall id $posts = $this->socialPostRepository->findBySocialTypeAndWallId('facebook', 9, false); // get by social type and feed id $posts = $this->socialPostRepository->findBySocialTypeAndFeedId('facebook', 89, false); // get by social type and wall id and feed id $posts = $this->socialPostRepository->findBySocialTypeAndWallIdAndFeedId('facebook', 9, 89, false); return $this->renderTemplate('Social/default.html.twig', ['posts' => $posts]); } } ``` ### Example B If you want to modify the listing according your needs, you could fetch the listing only: ```php socialPostRepository = $socialPostRepository; } public function defaultAction(Request $request): Response { // get post listing by wall id $postListing = $this->socialPostRepository->findByWallIdListing(9, false); $postListing->addConditionParam('myField = 42'); $posts = $postListing->getObjects(); // of course all other methods from example A are also available within listing context return $this->renderTemplate('Social/default.html.twig', ['posts' => $posts]); } } ``` ### Example C Only use the `getFeedPostJoingListing()` method to create your custom query: ```php socialPostRepository = $socialPostRepository; } public function defaultAction(Request $request): Response { $postListing = $this->socialPostRepository->getFeedPostJoinListing(); $postListing->addConditionParam('myField = 42'); $posts = $postListing->getObjects(); return $this->renderTemplate('Social/default.html.twig', ['posts' => $posts]); } } ``` ### Complex Queries Within complex queries, you're allowed to query for `wallTags` and `feedTags` without any id-based relation with different mix&match patterns. ```php socialPostRepository = $socialPostRepository; } public function defaultAction(Request $request): Response { // get posts with wall tags $wallTagPosts = $this->socialPostRepository->findByTag(['my_wall_tag']); // get posts with feed tags $feedTagPosts = $this->socialPostRepository->findByTag([], ['my_feed_tag']); // get posts with wall and feed tags $wallAndFeedTypes = $this->socialPostRepository->findByTag(['my_wall_tag'], ['my_feed_tag', 'my_other_feed_tag']); // get posts with social type and wall tags $socialWallTagTypes = $this->socialPostRepository->findSocialTypeAndByTag('instagram', ['my_wall_tag']); // get posts with social type and wall and feed tags $socialWallAndFeedTagTypes = $this->socialPostRepository->findSocialTypeAndByTag('instagram', ['my_wall_tag'], ['my_feed_tag']); return $this->renderTemplate('Social/default.html.twig', []); } } --- ## Logging(Social-data) ![Import log stored in its own table and shown in the admin](./img/logging.png) The OpenDxp\Bundle\SocialDataBundle comes with a dedicated log table. ### Modify Clean Up Task Expiration Days Logs will be removed after `30 days`. Change the expiration via configuration: ```yaml opendxp_social_data: maintenance: clean_up_logs: expiration_days: 10 #delete logs older than 10 days, default 30 ``` ### Disable Clean Up Task To disable the complete clean up task, you need to define it via configuration: ```yaml opendxp_social_data: maintenance: clean_up_logs: enabled: false # disable task, default true ``` ### Custom Clean-Up #### Wall TBD #### Global Log Flush There is also a global log flush workflow. Go to the global connector configuration panel and hit the "Flush all logs" button at the left top corner. > Be aware this will truncate the logs tables and can't be undone! --- ## Custom Connector It's very easy to add your own connector. In fact there are two services, two configuration classes and two form classes to define. To get started, you need register them first: ```yaml services: ## Post Builder App\SocialData\Connector\MyConnectorType\Builder\SocialPostBuilder: ~ ## Definition App\SocialData\Connector\MyConnectorType\ConnectorDefinition: tags: - { name: social_data.connector_definition, identifier: my_connector_type, socialPostBuilder: App\SocialData\Connector\MyConnectorType\Builder\SocialPostBuilder } ``` Now you need to add them to the global register: ```yaml opendxp_social_data: social_post_data_class: SocialPost available_connectors: - connector_name: my_connector_type ``` After that you're already able to add your connector in the configuration panel in backend. *** ### Service Classes #### Connector Definition The `Connector Definition` presents all connector configuration. This class needs to implement the `ConnectorDefinitionInterface`. | Method | Description |------|----------------------| | `isOnline` | TBD | | `beforeEnable` | TBD | | `beforeDisable` | TBD | | `isAutoConnected` | TBD | | `isConnected` | TBD | | `connect` | TBD | | `disconnect` | TBD | | `needsEngineConfiguration` | TBD | | `getEngineConfigurationClass` | TBD | | `getFeedConfigurationClass` | TBD | | `getEngineConfiguration` | TBD | ##### Configuration Classes The `Configuration Classes` presents all connector configuration. You need two of them: The Engine configuration and Feed configuration class. ###### Engine Configuration The engine configuration class needs to implement the `ConnectorEngineConfigurationInterface`. | Required Methods | Description |------|----------------------| | `static function getFormClass` | Returns the configuration form type | ###### Feed Configuration THe feed configuration class needs to implement the `ConnectorFeedConfigurationInterface`. | Required Methods | Description |------|----------------------| | `static function getFormClass` | Returns the configuration form type | *** #### Social Post Builder The social post builder class needs to implement the `SocialPostBuilderInterface`. | Method | Description |------|----------------------| | `configureFetch` | TBD | | `fetch` | TBD | | `configureFilter` | TBD | | `filter` | TBD | | `configureTransform` | TBD | | `transform` | TBD | --- ## Testing(Social-data) The bundle ships the classes to test a connector or a project with social posts, under `OpenDxp\Bundle\SocialDataBundle\Test`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Setup `InstallSocialPostClass` installs the class `SocialPost` of the bundle before the first test. Register it in `phpunit.xml.dist`, after the extensions of DAMA and Foundry: ```xml ``` The test application names the class in its configuration: ```yaml opendxp_social_data: social_post_data_class: SocialPost available_connectors: - connector_name: my_connector_type ``` ### Building posts without the platform `Connectors::fetching()` makes the connector return the given entities instead of fetching posts from its platform. The social post builder of the connector still filters and transforms them. The processor then builds and saves the posts as it does in production. ```php use OpenDxp\Bundle\SocialDataBundle\Processor\SocialPostBuilderProcessor; use OpenDxp\Bundle\SocialDataBundle\Repository\SocialPostRepositoryInterface; use OpenDxp\Bundle\SocialDataBundle\Test\Connectors; use OpenDxp\Bundle\SocialDataBundle\Test\Factory\FeedFactory; use OpenDxp\TestFoundation\Container; use SocialData\Connector\Youtube\Model\EngineConfiguration; it('builds a social post from a fetched video', function () { $engineConfiguration = new EngineConfiguration(); $engineConfiguration->setApiKey('api-key'); $feed = FeedFactory::new() ->forConnector('youtube', $engineConfiguration) ->create(); Connectors::fetching('youtube', [ [ 'id' => 'aqz-KE-bpKQ', 'title' => 'A ride through the Alps', ], ]); Container::get(SocialPostBuilderProcessor::class)->process( true, $feed->getWall()->getId(), ); $posts = Container::get(SocialPostRepositoryInterface::class)->findByFeedId($feed->getId()); expect($posts)->toHaveCount(1); }); ``` The entities have the shape that the method `fetch()` of the connector returns. ### Test API | Factory | Creates | |--------------------------|-----------------------------------------------------------------------------------------------| | `WallFactory` | A wall with a data object folder for its posts and an asset folder for their media. | | `FeedFactory` | A feed on a wall. `forConnector()` sets the connector and the configuration of its engine. | | `ConnectorEngineFactory` | The enabled engine of a connector. `forConnector()` sets the connector and the configuration. | --- ## Changelog(Social-data) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [ENHANCEMENT] Add classes to test connectors and projects, see [Tests](docs/40_Tests.md) - [CHORE] Remove the deprecated `nullable` of the join columns of the tags and pass the columns of a select one by one - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update workflows [#1](https://github.com/open-dxp/social-data-bundle/pull/1) --- ## Social Data Bundle This Bundles allows you to load social data from different networks like Facebook, Instagram or YouTube. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 18.02.2026 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/social-data-bundle" : "~1.0.0", } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\SocialDataBundle\OpenDxpSocialDataBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpSocialDataBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\SocialDataBundle\Migrations'` ### Usage This Bundle needs some preparation. Please check out the [Setup](docs/00_Setup.md) guide first. ### Further Information - [Setup](docs/00_Setup.md) - [Connectors](./docs/10_Connectors.md) - [Facebook](https://github.com/open-dxp/social-data-facebook-connector) - [Instagram](https://github.com/open-dxp/social-data-instagram-connector) - [Youtube](https://github.com/open-dxp/social-data-youtube-connector) - [Walls And Feeds](docs/11_WallsAndFeeds.md) - [Events](docs/12_Events.md) - [Frontend Usage](docs/13_FrontendUsage.md) - [Logging](docs/20_Logging.md) - [Custom Connector](docs/30_CustomConnector.md) - [Testing](docs/40_Tests.md) ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Social-data-facebook-connector) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Test the building of social posts with the test classes of `open-dxp/social-data-bundle` - [CHORE] Require `open-dxp/social-data-bundle` ^1.1 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [CHORE] Rename 'pimcore' config directories to 'opendxp'. [#2](https://github.com/open-dxp/social-data-facebook-connector/pull/2) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update workflows [#1](https://github.com/open-dxp/social-data-facebook-connector/pull/1) --- ## Social Data Facebook Connector This Connector allows you to fetch social posts from Facebook. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 20.02.2026 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/social-data-bundle" : "~1.0.0", "open-dxp/social-data-facebook-connector" : "~1.0.0" } ``` Add Bundle to `bundles.php`: ```php return [ SocialData\Connector\Facebook\SocialDataFacebookConnectorBundle::class => ['all' => true], ]; ``` #### Install Assets ```bash bin/console assets:install public --relative --symlink ``` ### Enable Connector ```yaml # config/packages/social_data.yaml opendxp_social_data: social_post_data_class: SocialPost available_connectors: - connector_name: facebook ``` #### Set Cookie SameSite to Lax Otherwise, the oauth connection won't work. > If you have any hints to allow processing an oauth connection within `strict` mode, > please [tell us](https://github.com/open-dxp/social-data-facebook-connector/issues). ```yaml framework: session: cookie_samesite: 'lax' ``` ### Facebook Backoffice First, you need to create a facebook app. Add `https://YOURDOMAIN/admin/social-data/connector/facebook/check` to the `Valid OAuth Redirect URIs` in facebook backoffice. ### Connector Configuration Now head back to the backend (`System` => `Social Data` => `Connector Configuration`) and checkout the facebook tab. - Click on `Install` - Click on `Enable` - Before you hit the `Connect` button, you need to fill you out the Connector Configuration. After that, click "Save". - Click `Connect` | Name | Description | |--------------|---------------------------------| | `App ID` | The ID of your Facebook app | | `App Secret` | The secret of your Facebook app | ### Connection ![Facebook connection from the Connect button to the saved access token](./docs/img/connection.png) This will guide you through the facebook token generation. After hitting the "Connect" button, **a popup** will open to guide you through facebook authentication process. If everything worked out fine, the connection setup is complete after the popup closes. Otherwise, you'll receive an error message. You may then need to repeat the connection step. ### Feed Configuration ![Facebook feed with page ID and limit feeding posts into a wall](./docs/img/feed_configuration.png) | Name | Description | |-----------|-------------------------------------------------------------------------------| | `Page ID` | Defines which page entries should be imported | | `Limit` | Define a limit to restrict the amount of social posts to import (Default: 50) | ### Extended Connector Configuration Normally you don't need to modify connector (`connector_config`) configuration, so most of the time you can skip this step. However, if you need to change some core setting of a connector, you're able to change them of course. ```yaml # config/packages/social_data.yaml opendxp_social_data: available_connectors: - connector_name: facebook connector_config: api_connect_permission: ['pages_show_list', 'pages_read_engagement', 'pages_read_user_content'] # default value ``` *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Social-data-instagram-connector) ### 1.1.1 - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Test the building of social posts with the test classes of `open-dxp/social-data-bundle` - [CHORE] Require `open-dxp/social-data-bundle` ^1.1 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [CHORE] Rename 'pimcore' config directories to 'opendxp'. [#2](https://github.com/open-dxp/social-data-instagram-connector/pull/2) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Add workflow definitions [#1](https://github.com/open-dxp/social-data-instagram-connector/pull/1) --- ## Social Data Instagram Connector This Connector allows you to fetch social posts from Instagram. > [!IMPORTANT] > The [Instagram Basic Display API](https://developers.facebook.com/blog/post/2024/09/04/update-on-instagram-basic-display-api) has been shut down. > Personal Instagram accounts are no longer supported. Therefore this extension **only works with Creator or Business Instagram accounts**! #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 20.02.2026 | Feature Branch | 1.x | ### Installation ```json "require" : { "open-dxp/social-data-bundle" : "~1.0.0", "open-dxp/social-data-instagram-connector" : "~1.0.0" } ``` #### API via Facebook Login If you want to use the facebook api, you also have to install the `league/oauth2-facebook` extension: ```json "require" : { "league/oauth2-facebook": "^2.0" } ``` Add Bundle to `bundles.php`: ```php return [ SocialData\Connector\Instagram\SocialDataInstagramConnectorBundle::class => ['all' => true], ]; ``` #### Install Assets ```bash bin/console assets:install public --relative --symlink ``` ### Enable Connector ```yaml # config/packages/social_data.yaml opendxp_social_data: social_post_data_class: SocialPost available_connectors: - connector_name: instagram ``` #### Set Cookie SameSite to Lax Otherwise, the oauth connection won't work. > If you have any hints to allow processing an oauth connection within `strict` mode, > please [tell us](https://github.com/open-dxp/social-data-instagram-connector/issues). ```yaml framework: session: cookie_samesite: 'lax' ``` ### Setup App Some hints to set up your instagram app #### Instagram API with Instagram Login - Create Business App - Add "Instagram" Product - Add `https://YOURDOMAIN/admin/social-data/connector/instagram/check` in `Instagram => API setup with Instagram business login => 3. Set up Instagram business login => Business login settings` - Select `Instagram API with Instagram Login` and store `Instagram app ID` and `Instagram app secret` in the opendxp connector section #### Instagram API with Facebook Login - Create Business App - Select `Instagram API with Facebook Login` and store `App-ID` and `App Secret` in the opendxp connector section - Add "Facebook Login for Business" Product - Add `https://YOURDOMAIN/admin/social-data/connector/instagram/check` in `Valid OAuth Redirect URIs` in section "Settings" ### Connector Configuration Now head back to the backend (`System` => `Social Data` => `Connector Configuration`) and checkout the instagram tab. - Click on `Install` - Click on `Enable` - Before you hit the `Connect` button, you need to fill you out the Connector Configuration. After that, click "Save". - Click `Connect` | Name | Description | |--------------|-------------------------------------------------------------------------------------| | `App ID` | The ID of your Instagram app | | `App Secret` | The secret of your Instagram app | | `API Type` | Choose `Instagram API with Instagram Login` or `Instagram API with Facebook Login` | ### Connection ![Instagram connection from the Connect button to the saved access token](./docs/img/connection.png) This will guide you through the instagram token generation. After hitting the "Connect" button, a popup will open to guide you through instagram authentication process. If everything worked out fine, the connection setup is complete after the popup closes. Otherwise, you'll receive an error message. You may then need to repeat the connection step. ### Feed Configuration ![Instagram feed with account ID and limit feeding posts into a wall](./docs/img/feed_configuration.png) | Name | Description | |--------------|-------------------------------------------------------------------------------| | `Account ID` | Defines which Instagram account is imported (only with the Facebook Login) | | `Limit` | Define a limit to restrict the amount of social posts to import (Default: 50) | ### Extended Connector Configuration Normally you don't need to modify connector (`connector_config`) configuration, so most of the time you can skip this step. However, if you need to change some core setting of a connector, you're able to change them of course. ```yaml # config/packages/social_data.yaml opendxp_social_data: available_connectors: - connector_name: instagram connector_config: api_connect_permission_instagram_login: ['instagram_business_basic'] # default value api_connect_permission_facebook_login: ['instagram_basic', 'pages_read_engagement', 'pages_show_list', 'business_management'] # default value ``` *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Changelog(Social-data-youtube-connector) ### 1.1.1 - [BUGFIX] A feed without a limit fetches 50 videos instead of one - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.1.0 - [CHORE] Test the building of social posts with the test classes of `open-dxp/social-data-bundle` - [CHORE] Require `open-dxp/social-data-bundle` ^1.1 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [CHORE] Rename 'pimcore' config directories to 'opendxp'. [#2](https://github.com/open-dxp/social-data-youtube-connector/pull/2) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update workflows [#1](https://github.com/open-dxp/social-data-youtube-connector/pull/1) --- ## Social Data YouTube Connector This Connector allows you to fetch social posts from YouTube. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.0` | `7.4` | 20.02.2026 | Feature Branch | 1.x | ### Installation #### I. Add Dependency ```json "require" : { "open-dxp/social-data-bundle" : "~1.0.0", "open-dxp/social-data-youtube-connector" : "~1.0.0" } ``` Add Bundle to `bundles.php`: ```php return [ SocialData\Connector\Youtube\SocialDataYoutubeConnectorBundle::class => ['all' => true], ]; ``` #### Install Assets ```bash bin/console assets:install public --relative --symlink ``` ### Enable Connector ```yaml # config/packages/social_data.yaml opendxp_social_data: social_post_data_class: SocialPost available_connectors: - connector_name: youtube ``` ### YouTube Backoffice Some hints to set up your YouTube app: - Create API Key on https://console.cloud.google.com/apis/credentials - Enable YouTube API v3: https://console.developers.google.com/apis/api/youtube.googleapis.com/overview ### Connector Configuration Now head back to the backend (`System` => `Social Data` => `Connector Configuration`) and checkout the YouTube tab. - Click on `Install` - Click on `Enable` - Fill out the `API Key` and click "Save" ### Connection YouTube is auto connected after a valid API Key has been set. ### Feed Configuration ![YouTube feed with fetch type, value and limit feeding videos into a wall](./docs/img/feed_configuration.png) | Name | Description | |--------------|-------------------------------------------------------------------------------| | `Fetch Type` | Choose the fetch type. Values: `Channel ID` or `Playlist ID` | | `Value` | The channel id or playlist id | | `Limit` | Define a limit to restrict the amount of social posts to import (Default: 50) | ### Third-Party Requirements To use this connector, this bundle requires some additional packages: - [google/apiclient](https://github.com/googleapis/google-api-php-client): Required for Google API *** ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © 2026 OpenDXP — GPLv3 --- ## Usage(Toolbox) Some important advices if you're going to use this bundle in your project. ### Area Brick ![Area brick toolbar with the generated Toolbox group and a Project group](./img/area_brick_groups.png) The Toolbox Bundle will help you to display area bricks with some nice additions. #### Enable Bricks Every preconfigured brick needs to be enabled: ```yaml opendxp_toolbox: enabled_core_areas: - accordion - anchor - columns - container - content - download - gallery - googleMap - headline - iFrame - image - linkList - parallaxContainer - parallaxContainerSection - separator - slideColumns - snippet - spacer - teaser - video ``` ##### Area Brick Configuration **Important!** Make sure that every `opendxp_areablock` in your project implements the `toolbox_areablock_config()` element. If you miss this, the toolbar will get messy. ```twig
{# choose a project wide unique name to dis-/allow elements in your areablock through the toolbox configuration (see section "allow/disallow elements" below #} {{ opendxp_areablock('mainContentBlock', toolbox_areablock_config('mainContentBlock')) }}
``` ### Toolbar Configuration Of course, you're able to extend/modify the toolbar configuration: ```yaml opendxp_toolbox: area_block_configuration: toolbar: width: 200 buttonWidth: 200 buttonMaxCharacters: 40 controlsAlign: 'top' controlsTrigger: 'hover' # define custom groups. Note: The "toolbox" group will be generated automatically. groups: - name: Project # optional, set sorting to "manually" to respect given order, otherwise sorting will be alphabetically sorting: !php/const OpenDxp\Bundle\ToolboxBundle\Manager\AreaManagerInterface::BRICK_GROUP_SORTING_MANUALLY elements: - your_custom_area_brick ``` ### Allow/Disallow Elements ##### Globally You're able to disable editables completely: ```yaml opendxp_toolbox: areas: accordion: enabled: false ``` If you want to disable any area from third party bundles (for example the members brick) just use their brick id to disable them: ```yaml areas: members_login: enabled: false ``` ##### In Snippets Use the `snippet_areablock_restriction` config node to disable bricks in specific snippets. ```yaml # define which elements should not appear in snippet documents opendxp_toolbox: snippet_areablock_restriction: snippet_c: disallowed: - parallaxContainer - teaser - container - snippet - accordion - anchor - container - teaser accordion: allowed: # if "allowed" is configured the "disallowed" node will be ignored - teaser - download ``` ##### In Area-Blocks Use the `areablock_restriction` config node to disable bricks in specific areas. **Example** ```yaml opendxp_toolbox: areablock_restriction: container: allowed: # if "allowed" is configured the "disallowed" node will be ignored - container - parallaxContainer columns: disallowed: - container - parallaxContainer mainContentBlock: #this is a project related areablock example, see section "Area Brick Configuration" above. disallowed: - container - yourCustomBrick ``` --- ## Genius(Toolbox) The Content Crafter assistant can fill Toolbox bricks. This page lists what Toolbox registers for it. The integration is loaded only where the Content Crafter bundle is installed. - [Editable types](#editable-types) - [The Google Map takes addresses](#the-google-map-takes-addresses) - [The video brick and its lightbox](#the-video-brick-and-its-lightbox) - [Register an editable type of your own](#register-an-editable-type-of-your-own) - [Ask a tool without the chat](#ask-a-tool-without-the-chat) ### Editable types Two editable types, in `src/ContentCrafter/EditableType/`. Content Crafter already reads and writes the areas of a page, and the bricks it lays out are mostly ordinary editables the core knows: a headline, an image, a wysiwyg, a link. These two are Toolbox's own shapes and would otherwise be left as they are. | editable type | supports the editable | is | |-------------------------|-----------------------|----------------------------------------------| | `GoogleMapEditableType` | `googlemap` | a list of addresses | | `VhsEditableType` | `vhs` | the core `VideoEditableType` plus a lightbox | The `list_area_bricks` tool lists the bricks of a page and the values each brick takes. ### The Google Map takes addresses The editable looks the coordinates up itself when the page is saved, so the value is the place as it would be written on an envelope and nothing else. ```json [{"title": "Head office", "street": "Bahnhofstrasse 1", "zip": "8001", "city": "Zurich", "country": "Switzerland"}] ``` `title`, `street`, `zip`, `city`, `country` and `hideInfoWindow` are the whole set of keys. A place without a `city` is refused, because there is nothing to look up, and a key that is not one of the six is refused by name rather than dropped. `"hideInfoWindow": true` keeps that one marker's bubble shut until it is clicked. The brick's own settings are separate from the places and are written along with them: `map_zoom`, `map_type` and `iw_on_init`, see [Google Maps Element](22_GoogleMapsElement.md). ### The video brick and its lightbox `VhsEditableType` extends the core `VideoEditableType` and adds one key, so the video is named the same way as anywhere else. ```json {"type": "asset", "id": 12} {"type": "youtube", "url": "https://..."} ``` A `poster` image id, a `title` and a `description` may come along. `"showAsLightbox": true` opens the video over the page instead of playing it in place. Which sources a `type` may name is the core list unless the editable's own config narrows it with `allowedTypes`, see [Vhs Element](21_VhsElement.md). ### Register an editable type of your own A brick with a shape of its own needs an `EditableTypeInterface` implementation. Where the shape is a core editable plus one setting, extend that core type and add your key to `describeKeys()` and one clause to `describe()`, the way `VhsEditableType` does. The interface and the `ResolvedSetting` refusals are written out in [Add an editable type to page content](https://docs.opendxp.io/docs/bundles/content-crafter/extending/Editable_Types). ### Ask a tool without the chat The Content Crafter workbench runs a tool against this installation under a named backend user and without a model call. It ships with Content Crafter, so run it from that bundle's checkout. ```bash php workbench/bin/tool.php list_area_bricks --user=admin --arguments='{"documentId":19}' ``` See [Debugging](https://docs.opendxp.io/docs/bundles/content-crafter/Debugging). --- ## Custom Bricks If you want to have full control about your area brick, create a [default brick](./10_CustomBricks.md#default-brick). If you just want to create a simple brick, create a [simple brick](./10_CustomBricks.md#simple-brick). With simple bricks you don't have to create any php classes at all but. - [Default Brick](./10_CustomBricks.md#default-brick) - [Simple Brick](./10_CustomBricks.md#simple-brick) - [Bricks without Editables (No Config Dialog)](./10_CustomBricks.md#bricks-without-editables-no-config-dialog) - [Bricks with tabbed config dialog](./10_CustomBricks.md#tabbed-config-dialog) ### Default Brick There are three simple steps to create a custom brick: 1. Add this configuration to `/config/packages/toolbox.yaml`: ```yaml services: App\Document\Areabrick\MyBrick\MyBrick: parent: OpenDxp\Bundle\ToolboxBundle\Document\Areabrick\AbstractAreabrick tags: - { name: toolbox.area.brick, id: my_brick } opendxp_toolbox: areas: # that's the name of your brick. my_brick: config_elements: title1: type: input title: That's a Title description: Lorem Ipsum # default config for input # see: https://docs.opendxp.io/docs/core-framework/Documents/Editables/Input#configuration config: ~ title2: type: input title: That's also a Title description: Lorem Ipsum config: ~ ``` 2. Add the area class to `App/Document/Areabrick/MyBrick/MyBrick.php`: ```php getTemplateDirectoryName(), $this->getTemplateSuffix()); } public function getName():string { return 'My Brick'; } public function getDescription():string { return 'My Brick'; } public function getIcon():string { return '/static/areas/my-brick/icon.svg'; } } ``` 3. Add the view to `/templates/areas/my-brick/view.html.twig`: ```twig

{{ opendxp_input('title1').data }}

{{ opendxp_input('title2').data }}

``` That's it. If you want to refresh the permission table you also need to execute the `bin/console cache:clear` command. *** ### Simple Brick Two steps to create a simple brick: 1. Add this configuration to `/config/packages/toolbox.yaml`: ```yaml services: # this is the fastest way to create a simple brick. # template needs to be located in /template/areas/my_simple_brick/view.html.twig app.brick.my_simple_brick: parent: OpenDxp\Bundle\ToolboxBundle\Document\Areabrick\AbstractAreabrick tags: - { name: toolbox.area.simple_brick, id: my_simple_brick, title: 'My Simple Brick' } # OR, you may want to define some more info: description, template path and icon app.brick.my_second_simple_brick: parent: OpenDxp\Bundle\ToolboxBundle\Document\Areabrick\AbstractAreabrick tags: - { name: toolbox.area.simple_brick, id: my_scond_simple_brick, title: 'My Second Simple Brick', description: 'Some Description', template: 'areas/my-second-simple-brick/view.html.twig', icon: '/public/path/to/your/icon.svg' } opendxp_toolbox: areas: # that's the name of your simple brick. # configuration behaves the same as a default brick my_simple_brick: config_elements: title: type: input title: That's a Title description: Lorem Ipsum config: ~ ``` 2. Add the view to `/templates/areas/my_simple_brick/view.html.twig`: ```twig
{{ opendxp_input('title').data }}
``` That's it. If you want to refresh the permission table you also need to execute the `bin/console cache:clear` command. *** ### Bricks without Editables (No Config Dialog) Sometimes you need a real simple area brick without any configuration for editors. To do so, you only need to change the parent class: ```yaml services: # for default bricks App\Document\Areabrick\MyBrick\MyBrick: parent: OpenDxp\Bundle\ToolboxBundle\Document\Areabrick\AbstractBaseAreabrick tags: - { name: toolbox.area.brick, id: my_brick_without_configurable_options } # for simple bricks app.brick.my_simple_brick_without_configurable_options: parent: OpenDxp\Bundle\ToolboxBundle\Document\Areabrick\AbstractBaseAreabrick tags: - { name: toolbox.area.simple_brick, id: my_simple_brick_without_configurable_options, title: 'My Simple Brick (Without configurable Options)' } ``` *** #### Tabbed Config Dialog ![Config dialog with two tabs and the fields of the first tab](./img/config_dialog_tabs.png) To use tabs in your config dialog, you have to define them via the tab config node: ```yaml opendxp_toolbox: areas: dummy_brick: tabs: # <-- define tabs here first! tab1: 'Tab 1' tab2: 'Tab 2' config_elements: title1: type: input title: That's Title I description: Lorem Ipsum tab: tab1 # <-- add to tab1 config: ~ title2: type: input title: That's Title II description: Lorem Ipsum tab: tab1 # <-- add to tab1 config: ~ title3: type: input title: That's Title III description: Lorem Ipsum tab: tab2 # <-- add to tab2 config: ~ ``` --- ## Testing(Toolbox) The test API of OpenDXP creates pages for the tests of a project. Toolbox adds a brick for each of its areabricks and a factory for teaser snippets. Both live in the namespace `OpenDxp\Bundle\ToolboxBundle\Test`. This page builds on [Factories and Stories](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing/Factories_and_Stories). - [Place bricks on a page](#place-bricks-on-a-page) - [Bricks inside bricks](#bricks-inside-bricks) - [The bricks](#the-bricks) - [Teaser snippets](#teaser-snippets) ### Place bricks on a page The page factory of OpenDXP places bricks in an areablock of the page: ```php use OpenDxp\Bundle\ToolboxBundle\Test\Brick\HeadlineBrick; use OpenDxp\Bundle\ToolboxBundle\Test\Brick\ImageBrick; use OpenDxp\Test\Factory\AssetImageFactory; use OpenDxp\Test\Factory\DocumentPageFactory; $image = AssetImageFactory::createOne(); $harbour = ImageBrick::showing($image) ->withAltText('The harbour at night') ->withCaption(); $page = DocumentPageFactory::new() ->withBricks('content', HeadlineBrick::saying('Opening hours'), $harbour) ->create(); ``` A brick starts with the values that the dialog of the areabrick suggests to an editor. A headline is an `h3`, and two columns share the row evenly. Each state of a brick changes one setting of the dialog. A state is named after the field in the dialog, like `withHeadlineType('h2')` or `withLightBox()`. A brick takes the value of a select in the dialog as a string. A project can add values to these selects in its configuration. The brick takes those values the same way: `withType('column_2_10')`. Every brick with additional classes in its dialog has `withClass('highlighted')`. The bricks fill the editables of the classic layouts. Every brick that the headless layout supports has `forHeadless()`. This state gives the brick the editable names of the headless layout. Only accordion, container, image and teaser change their names. Parallax container and slide columns have no headless form. ### Bricks inside bricks Container, columns, slide columns, accordion and parallax container hold other bricks: ```php use OpenDxp\Bundle\ToolboxBundle\Test\Brick\AccordionBrick; use OpenDxp\Bundle\ToolboxBundle\Test\Brick\ColumnsBrick; use OpenDxp\Bundle\ToolboxBundle\Test\Brick\ContentBrick; use OpenDxp\Bundle\ToolboxBundle\Test\Brick\HeadlineBrick; $columns = ColumnsBrick::new() ->withType('column_4_8') ->withColumn(0, HeadlineBrick::saying('Delivery')) ->withColumn(1, ContentBrick::saying('

Within two days.

')); $faq = AccordionBrick::new() ->withPanel('Delivery', ContentBrick::saying('

Within two days.

')) ->withPanel('Returns', ContentBrick::saying('

Within thirty days.

')); ``` Columns count from 0. A column without bricks stays empty. ### The bricks | Brick | Created with | States | |--------------------------|-----------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `AccordionBrick` | `new()` | `withPanel($title, ...$bricks)`, `withComponent('tab')`, `withType('panel-danger')` | | `AnchorBrick` | `new()` | `withAnchorName('contact')`, `withAnchorTitle('Contact')` | | `ColumnsBrick` | `new()` | `withType('column_4_8')`, `withColumn(0, ...$bricks)`, `withEqualHeight()`, `withColumnAdjuster(['xs' => '12_12'])` | | `ContainerBrick` | `containing(...$bricks)` | `withFullWidthContainer()` | | `ContentBrick` | `saying('

Text

')` | | | `DownloadBrick` | `showing(...$assets)` | `withPreviewImages()`, `withFileInfo()` | | `GalleryBrick` | `showing(...$assets)` | `withThumbnails()`, `withLightBox()` | | `GoogleMapBrick` | `new()` | `withLocation(MapLocation::at($street, $zip, $city, $country))`, `withMapZoom(15)`, `withMapType('satellite')`, `withInfoWindow()` | | `HeadlineBrick` | `saying('Opening hours')` | `withHeadlineType('h2')`, `withAnchorName('opening-hours')` | | `IframeBrick` | `showing('https://example.com')` | `withHeight(480)` | | `ImageBrick` | `showing($image)` | `withAltText('…')`, `withCaption()`, `withLightBox()`, `linkingTo('/contact')` | | `LinkListBrick` | `new()` | `withLink('Imprint', '/imprint')` | | `ParallaxContainerBrick` | `new()` | `withSection(ParallaxSection::containing(...$bricks))`, `withBackgroundImage($asset)`, `withFrontImage($image, 'top-left', 'half-window-width')`, `withBehindImage(…)`, `withTemplate('…')`, `withBackgroundColor('…')` | | `SeparatorBrick` | `new()` | `withSpace('large')` | | `SlideColumnsBrick` | `new()` | `withSlidesPerView(3)`, `withSlide(...$bricks)`, `withEqualHeight()` | | `SnippetBrick` | `showing($snippet)` | | | `SpacerBrick` | `new()` | `withSpacerClass('spacer-50')` | | `TeaserBrick` | `showing($image, $headline, $html)`, `showingSnippet($snippet)` | `linkingTo('/contact')`, `withLightBox()`, `withLayout('default')` | | `VideoBrick` | `showing(VideoSource::youtube($idOrLink))` | `withPoster($image)`, `withLightBox()`, `withVideoParameter('rel', '0')`, `withAutoplay()` | A download and a gallery also take asset folders. The download offers every file inside a folder. The gallery shows the images directly inside a folder. A section of a parallax container has a dialog of its own: `withContainerType('container')`, `withTemplate('…')`, `withBackgroundImage($asset)` and `withBackgroundColor('…')`. `VideoSource` knows `youtube()`, `vimeo()` and `asset($video)`. ### Teaser snippets A teaser can show a snippet instead of its own content. `TeaserSnippetFactory` builds such a snippet: ```php use OpenDxp\Bundle\ToolboxBundle\Test\Brick\TeaserBrick; use OpenDxp\Bundle\ToolboxBundle\Test\Factory\TeaserSnippetFactory; $snippet = TeaserSnippetFactory::new() ->withImage($image) ->withHeadline('Opening hours') ->withText('

Monday to Friday

') ->linkingTo('/contact') ->create(); $teaser = TeaserBrick::showingSnippet($snippet); ``` The snippet uses the layout `default` until `withLayout()` names another one. `withLightBox()` opens the image in a light box, and `withClass('highlighted')` sets the additional classes of the snippet. --- ## Elements Overview ### Accordion / Tab Create an accordion or tab element. It's possible to change the layout from accordion to tabs without loosing the content. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|--------|---------------------------|---------------|-------------------------------------------------------| | `type` | select | Choose accordion type | panel-default | `opendxp_select('type')` | | `component` | select | Choose the component type | accordion | `opendxp_select('component')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Anchor Create an anchor element. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------|-------|----------------------|---------------|---------------------------------| | `anchor_name` | input | Set the anchor name | - | `opendxp_input('anchor_name')` | | `anchor_title` | input | Set the anchor title | - | `opendxp_input('anchor_title')` | ### Columns Create (nested) columns. #### Configuration By default, the toolbox will transform the stored values into bootstrap grid values. If you're using a different grid system, you probably need to change the [grid calculation](30_ToolboxTheme.md). **Note:** If you're changing the column amount during a layout change, the nested content may gets lost depending on the new column amount - Changing from 3 columns to 2 columns: the content of the third column gets lost. - Changing from 2 columns to 4 columns: the content of the first two columns stays the same. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|----------|-----------------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------| | `type` | select | Set the column type. see example below. | column_6_6 | `opendxp_input('type')` | | `columnadjuster` | section | This element comes by default after the `type` field. Read more about this feature [here](60_ColumnAdjuster.md) | - | - | | `equal_height` | checkbox | Appends some equal height classes | false | `opendxp_checkbox('equal_height')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Column Calculation Example ```yaml opendxp_toolbox: areas: columns: config_elements: type: config: store: column_8_4: '2 Columns' ``` `column_8_4` will generates two columns: 1. column with `col-12 col-sm-8 col-md-8` 2. column with `col-12 col-sm-4 col-md-4` It's possible, however, to define custom breakpoint classes and also offset elements: ```yaml opendxp_toolbox: areas: columns: config_elements: type: config: store: column_4_4_4: '3 Columns (33:33:33)' column_o1_4_o1_5: name: '2 Columns (1 Offset, 33%%, 1 Offset, 40%%, 1 Offset)' breakpoints: xs: o0_12_o0_12 sm: o0_6_o0_6 md: o1_4_o1_5 lg: o1_4_o1_5 column_o2_4_o1_3: name: '2 Columns (2 Offset, 33%%, 1 Offset, 25%%, 2 Offset)' breakpoints: xs: o0_12_o0_12 sm: o1_5_o1_4 md: o1_5_o1_4 lg: o2_4_o1_3 column_4_3_o1_3: name: '3 Columns (33%%, 25%%, 1 Offset, 25%%, 1 Offset)' breakpoints: xs: 12_12_o0_12 sm: 6_6_o0_12 md: 4_4_o0_4 lg: 4_3_o1_3 ``` ### Container Create a container element. Useful if you're using a full width layout. #### Available Options | Name | Type | Description | Default Value | Frontend | |------------------------|----------|----------------------------------|---------------|-------------------------------------------------------| | `full_width_container` | checkbox | Adds the `container-fluid` class | false | `opendxp_checkbox('full_width_container')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Content Create a wysiwyg editor. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|--------|--------------------|---------------|-------------------------------------------------------| | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Download Create download elements. > Note: If you're using the [MembersBundle](https://github.com/open-dxp/members-bundle), the download element will automatically check for a restriction. #### Available Options | Name | Type | Description | Default Value | Frontend | |-----------------------|-----------|------------------------------|---------------|-------------------------------------------------------| | `downloads` | relations | Add download files / folders | - | `opendxp_relations('downloads')` | | `show_preview_images` | checkbox | Display Preview Images | false | `opendxp_checkbox('show_preview_images')` | | `show_file_info` | checkbox | Display File Info | false | `opendxp_checkbox('show_file_info')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Configuration Parameter Use the `event_tracker` Parameter to build a helper markup for google events: **Example** ```yaml opendxp_toolbox: areas: download: config_parameter: event_tracker: category: 'PDF' action: 'download' label: ['getMetadata', ['name']] noninteraction: true ``` #### View Helper In `Download/Partial/item.html.twig`, you'll find a `toolbox_download_info()` helper. This Twig Extension will generate some download info. **Usage**: ```twig {% set downloadInfo = toolbox_download_info(download, true, 'optimized', 0) %} ``` **Arguments:** 1. Asset, Download File 1. Bool, Show Preview Image 1. String, File Size Unit (mb, kb, optimized). Optimized means: get the best matching unit. 4. File Size Precision: Round Precision ### Gallery Create image galleries. #### Dependency The base markup of this gallery element includes some [slick slider](http://kenwheeler.github.io/slick/) standards. If you want to use a different extension to generate your galleries, just override the templates or use the change the selector in your javascript call. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|-----------|---------------------------------------------|---------------|-------------------------------------------------------| | `images` | relations | Add images / folders | - | `opendxp_relations('images')` | | `use_light_box` | checkbox | Add a `light-box` class and a wrapping link | false | `opendxp_checkbox('use_light_box')` | | `use_thumbnails` | checkbox | Add a thumbnail slider | false | `opendxp_checkbox('use_thumbnails')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Google Map Create a Google Map Element. You're able to define one or multiple markers. Toolbox will automatically generate the long/lat information after saving the document. #### Get & set your API Key To get a valid API Key you need to follow those steps: - Create [a valid google maps api key](https://developers.google.com/maps/documentation/javascript/get-api-key) - Enable two APIs: Geocoding API, Maps Javascript API - Generate an API Key - Copy API Key #### Key Integration You have three ways to integrate your Keys. ##### I. Google Marketing Configuration > Note: This is the recommended way to integrate GM Keys! Add the keys to the configuration of the Google Marketing bundle: ```yaml # config/config.yaml opendxp_google_marketing: browser_api_key: YOUR_BROWSER_KEY simple_api_key: YOUR_SIMPLE_KEY ``` ![Three ways to set the browser API key of the Google Map element](./img/google_maps_api_key.png) ##### II. Using a Parameter If you want to define them via parameters, you're able to define them like this: ```yaml # config/config.yaml parameters: toolbox_google_service_browser_api_key: YOUR_BROWSER_KEY toolbox_google_service_simple_api_key: YOUR_SIMPLE_KEY ``` ##### III. Direct Element Configuration If you don't want to define them via parameters, you need to override the default parameters on configuration layer: ```yaml opendxp_toolbox: areas: googleMap: config_parameter: map_api_key: null # replace here simple_api_key: null # replace here ``` #### Script Integration Now you can include the script tag in your footer: ```html ``` > Note: This is a [custom toolbox element](22_GoogleMapsElement.md). #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|----------|-------------------------------|---------------|-------------------------------------------------------| | `map_zoom` | numeric | Map Zoom | 12 | `opendxp_numeric('map_zoom')` | | `map_type` | select | Map Type (ROADMAP, HYBRID ..) | roadmap | `opendxp_select('map_type')` | | `iw_on_init` | checkbox | Open Info Window by Default | false | `opendxp_checkbox('iw_on_init')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Configuration Parameter | Name | Type | Description | Default Value | |------------------|--------|---------------------------------------------------------------------------------------------------------------------|-------------------------------------------| | `map_options` | array | Map Zoom | [] | | `map_style_url` | string | Define a custom map style (path to json) | false | | `marker_icon` | string | Define a custom marker_icon (path to icon) | false | | `map_api_key` | string | Set a custom map api key. To extend the daily request to 2.500 per day. This key is used by frontend-api-requests | `'%toolbox.google_maps.browser_api_key%'` | | `simple_api_key` | string | Set a custom simple api key. To extend the daily request to 2.500 per day. This key is used by backend-api-requests | `'%toolbox.google_maps.simple_api_key%'` | **Example** ```yaml opendxp_toolbox: areas: googleMap: config_parameter: map_options: streetViewControl: true mapTypeControl: false panControl: false scrollwheel: false map_style_url: false marker_icon: false map_api_key: false simple_api_key: false ``` #### UI Extension There is also an ui extension for the google maps element. Read more about it [here](80_Javascript.md) #### Route Link Renderer There is a macro in `views/Macro/mapLink.html.twig` (used in `views/[THEME NAME]/google_map/info-window.html.twig`) which will render the map route link: ```twig {# default #} {{ link_generator.generate(googleMapsHostUrl, mapParams) }} {# generates #} {# https://maps.google.ch/?daddr=47.4838827,9.7574593&directionsmode=driving #} ``` ```twig {# use address params #} {{ link_generator.generate(googleMapsHostUrl, mapParams, false) }} {# generates #} {# https://maps.google.ch/?daddr=way+132,666+city,country&directionsmode=driving #} ``` ### Headline Create a headline. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|--------|--------------------------|---------------|-------------------------------------------------------| | `headline_type` | select | Define the headline size | h3 | `opendxp_select('headline_type')` | | `anchor_name` | input | Define a anchor name | - | `opendxp_input('anchor_name')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### iFrame Create an iFrame field. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|-------------------------------------------------------| | `url` | input | Set a Url which should be loaded. If the Url is not allowed to implement (Source has a `SAMEORIGIN`, `DENY` entry in `x-frame-options` header) you'll receive an error. | - | `opendxp_input('url')` | | `iheight` | numeric | Initial Height of the iFrame | 200 | `opendxp_numeric('iheight')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Javascript Plugin There is also a javascript plugin for the iFrame element. Read more about it [here](80_Javascript.md). We can't provide any out-of-the-box solution for changing the iframe height dynamically (cross-domain policy), so you need to take care about that by yourself. Possible Solutions to mastering dynamic iFrame heights: - Define an iFrame height for every breakpoint in your stylesheet. - Use the plugin events (see iframe javascript extension) and connect it with a plugin like the [iframe-resizer](https://github.com/davidjbradshaw/iframe-resizer). ### Image Create an image field. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|----------|---------------------------------------------|---------------|-------------------------------------------------------| | `use_light_box` | checkbox | Add a `light-box` class and a wrapping link | false | `opendxp_checkbox('use_light_box')` | | `show_caption` | checkbox | Render image caption | false | `opendxp_checkbox('show_caption')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Link List Create a link list (via opendxp block element). #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|--------|--------------------|---------------|-------------------------------------------------------| | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Parallax Container Build a Parallax Container. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|---------------|-------------------------------------|---------------------|-------------------------------------------------------| | `template` | select | Define a Parallax Template | no-template | `opendxp_select('template')` | | `background_image` | relation | Define a background image | - | `opendxp_relation('background_image')` | | `background_color` | select | Define a background color | no-background-color | `opendxp_select('background_color')` | | `image_front` | parallaximage | Parallax Images behind content | - | *not available* | | `image_behind` | parallaximage | Parallax Images in front of content | - | *not available* | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Configuration Parameter - Use the `window_size` Parameter to render a larger edit window - Use the `background_mode` Parameter to define the background mode (wrap, prepend) - Use the `background_image_mode` Parameter to define the append mode (data, class) - Use the `background_color_mode` Parameter to define the append mode (data, class) **Example** ```yaml opendxp_toolbox: areas: parallaxContainer: config_parameter: window_size: large background_mode: wrap background_image_mode: data background_color_mode: data ``` ### Parallax Container Section Build a Parallax Container Section. > Note: This element is only available in a parallax container element. #### Stored Values A section renders these values when the document holds them. The editmode offers no dialog to change them. | Name | Type | Description | Default Value | Frontend | |--------------------|----------|------------------------------------|---------------------|----------------------------------------| | `template` | select | Define a Parallax Section Template | no-template | `opendxp_select('template')` | | `container_type` | select | Define a Container Type | none | `opendxp_select('container_type')` | | `background_image` | relation | Define a background image | - | `opendxp_relation('background_image')` | | `background_color` | select | Define a background color | no-background-color | `opendxp_select('background_color')` | #### Configuration Parameter - Use the `background_image_mode` Parameter to define the append mode (data, class) - Use the `background_color_mode` Parameter to define the append mode (data, class) **Example** ```yaml opendxp_toolbox: areas: parallaxContainerSection: config_parameter: background_image_mode: data background_color_mode: data ``` ### Separator Create a Separator Element (hr) #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|--------|-----------------------------------|---------------|-------------------------------------------------------| | `space` | select | Add some seperator spacer classes | default | `opendxp_select('space')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Slide Columns Create a sliding column element. #### Dependency We basically designed this element in combination with the [slick slider](http://kenwheeler.github.io/slick/) plugin. Since we want to avoid specific markup in a most possible way, there are still some references if your looking at the toolbox [backend style](https://github.com/open-dxp/toolbox-bundle/blob/1.x/public/css/admin.css#L47). This is just a hint if you're going to use a different javascript extension: Be sure this element works in your backend too. :) > Note: You need to implement your own javascript logic. Get some hints [here](50_FrontendTips.md). #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|----------|-----------------------------------|---------------|-------------------------------------------------------| | `slides_per_view` | select | Slides per View | 4 | `opendxp_select('slides_per_view')` | | `equal_height` | checkbox | Appends some equal height classes | false | `opendxp_checkbox('equal_height')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Configuration Parameter - Use the `column_classes` Parameter to define column classes - Use the `breakpoints` Parameter to define special breakpoint classes **Example** ```yaml opendxp_toolbox: areas: slideColumns: config_parameter: column_classes: '2': 'col-12 col-sm-6' breakpoints: [] ``` ### Spacer Create a spacer element. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|--------|--------------------|---------------|-------------------------------------------------------| | `spacer_class` | select | Spacer classes | spacer-none | `opendxp_select('spacer_class')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | ### Teaser Create teaser elements. #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|----------|--------------------------------------------------------------|---------------|---------------------------------------------------------------------------| | `type` | select | Define Teaser Type: direct or as snippet | direct | `opendxp_select('type')`. Read more about below in "Teaser Type" Section. | | `layout` | select | Define Teaser Layout | default | `opendxp_select('layout')` | | `use_light_box` | checkbox | Add a `light-box` class and a wrapping link for teaser image | false | `opendxp_checkbox('use_light_box')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Teaser Types Like explained above, it's possible to switch between two Types of Teasers: ##### Direct The `direct` teaser type allows you to place a teaser structure at any place in your document. Just change the options through the edit window. ##### Snippet Sometimes you want do add teasers in a more reusable way. For that you should use the `snippet` type. The ToolboxBundle will add a `Teaser Snippet` document type during installation, use it to create teaser elements in snippet context. This document type will also add all custom elements (`layout`, `use_light_box`, `additional_classes`) with all given teaser layouts. > Note: If you're using the `snippet` type, all option fields (`layout`, `use_light_box`, `additional_classes`) will become unavailable in your document. ### Video Create a Video Element. > Note: This is a [custom toolbox element](21_VhsElement.md). #### Available Options | Name | Type | Description | Default Value | Frontend | |----------------------|----------|------------------------------------------------|---------------|-------------------------------------------------------| | `autoplay` | checkbox | Start/Stop Video if it's in a visible viewport | false | `opendxp_checkbox('autoplay')` | | `additional_classes` | select | Add custom classes | - | see [section additional classes](#additional-classes) | #### Configuration Parameter - Use the `video_types` Parameter to enable/disable Video Types **Example** ```yaml opendxp_toolbox: areas: video: config_parameter: video_types: asset: active: false allow_lightbox: true youtube: active: true allow_lightbox: true vimeo: active: false allow_lightbox: true ``` #### UI Extension There is also an ui extension for the video element. Read more about it [here](80_Javascript.md) ### Element Config Field Overview In short, you're able to use all the [opendxp editables](https://docs.opendxp.io/docs/core-framework/Documents/Editables/). **Example** ```yaml opendxp_toolbox: areas: container: config_elements: awesome_fields: type: input # all the opendxp editables config: # all available configuration attributes from # https://docs.opendxp.io/docs/core-framework/Documents/Editables/Input#configuration ``` #### Editable Store Provider In addition, you could use the toolbox editable store provider to generate dynamic store data. Read more about it [here](./16_EditableStoreProvider.md). ### Additional Classes Almost every toolbox element supports the `additionalClasses` field type. This Element will help you to generate some additional classes for every toolbox element. This is great since you don't need to override the element view, just add one or more additional classes via config. > Note: The class gets attached to the `toolbox-*` wrapper element. #### Main Additional Class To add some ```yaml opendxp_toolbox: areas: headline: config_elements: additional_classes: type: additionalClasses config: store: white-bg: 'White Background' ``` This will generate a drop-down in your area config field: ![Additional class drop-down and the class it adds to the element](./img/additional_classes_single.png) > **Note!** You can only use `additionalClasses` once per field. > **Note!** Name needs to be `additional_classes`. #### Chained Additional Classes If you need to add more additional classes you need to add one or more fields of type `additionalClassesChained`. ```yml opendxp_toolbox: areas: headline: config_elements: additional_classes: type: additionalClasses config: store: ac_class_1: 'class 1' ac_class_2: 'class 2' ac_class_3: 'class 3' additional_classes_chain_1: type: additionalClassesChained title: 'II. Chained Classes' config: store: chain_one_class_1: 'chain one class 1' chain_one_class_2: 'chain one class 2' chain_one_class_3: 'chain one class 3' additional_classes_chain_2: type: additionalClassesChained title: 'III. Chained Classes' config: store: chain_two_class_1: 'chain two class 1' chain_two_class_2: 'chain two class 2' chain_two_class_3: 'chain two class 3' ``` This will generate some drop-downs in your area config field: ![Three additional class drop-downs and the classes they add to the element](./img/additional_classes_chained.png) > **Note!** You can only use `additionalClassesChained` if there is a configured `additionalClasses` field. > **Note!** Name needs to be `additional_classes_chain_[INT]` where `[INT]` needs to be numeric. Now check the toolbox-element, all additional classes are available in the `toolbox-element`: ```html
[...]
``` --- ## Wysiwyg Editor Configuration The Toolbox Bundle allows you to override and specify the wysiwyg configuration. There are several reasons for that: - Keep the editor simple, remove unwanted dangerous elements from the wysiwyg - Define custom styles via configuration - Use the same editor layout in every wysiwyg element (Document, Emails, Objects) > [!IMPORTANT] > Toolbox **automatically enables** its extension configuration when the TinyMCE bundle is installed. *** ### TinyMCE #### Toolbar Checkout the [available toolbar buttons](https://www.tiny.cloud/docs/advanced/available-toolbar-buttons/). > [!TIP] > Info: This is the global configuration for the TinyMCE-Editor Toolbar. > If you need to provide a different configuration in objects or areas, use the object/area configuration (see below) #### Overriding Configuration **Example** ```yaml opendxp_toolbox: wysiwyg_editor: config: block_formats: 'Paragraph=p; Header 1=h1; Header 2=h2; Header 3=h3' style_formats: - title : 'Example' inline : 'span' classes : 'example' selector: 'a' toolbar2: 'blocks | styles' ``` > [!IMPORTANT] > If your extending style formats, you also have to extend the [html sanitize](https://docs.opendxp.io/docs/core-framework/Documents/Editables/WYSIWYG#extending-symfony-html-sanitizer-configuration) > otherwise you're applied data will be removed after persisting! ##### Area Editor Configuration If you only need to modify the toolbar configuration for document areas, add this to your configuration: **Example** ```yaml opendxp_toolbox: wysiwyg_editor: area_editor: config: # his will change the toolbar2 only for document editables editors toolbar2: 'blocks' ``` ##### Object Editor Configuration If you only need to modify the toolbar configuration for objects, add this to your configuration: > [!NOTE] > The object configuration does not respect different toolbox context environments at the moment. > Objects are not restricted to any sites by nature which makes any context-binding quite impossible. **Example** ```yaml opendxp_toolbox: wysiwyg_editor: object_editor: config: # this will change the toolbar2 only for object editors toolbar2: 'blocks' ``` ##### TinyMce Editor Plugins Toolbox provides some additional Editor Plugins ###### Google Opt Out Add a link to allow user to disable Google Analytics tracking. The button is called "Google Opt-Out Link". Its dialog "Basic Settings" asks for the "Google Analytics Code" and the "Text" of the link. There is also a [frontend Javascript Plugin](./80_Javascript.md). ###### Enable Button ```yaml opendxp_toolbox: wysiwyg_editor: config: toolbar2: 'tb_goo_link_button' ``` --- ## Image Thumbnails To stay organized, the ToolboxBundle provides a dedicated configuration and a simple helper for image thumbnails. Every required thumbnail size is defined in the [toolbox configuration](https://github.com/open-dxp/toolbox-bundle/blob/master/config/image_thumbnails.yaml). So it's easy for you to simplify or change the [Image Thumbnail](https://docs.opendxp.io/docs/core-framework/Assets/Working_with_Thumbnails/Image_Thumbnails) reference. Although this is just an optional feature, it makes sense to use the view helper in your project and custom bricks. ### Configuration ```yaml opendxp_toolbox: image_thumbnails: # get merged or overrides the toolbox defaults gallery_element: 'myOverriddenGalleryThumbnailSize' my_thumbnail_size: 'myThumbnailSize' ``` ### View Helper: ```twig {{ asset.getThumbnail(toolbox_get_image_thumbnail('my_thumbnail_size')) }} ``` --- ## Context The Toolbox context allows you to use different configuration namespaces. For example, if you have multiple opendxp sites, it's possible to use different elements and configuration. You're also able to merge different context configuration with the main one. ### Real Life Example You have one main toolbox configuration. Now you need to implement a second page for your client, with a different layout and areas. Just create a toolbox context (see below) and you're able to provide dedicated elements and a specific configuration for each area element. If your client opens the document in the backend in a specific site tree for example, he will only see those defined elements in the toolbar. ### Context Configuration | Name | Type | Description | |-------------------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `merge_with_root` | bool | Use the main toolbox configuration as base configuration and reconfigure them in the new context. **Note**: If you disable this note, you need to provide every single configuration by your own. | | `enabled_areas` | array | Enable specific Areas | | `disabled_areas` | array | Disable specific Areas. **Note:** If you have configured `enabled_areas` this option will be ignored. | > **Note**: If you have enabled `merge_with_root` you cannot use a different theme in sub context since there would be a layout mismatch. #### Merge Hierarchy Merge from root means: 1. get all config from toolbox core bundle 2. merge with all `toolbox` configs defined in app 3. merge with all `toolbox.context.context_name.xy` configs defined in app ### Configuration Example ```yml opendxp_toolbox: context: portal: # context identifier settings: merge_with_root: true enabled_areas: - 'headline' - 'accordion' areas: headline: config_elements: headline_type: type: select title: 'New Type' config: name: headlineType store: h1: Headline 1 h2: Headline 2 default: h2 anchor_name: ~ app: # context identifier settings: merge_with_root: true disabled_areas: - 'accordion' - 'columns' ``` ### Context Resolver You need a Context Resolver to inform Toolbox which context is the current active one. If the resolver returns `null` the main configuration will be used. #### Add Context Resolver to the Toolbox configuration. > **Note:** A Context Resolver is a global setting and cannot be added to a sub context. ```yml opendxp_toolbox: context_resolver: 'App\Services\ToolboxBundle\ContextResolver' ``` #### Create Context Resolver Class ```php requestHelper->hasMainRequest()) { return null; } $request = $this->requestHelper->getMainRequest(); //if request is coming from a wysiwyg configuration request (/admin/*.js) if ($request->query->has('tb_document_request_id')) { try { $currentDocument = Document::getById($request->query->get('tb_document_request_id')); } catch (\Exception $e) { $currentDocument = null; } $site = $currentDocument instanceof Document ? Tool\Frontend::getSiteForDocument($currentDocument) : null; } elseif ( $this->editModeResolver->isEditmode($request) || $this->requestHelper->isFrontendRequestByAdmin($request) ) { // in backend, we don't have any site request, we need to fetch it via document $currentDocument = $this->documentResolver->getDocument(); $site = Tool\Frontend::getSiteForDocument($currentDocument); } else { $site = $this->siteResolver->isSiteRequest($request) ? $this->siteResolver->getSite($request) : null; } if (!$site instanceof Site) { return null; } if ($site->getRootId() === 1) { return 'portal'; } elseif ($site->getRootId() === 2) { return 'app'; } return null; } } ``` --- ## Store Provider for (Multi-) Select Editables This Bundle allows you to generate dynamic data for your dropdown elements. If you're in opendxp context, a typical store looks like this: ```yml opendxp_toolbox: areas: video: config_elements: a_classical_store: type: multiselect title: 'Test 2' config: store: my_value: 'My Value' foo: 'Bar' ``` #### Configure Dynamic Store Provider But you're also able to provide your data from a symfony service: ```yml opendxp_toolbox: areas: video: config_elements: my_dynamic_store_provider: type: select title: 'Test' config: store_provider: 'my_awesome_store_provider' ``` #### Register Custom Store Provider Now we need to register our new service: ```yml # app/config.yaml services: App\Toolbox\MyStoreProvider: tags: - { name: toolbox.editable.store_provider, identifier: 'my_awesome_store_provider' } ``` #### Create Store Provider ```php 'My Value', 'foo' => 'Bar' ]; } } ``` --- ## Code Style #### CamelCase All Toolbox Elements are written in camelcase. **Controller** - `Document\Areabrick\GoogleMap` #### Underscore All Configuration Elements are written in underscore: ```yaml opendxp_toolbox: areas: anchor: config_elements: anchor_name: # underscore: in view, you'll call it with opendxp_input('anchor_name'); type: input title: Anchor Name config: ~ anchor_title: # underscore: in view, you'll call it with opendxp_input('anchor_title'); type: input title: Anchor Title config: ~ ``` #### Underscore Exceptions - Google Maps Element, Map Options: Values must be camelcase because of the Google map configuration mapping. - Config Elements `config` Tree: Values must be camelcase because of the opendxp element configuration mapping. #### Strings - Do not use percentage values in titles - Always quote your title values --- ## VHS Element Create a Video Element. This Element extends the default opendxp video element. > Note: This element is also used in the toolbox video element. ### Usage ```twig {{ opendxp_vhs('video', { 'attributes': { 'class': 'video-js vjs-default-skin vjs-big-play-centered', 'data-setup': '{}' }, 'thumbnail': toolbox_get_image_thumbnail('video_thumbnail'), 'imagethumbnail': toolbox_get_image_thumbnail('video_poster'), 'disableProgressReload' : true, 'height': 250 }) }} ``` --- ## Google Maps Element Create a Google Map Element. > Note: This element is also used in the toolbox google map element. ### Usage ```twig {{ opendxp_googlemap('googlemap', { 'reload' : true, 'mapZoom' : mapZoom, 'mapType' : mapType, 'iwOnInit' : iwOnInit }) }} ``` --- ## Commands ![Output of the check-config command for the accordion area brick](./img/check_config_output.png) ### Area Configuration Use this command to get a brief overview about a given area brick. ```bash $ bin/console opendxp_toolbox:check-config --area=accordion # use with context $ bin/console opendxp_toolbox:check-config --area=accordion --context=portal ``` --- ## Toolbox Theme / Layout The Toolbox Bundle is currently using Bootstrap 4 as default framework. ### Supported Frameworks - [Bootstrap 4](./themes/Bootstrap4.md) - [Bootstrap 3](./themes/Bootstrap3.md) - [UIkit3](./themes/UiKit3.md) - [Headless](./themes/Headless.md) *** It's also possible to create your custom layout / theme. ### Theme Configuration Within the `theme` node you're able to define your custom layout information. ```yaml opendxp_toolbox: theme: grid: ~ # defines the view namespace [LAYOUT_NAME] layout: !php/const OpenDxp\Bundle\ToolboxBundle\Manager\LayoutManagerInterface::TOOLBOX_LAYOUT_BOOTSTRAP4 default_layout: false wrapper: image: - {tag: 'div', class: 'row'} - {tag: 'div', class: 'col-12'} columns: - {tag: 'div', class: 'row'} gallery: - {tag: 'div', class: 'row'} - {tag: 'div', class: 'col-12 col-gallery', attr: 'only-attributes-without-values-are-allowed'} slideColumns: - {tag: 'div', class: 'row'} teaser: - {tag: 'div', class: 'row'} - {tag: 'div', class: 'col-12'} ``` ##### Grid Please [read this](60_ColumnAdjuster.md) to learn more about the fancy column adjuster - where this setting is important! ##### Layout This property defines the current layout view path. ##### Default Layout Define a fallback layout. If you're using a custom layout and you have defined a default layout, the template routing will work like this: ```yaml opendxp_toolbox: theme: layout: 'Special' default_layout: 'Bootstrap4' ``` ```twig {# example: Image #} 1. search layout: @OpenDxpToolbox/Toolbox/Special/Image/view.html.twig 2. fallback layout: @OpenDxpToolbox/Toolbox/Bootstrap3/Image/view.html.twig ``` > Note: `default_layout` is set to `false` by default, so no fallback layout gets loaded if the layout template is not available. ##### Wrapper Overriding templates is a great thing. Using the yaml configuration files is even better. With this property you have the power to wrap as many elements as you want around every toolbox element. As you can see, this bundle already adds some wrappers to specific elements. ### Views All Views get loaded from `@OpenDxpToolbox/Toolbox/[LAYOUT_NAME]`. ### Calculators There are two elements which needs some special calculation, depending on the current Grid-Framework: - Columns - SlideColumns Each element needs a calculator to provide correct grid values. ### Custom Layout Implementation So let's assume that you want to add your own custom grid framework: ```yaml # config/packages/toolbox.yaml opendxp_toolbox: theme: layout: 'YourGridSystem' wrapper: image: - {tag: 'div', class: 'grid-row'} - {tag: 'div', class: 'col 12-columns'} ``` From now on, the Toolbox Bundle will search every element view in `ToolboxBundle/templates/toolbox/YourGridSystem/*`. Now implement the calculators (don't forget the tags): ```yaml # config/services.yaml services: _defaults: autowire: true public: false # column calculator App\Calculator\ColumnCalculator: calls: - [setConfigManager, ['@OpenDxp\Bundle\ToolboxBundle\Manager\ConfigManager']] tags: - { name: toolbox.calculator, type: column } # slide column calculator App\Calculator\SlideColumnCalculator: tags: - { name: toolbox.calculator, type: slide_column } ``` ```yaml # config/packages/toolbox.yaml opendxp_toolbox: theme: calculators: column_calculator: App\Calculator\ColumnCalculator slide_calculator: App\Calculator\SlideColumnCalculator ``` #### Column Calculator ```php configManager = $configManager; return $this; } public function calculateColumns($value, $columnConfiguration = []) { $themeSettings = $this->configManager->getConfig('theme'); $gridSettings = $themeSettings['grid']; $gridSize = $gridSettings['grid_size']; $columns = []; // generate column classes here. // please check out the bootstrap4 calculator if you need more information. return $columns; } public function getColumnInfoForAdjuster($value, $columnConfiguration = null) { // generate column info for the column adjuster. // please check out the bootstrap4 calculator if you need more information. } } ``` #### Slide Column Calculator ```php ``` This will generate something like this: ```html
``` --- ## Frontend Tips #### Gallery / Slider Yes, there are a lot of slider out there. Toolbox has some references to the [slick slider](http://kenwheeler.github.io/slick/) so we'll show you some things to consider if you want to use it too: ##### Backend There are three options you need to take care about, otherwise you'll run into some troubles if your opening your document in editmode: ```javascript var editmode = true, //implement your js editmode resolver settings = { accessibility: !editMode, rows: 0, infinite : !editMode }; ``` #### Light-Box **Recommendation**: [LightGallery](https://github.com/sachinchoolur/lightGallery) --- ## Column Adjuster This Feature is so damn hot, it even has its own documentation page! To enable this feature, you need to add this to your toolbox configuration: ```yaml opendxp_toolbox: theme: grid: grid_size: 12 breakpoints: - identifier: 'xs' name: 'Breakpoint: XS' description: 'Your Description' - identifier: 'sm' name: 'Breakpoint: SM' description: 'Your Description' - identifier: 'md' name: 'Breakpoint: MD' description: 'Your Description' - identifier: 'lg' name: 'Breakpoint: LG' description: 'Your Description' ``` ### Parameter | Name | Type | Description | |---------------|---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `grid_size` | integer | Max Grid Columns (Default 12 in Bootstrap) | | `breakpoints` | array | Your Grid Breakpoints. **Important (!)**: The Column Adjuster is mobile first! Always start your array with the smallest breakpoint! Otherwise the automatic class inheritance won't work! | --- ## Configuration Flags(Toolbox) Sometimes we implement new features which could break the data stream / layout after updating. To avoid this and keep the backward compatibility promise, we've implemented the config flags. *** Currently, no configuration flags available. --- ## Javascript UI Extension We're providing some helpful UI extensions to simplify your daily work with Toolbox. *** ### VanillaJs All Extensions are available on npmjs.com via [js-opendxp-toolbox](https://www.npmjs.com/package/js-opendxp-toolbox). #### Installation ```bash npm i js-opendxp-toolbox ``` Read more about installation and usage on [github](https://github.com/open-dxp/js-opendxp-toolbox). --- ## Headless Learn, how to put toolbox into headless mode. ### Thinks to know - The Headless layout will super simplify the backend edit mode. No views will be generated there, but only the configuration fields. - In the frontend layer, the editable output will be a simple array (already nested) - All toolbox editables except `parallax` and `slidecolumn` are headless ready out of the box - Since the output is json, you're not able to add or modify data in view. Use the `HEADLESS_EDITABLE_ACTION` event to add more data and use a tagged `toolbox.property.normalizer` to change the json output ### Headless Aware Editable If your editable should work within the headless layout, you need to add some more stuff: - Add `ToolboxHeadlessAwareBrickInterface` - Add `headlessAction` method Example: ```php buildInfoParameters($info); return parent::action($info); } public function headlessAction(Info $info, HeadlessResponse $headlessResponse): void { $this->buildInfoParameters($info, $headlessResponse); parent::headlessAction($info, $headlessResponse); } private function buildInfoParameters(Info $info, ?HeadlessResponse $headlessResponse = null): void { $infoParams = $info->getParams(); $mySpecialParameter = '[AWESOME]'; if ($headlessResponse instanceof HeadlessResponse) { // will be used in fe output $headlessResponse->set('mySpecialParameter', $mySpecialParameter); return; } // will be used in editmode $info->setParam('mySpecialParameter', $mySpecialParameter); } } ``` #### Change the output The configuration decides what a brick outputs under `data`: every element of `config_elements` and `inline_config_elements`, unless it has `omit_data_output`. Each value goes through the `property_normalizer` of its element, or else through the normalizer that `property_normalizer.default_type_mapping` names for its type. The headless action changes this output with two methods of `HeadlessResponse`: ```php $headlessResponse ->set('insights', $listing->getObjects()) ->set('anchorName', $slug) ->set('contact', $person, PersonNormalizer::class) ->remove('limit', 'categories'); ``` - `set(string $name, mixed $value, ?string $normalizer = null)` outputs the value under the name. It replaces an element under the same name, also one with `omit_data_output`. The value goes through the first normalizer of these: the one you pass, the one in `additional_property_normalizer` for the name, the one of the element with the name. A value without any of them is output as it is. - `remove(string ...$names)` leaves the names out of the output, the values of elements as well as values you set. The last call for a name wins. Both methods work before and after `parent::headlessAction()`, and in a listener of `HEADLESS_EDITABLE_ACTION` as well. Pass a normalizer by the class that the configuration names: headless toolbox replaces `LinkNormalizer` and `ImageEditableNormalizer` with headless versions under these names. A value you set under a new name needs a description in the API schema. Put an `#[OA\Schema]` on the areabrick, see the testing docs of the headless toolbox bundle. ### Setup ```yaml opendxp_toolbox: theme: layout: !php/const OpenDxp\Bundle\ToolboxBundle\Manager\LayoutManagerInterface::TOOLBOX_LAYOUT_HEADLESS calculators: column_calculator: OpenDxp\Bundle\ToolboxBundle\Calculator\Bootstrap4\ColumnCalculator # or your custom headless calculator slide_calculator: OpenDxp\Bundle\ToolboxBundle\Calculator\Bootstrap4\SlideColumnCalculator # or your custom headless calculator. slide columns aren't supported right now, so it doesn't matter which service you're using ``` *** ### Headless Documents It's possible to create simple headless documents: ```yaml opendxp_toolbox: enabled_core_areas: - content - headline - image theme: layout: !php/const OpenDxp\Bundle\ToolboxBundle\Manager\LayoutManagerInterface::TOOLBOX_LAYOUT_HEADLESS headless_documents: default_headless_document: areas: index_headline: type: area config: type: headline myBlock: type: areablock another_headless_document: areas: headline: type: area config: type: headline wysiwyg: type: area config: type: content simple_input: type: input title: 'My Simple Input' awesome_blocks: type: block children: block_text: type: input title: 'Text' block_link: type: link property_normalizer: OpenDxp\Bundle\ToolboxBundle\Normalizer\LinkNormalizer title: 'Link' config: class: 'list-link' special_accordion: type: area config: type: accordion ``` - Add `ToolboxBundle\Controller\HeadlessController::headlessDocumentAction` as action to your document. - Add a text property to the document called `headless_document` and set `default_headless_document` as value. You can create multiple documents that way. *** ### Property names The headless JSON uses the names of your configuration as its keys: the areas of a headless document, the editables of a brick, the children of a block and the data attributes of the gallery. Most configurations write them in snake_case, while the rest of the JSON uses camelCase. Toolbox can output these names in camelCase: ```yaml opendxp_toolbox: headless: camel_case_property_names: true ``` | `camel_case_property_names` | Output | |-----------------------------|-------------------------------------------------| | `false` | `headline_text`, as the configuration writes it | | `true` | `headlineText` | The default is `false`. Toolbox 2.0 always outputs camelCase, so Toolbox reports a deprecation until the option is `true`. Switch when your frontend reads camelCase. With `camel_case_property_names: true`: - Only the JSON changes. The configuration and the stored content keep their names. - The API schema of the headless toolbox bundle uses the same names, so a generated client fits the JSON. - When a headless action adds a value under the name of an element, the value replaces the element. The headline brick, for example, outputs only `anchorName`, the slug of the anchor. The raw text under `anchor_name` is gone. - The headless bundle names the template of a headless document `_cmsTemplate` instead of `_cms_template`. - Names inside a value stay as they are: the output of normalizers, the arrays a headless action sets and the parameters of a video player. When two names become the same name, like `opening_hours` and `openingHours` in one headless document, `bin/console cache:clear` fails with an error that names both of them. Rename one of them. The check covers every toolbox context. After the switch, generate the API client of the frontend again. The TypeScript compiler then marks every place that still reads an old name. ### Extend existing headless editables Register an event listener to `ToolboxEvents::HEADLESS_EDITABLE_ACTION`. Its `HeadlessEditableActionEvent` gives you the `HeadlessResponse` of the brick, which you change with `set()` and `remove()`. ### Normalize data In headless context, you're not able to modify output via view files and in some scenarios you also want to output data differently in a given context. Toolbox comes with some pre-configured normalizers: #### DownloadRelationsNormalizer This normalizer will transform download relations to meaningful data arrays (like the `toolbox_download_info` twig helper) #### GalleryRelationsNormalizer This normalizer will transform gallery relations to thumbnail data arrays #### ImageEditableNormalizer This normalizer will transform the inline image editable to a thumbnail data array #### Custom normalizer First, you need to add your normalizer: ```yaml services: App\Normalizer\MyNormalizer: tags: - { name: toolbox.property.normalizer } ``` ```php It is still possible, to override the default mapping by using the `property_normalizer` in your element config > since those will be processed with the highest priority! --- ## Changelog(Toolbox) ### 1.2.2 - [BUGFIX] The info window of the Google Map shows the address of its location. `/toolbox/ajax/gm-info-window` accepts only POST ### 1.2.1 - [SECURITY] [OPENDXP-SA-2026-023] The iframe brick fetches no url of the own network of the server when it checks the url in the editmode - [BUGFIX] An iframe url the server cannot reach shows its error in the editmode instead of breaking it - [CHORE] Check dependencies, code and commits for security issues and attach an SBOM to each release ### 1.2.0 - [NEW FEATURE] [HIGHLIGHT] A test API for projects: a brick for each areabrick and `TeaserSnippetFactory` under `OpenDxp\Bundle\ToolboxBundle\Test` [Read more](./docs/110_Testing.md) > Test your areabricks with the Toolbox test API: a brick for each Toolbox areabrick and a `TeaserSnippetFactory`. - [NEW FEATURE] Headless: `headless.camel_case_property_names: true` outputs the names of the configuration in camelCase [Read more](./docs/90_Headless.md#property-names) - [DEPRECATION] Headless JSON with the names of the configuration (`headless.camel_case_property_names: false`, the default). Toolbox 2.0 outputs camelCase - [NEW FEATURE] Headless: `HeadlessResponse::set()` and `HeadlessResponse::remove()` change the output of a brick in its headless action [Read more](./docs/90_Headless.md#change-the-output) - [DEPRECATION] `HeadlessResponse::setConfigElementData()`, `setInlineConfigElementData()`, `setAdditionalConfigData()`, `addAdditionalConfigData()` and `setBrickConfiguration()`. Use `set()` and `remove()` - [BUGFIX] Headless: the editmode shows a placeholder image for a snippet and a renderlet instead of their JSON - [BUGFIX] The image brick renders the alternative text of the editor - [BUGFIX] A video inherited from a content main document can be overwritten - [BUGFIX] Headless: the data of a brick no longer repeats the raw content of its blocks, areablocks and columns. The content is under `elements` - [BUGFIX] Headless: empty data, offsets of columns, parameters of a video and data attributes of a gallery are objects in JSON, not arrays - [BUGFIX] The parallax container renders the images behind its sections without images in front - [BUGFIX] A teaser without a layout falls back to the layout `default` - [BUGFIX] The additional classes of a teaser snippet reach the frontend - [CHORE] Remove the dialog configuration of the parallax container section. No editmode has opened it since Toolbox 4 - [CHORE] Remove Dailymotion from the default video types. It was never active, and no layout had a template or a player for it. A project enables it like any video type of its own: `video_types.dailymotion` in `config_parameter` of the video area, a template `type_dailymotion.html.twig` in its layout and a player in its frontend - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.1.0 - [NEW FEATURE] Genius support: a Content Crafter plan can fill the Google Map and video bricks [Read more](./docs/100_Genius.md) - [ENHANCEMENT] [MIGRATION] Provide default translations for permission keys - [CHORE] Quill is no longer supported ### 1.0.3 - [ENHANCEMENT] Change to new css color variable prefix naming ### 1.0.2 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.1 - [NEW FEATURE] Add `omit_data_output` support to editable configurations - [ENHANCEMENT] Introduce `DownloadInfoServiceInterface` for `DownloadInfoService` - [BUGFIX] Fix headless response for relations editable ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Migration `dachcom-digital/toolbox` -> `open-dxp/toolbox-bundle` [#2](https://github.com/open-dxp/toolbox-bundle/pull/2) - [CHORE] Update service definitions to use OpenDxp namespace [#3](https://github.com/open-dxp/toolbox-bundle/pull/3) - [CHORE] Update template paths to use OpenDxpToolbox namespace in HeadlessDocu… [#4](https://github.com/open-dxp/toolbox-bundle/pull/4) - [CHORE] Update namespaces (config) [#5](https://github.com/open-dxp/toolbox-bundle/pull/5) - [CHORE] Namespace migrations [#6](https://github.com/open-dxp/toolbox-bundle/pull/6) - [CHORE] Migration of config namespace [#7](https://github.com/open-dxp/toolbox-bundle/pull/7) - [CHORE] Adjust test workflows [#8](https://github.com/open-dxp/toolbox-bundle/pull/8) - [CHORE] Refactor [#9](https://github.com/open-dxp/toolbox-bundle/pull/9) - [ENHANCEMENT] Changed colors to use the css variables from the admin bundle. [#10](https://github.com/open-dxp/toolbox-bundle/pull/10) - [CHORE] Fix doc paths [#11](https://github.com/open-dxp/toolbox-bundle/pull/11) - [CHORE] Update references and terminology in documentation [#12](https://github.com/open-dxp/toolbox-bundle/pull/12) --- ## Migrating to OpenDXP(Toolbox) ### Migrating from dachcom-digital/toolbox v5.x to open-dxp/toolbox-bundle 1.0 * All PHP namespaces changed to `OpenDxp\Bundle\ToolboxBundle\` * The top-level config node changed from `toolbox` to `opendxp_toolbox` (change in your yaml config) --- ## Toolbox Bundle The Toolbox is a Kickstarter for your every day project. It provides some important bricks and structure basics which allow rapid and quality-oriented web development. #### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `1.x` | `7.4` | 2025 | Feature Branch | 1.x | #### Installation ```json "require": { "open-dxp/toolbox-bundle" : "~1.1.0" } ``` Add Bundle to `bundles.php`: ```php return [ OpenDxp\Bundle\ToolboxBundle\OpenDxpToolboxBundle::class => ['all' => true], ]; ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpToolboxBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxpToolboxBundle\Migrations'` ### What's the meaning of Toolbox? - create often used bricks in a second - extend, override toolbox bricks - add config elements via yml configuration - add consistent and beautiful config elements - add your custom bricks while using the toolbox config environment - removes the default `opendxp_area_*` element wrapper from each brick ### And what's not? It's not an Avada Theme. While the Toolbox provides some basic Javascript for you, you need to implement and mostly modify them by yourself. **Frontend JS Implementation** We're providing some helpful Javascript Plugins to simplify your daily work with the ToolboxBundle. Read more about the javascript implementation [here](docs/80_Javascript.md). ### Available Toolbox Bricks The Toolbox provides a lot of [ready-to-use Bricks](docs/11_ElementsOverview.md): - Accordion - Anchor - Columns - Container - Content - Download - Gallery - Google Map - Headline - iFrame - Image - Link List - Parallax Container - Parallax Container Section - Separator - Slide Columns - Spacer - Teaser - Video ### Additional Editables - [VHS Video](docs/21_VhsElement.md) - [Google Maps Element](docs/22_GoogleMapsElement.md) ### Further Information - [Important Usage Information](docs/0_Usage.md) - [Code Style](docs/1_CodeStyle.md) - [Helper Commands](docs/2_Commands.md) - [Toolbox Elements Overview](docs/11_ElementsOverview.md) - [Wysiwyg Configuration](docs/13_Wysiwyg_Editor.md) - [Image Thumbnails Strategy](docs/14_ImageThumbnails.md) - [Configuration Context](docs/15_Context.md) - [Editable Store Provider](docs/16_EditableStoreProvider.md) - [Create a Custom Brick](docs/10_CustomBricks.md) - [Theme / Layout](docs/30_ToolboxTheme.md) - [Overriding Views](docs/31_OverridingViews.md) - [Data Attributes Generator](docs/40_DataAttributesGenerator.md) - [Column Adjuster](docs/60_ColumnAdjuster.md) - [Configuration Flags](docs/70_ConfigurationFlags.md) - [Javascript Plugins](docs/80_Javascript.md) - [Headless Mode](docs/90_Headless.md) - [Genius](docs/100_Genius.md) [Ask about page content in plain language, optional] - [Testing](docs/110_Testing.md) ### OpenDxp Fixes / Overrides - Fix the opendxp iframe [maskFrames](public/js/document/edit.js) bug (in some cases the iframe overlay field does not apply to the right position) - Transforms all the brick config buttons (`opendxp_area_edit_button_*`) to more grateful ones. ### Upgrade Info Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Bootstrap 3 Theme This is the legacy setup for bootstrap 3. ### Setup ```yaml opendxp_toolbox: theme: layout: !php/const OpenDxp\Bundle\ToolboxBundle\Manager\LayoutManagerInterface::TOOLBOX_LAYOUT_BOOTSTRAP3 calculators: column_calculator: OpenDxp\Bundle\ToolboxBundle\Calculator\Bootstrap3\ColumnCalculator slide_calculator: OpenDxp\Bundle\ToolboxBundle\Calculator\Bootstrap3\SlideColumnCalculator wrapper: googleMap: - { tag: 'div', class: 'embed-responsive embed-responsive-16by9' } video: - { tag: 'div', class: 'embed-responsive embed-responsive-16by9' } image: - { tag: 'div', class: 'row' } - { tag: 'div', class: 'col-xs-12' } columns: - { tag: 'div', class: 'row' } gallery: - { tag: 'div', class: 'row' } - { tag: 'div', class: 'col-xs-12 col-gallery' } slideColumns: - { tag: 'div', class: 'row' } teaser: - { tag: 'div', class: 'row' } - { tag: 'div', class: 'col-xs-12' } ``` ### Layout ```html {{ opendxp_head_title() }} {{ opendxp_head_meta() }} {{ opendxp_head_link() }}
{% block content %} {{ opendxp_areablock('content', toolbox_areablock_config('content')) }} {% endblock %}
``` --- ## Bootstrap 4 Theme This is the default theme so there is not too much to configure. ### Setup ```yaml opendxp_toolbox: theme: grid: grid_size: 12 breakpoints: - identifier: 'xs' name: 'Breakpoint: XS' description: 'Your Description' - identifier: 'ty' name: 'Breakpoint: TY' description: 'Your Description' - identifier: 'sm' name: 'Breakpoint: SM' description: 'Your Description' - identifier: 'md' name: 'Breakpoint: MD' description: 'Your Description' - identifier: 'lg' name: 'Breakpoint: LG' description: 'Your Description' - identifier: 'xl' name: 'Breakpoint: XL' description: 'Your Description' ``` ### Layout ```html {{ opendxp_head_title() }} {{ opendxp_head_meta() }} {{ opendxp_head_link() }}
{% block content %} {{ opendxp_areablock('content', toolbox_areablock_config('content')) }} {% endblock %}
``` --- ## Headless Theme If you want to put toolbox into headless mode, read more about it [here](../90_Headless.md). --- ## UiKit Theme ### Setup ```yaml opendxp_toolbox: theme: layout: !php/const OpenDxp\Bundle\ToolboxBundle\Manager\LayoutManagerInterface::TOOLBOX_LAYOUT_UIKIT3 calculators: column_calculator: OpenDxp\Bundle\ToolboxBundle\Calculator\UIkit3\ColumnCalculator slide_calculator: OpenDxp\Bundle\ToolboxBundle\Calculator\UIkit3\SlideColumnCalculator wrapper: image: ~ gallery: ~ slideColumns: ~ teaser: ~ columns: - {tag: 'div', class: 'uk-grid'} grid: grid_size: 12 column_store: 11: '1/1' 12: '1/2' 13: '1/3' 14: '1/4' 15: '1/5' 16: '1/6' 23: '2/3' 25: '2/5' 34: '3/4' 35: '3/5' 45: '4/5' 56: '5/6' breakpoints: - identifier: 's' name: 'Breakpoint: S' description: 'Your Description' - identifier: 'm' name: 'Breakpoint: M' description: 'Your Description' - identifier: 'l' name: 'Breakpoint: L' description: 'Your Description' - identifier: 'xl' name: 'Breakpoint: XL' description: 'Your Description' areas: columns: config_elements: type: type: select title: 'Columns' config: store: column_11: '1 Column' column_13_23: '2 Columns (33:66)' column_23_13: '2 Columns (66:33)' column_14_34: '2 Columns (25:75)' column_34_14: '2 Columns (75:25)' column_12_12: '2 Columns (50:50)' column_13_13_13: '3 Columns (33:33:33)' default: column_12_12 equal_height: ~ additional_classes: ~ slideColumns: config_elements: slides_per_view: type: select title: 'Slides per View' config: store: '2': '2 Columns' '3': '3 Columns' '4': '4 Columns' '6': '6 Columns' default: '4' equal_height: ~ additional_classes: ~ config_parameter: column_classes: ~ breakpoints: [] ``` ### Layout ```html {{ opendxp_head_title() }} {{ opendxp_head_meta() }} {{ opendxp_head_link() }}
{% block content %} {{ opendxp_areablock('content', toolbox_areablock_config('content')) }} {% endblock %}
<-- Optional: Toolbox Core --> ``` --- ## Google Maps Component This component will enable the google maps rendering. ### Enable Component ```js import {GoogleMaps} from '@open-dxp/js-toolbox'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.toolbox-googlemap').forEach((el) => { new GoogleMaps(el); }); }); ``` ### Extended Usage ```js let map = new GoogleMaps(el, { emptyInfoWindowHtml: '
', }); map.resize() ``` Use resize method e.g. for Bootstrap collapsed elements: ```js document.addEventListener('shown.bs.collapse', (ev) => { map.resize() }); ``` --- ## Video Component This component will enable the video rendering. ### Enable Extension ```js import {Video} from '@open-dxp/js-toolbox'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.toolbox-video').forEach((el) => { new Video(el); }); }); ``` ### Extended Usage ```js new Video(el, { editmode: false, videoIdExtractor: { custom: function (videoId) { console.log(videoId); return videoId; } }, resources: { youtube: 'https://www.youtube.com/iframe_api', vimeo: 'https://player.vimeo.com/api/player.js', }, apiParameter: { youtube: { rel: 0 //disable related videos }, vimeo: {} }, pingAutoPlayOnScroll: false, assetLightbox: (videoId, posterPath) => { }, assetInline: (videoId) => { }, assetPlay: () => { }, assetPause: () => { }, youtubeLightbox: (videoId, posterPath, YT) => { }, vimeoLightbox: (videoId, posterPath, Vimeo) => { }, customVideoSetup: () => { }, customVideoPlay: () => { }, customVideoPause: () => { }, }); ``` #### Video Extended I: Open Video in a Light Box If you have selected the Light Box option, you need to take care about the video by yourself: ```js new Video(el, { youtubeLightbox: (videoId, posterPath) => { // implement your own openVideo() function somewhere. openVideo('https://youtube.com/watch?v=' + videoId); }, vimeoLightbox: (videoId, posterPath) => { // implement your own openVideo() function somewhere. openVideo('https://vimeo.com/' + videoId); } }); ``` #### Video Extended II: Use OpenDXP Assets as Video If you're using OpenDXP video assets, you need to provide your own player api. OpenDXP will render a default html5 video tag in frontend. If you want to add the autoplay function, you need to add a play and pause event: ```js new Video(el, { assetPlay: () => { // hit the play button of your html5 video. // this is also the place where to trigger the play state for your custom framework (video.js for example) video.querySelector('video').play(); }, assetPause: () => { // hit the pause button of your html5 video. video.querySelector('video').pause(); } }); ``` #### Video Extended III: Use a custom player engine If you have a different engine, you need to do some further work. ##### Add some markup ```twig
``` ##### Initialize Player ```js new Video(el, { videoIdExtractor: { custom: function (videoId) { // parse your video id console.log(videoId); return videoId; } }, customVideoSetup: () => { }, customVideoPlay: () => { }, customVideoPause: () => { }, }); ``` --- ## Iframe Component This component will enable the iframe rendering. We can't provide any out-of-the-box solution for changing the iframe height dynamically (cross-domain policy), so you need to take care about that by yourself. ### Enable Extension ```js import {Iframe} from '@open-dxp/js-toolbox'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.toolbox-iframe').forEach((el) => { new Iframe(el); }); }); ``` ### Extended Usage ```js new Iframe(el, { invalidClass: 'iframe-invalid', loadedClass: 'iframe-loaded', onLoad: (iframe) => { }, onLoaded: (iframe) => { }, }); ``` --- ## Google Opt-Out Link Component This component searches for google opt-out links. By clicking on a link with the class `a.google-opt-out-link` a cookie will be stored to prevent future analytic tracking. ### Enable Extension ```js import {GoogleOptOutLink} from '@open-dxp/js-toolbox'; ``` ```js document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.google-opt-out-link').forEach((el) => { new GoogleOptOutLink(el); }); }); ``` ### Extended Usage ```js new GoogleOptOutLink(el, { editmode: false, notify: function (message) { // implement your message style here console.log(message); } }); ``` --- ## Changelog(Toolbox-js) ### 1.0.0 - [NEW FEATURE] Initial release --- ## Toolbox JavaScript Extensions We're providing some helpful Javascript Plugins to simplify your daily work with the ToolboxBundle. This Library provides all JS components for the [OpenDXP Toolbox Bundle](https://github.com/open-dxp/toolbox-bundle). ### Installation ```bash npm i @open-dxp/js-toolbox ``` ### Extensions Overview - [Google Maps Extension](./docs/01_googleMaps.md) - [Video Extension](./docs/02_video.md) - [iFrame Extension](./docs/03_iframe.md) - [Google Opt-Out Extension](./docs/04_googleOptOut.md) ### Upgrade Notes #### 1.0.0 - Initial Release *** ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2025 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Bundles Core bundles extend the platform itself. Feature bundles add complete features on top of it. --- ## Architecture(Architecture) ### What Is This Bundle? The Admin Bundle provides the **backend UI** for OpenDXP. It renders the document tree, asset manager, object editor, user management, and all other admin panels using the [ExtJS](https://www.sencha.com/products/extjs/) framework on the frontend and Symfony controllers on the backend. ### Relationship to opendxp Core This bundle depends heavily on the **opendxp core** (`open-dxp/opendxp`). The core provides: | From core | Used by admin-bundle | |---------------------------|-------------------------------------------------| | `OpenDxp\Model\*` | Document, Asset, DataObject, Site models | | `OpenDxp\Event\*` | Core events (DocumentEvents, AssetEvents, etc.) | | `OpenDxp\Controller\*` | Base controller classes | | `OpenDxp\Test\Factory\*` | Factories for test data | | `OpenDxp\Config` | Global configuration | The admin-bundle adds its **own** event layer on top (`src/Event/AdminEvents.php`) for events that are specific to the admin UI lifecycle. ### Source Layout ``` src/ ├── Attribute/ # PHP attributes driving centralized listener behavior (e.g. AsHtmlContentTypeResponse) ├── Command/ # CLI commands (e.g. cache warm-up, admin user management) ├── Controller/ │ ├── Admin/ # Admin controllers, one subfolder per element type, thin pass-throughs to Handlers │ │ ├── Asset/ │ │ ├── DataObject/ │ │ ├── Document/ # DocumentController: tree, site panel, site custom settings │ │ └── ... │ └── Traits/ # Shared controller traits ├── CustomView/ # Custom document/asset/object tree view configuration ├── DataObject/ # Grid column config element definitions shared by DataObject grid Handlers ├── DependencyInjection/ # Bundle extension + compiler passes ├── Dto/ # Data transfer objects (grid configs, site custom settings, admin bootstrap settings) ├── Enricher/ # Adds admin-only data (permissions, admin styles) to tree/editor payloads ├── Enum/ # PHP enums for typed config values ├── Event/ # Admin event classes + AdminEvents constants ├── EventListener/ # Symfony event subscribers (internal) ├── Exception/ # Admin-specific exceptions (e.g. AdminOperationFailedException) ├── Factory/ # Factories for services that can't be constructed via plain DI ├── GDPR/ # GDPR data provider integrations (export/anonymize document, asset, object, mail data) ├── Handler/ # Business logic, one invokable class per action, see below ├── Helper/ # Stateless service helpers (e.g. GridHelperService) ├── Http/ # ExtJsValueResolver: resolves Payload::fromRequest() as a controller argument ├── Model/ # Admin-only models (GridConfig, GridConfigShare, etc.) ├── Payload/ # Shared request DTOs consumed by Handlers; action-specific ones live next to their Handler ├── Perspective/ # Perspective resolution and serialization ├── Repository/ # Persistence for admin-only data (e.g. per-user dashboard config), keyed by explicit params, no bound state ├── Security/ # Admin authentication, authenticators, security tokens ├── Service/ # Application services shared across Handlers (grid data, workflow, element resolution) ├── Session/ # Session access boundary: SessionGatewayInterface/SessionIdentityInterface and their Gateway/ implementations, see below ├── System/ # System-level services ├── Translation/ # Admin translation handling └── Twig/ # Twig extensions for admin templates ``` ### Handler / Payload / Service Pattern Admin controller actions contain no business logic. Each action is a thin pass-through that resolves a typed request Payload, invokes a Handler, and maps the result to JSON: ```php #[Route('/save', name: 'save', methods: ['PUT'])] public function saveAction( SaveClassDefinitionPayload $payload, SaveClassDefinitionHandler $handler, ): JsonResponse { return $this->apiJson($handler($payload)); } ``` `AdminAbstractController::apiJson()` serializes a Handler's Result into the wire envelope `{success: true, ...resultProperties}`. Pass `rootProperty: 'nodes'` when the established wire contract for an endpoint is the bare value of a single Result property instead of the enveloped shape. For a void Handler with nothing to report, use `apiOk()` (`{success: true}`). Never build the response body by hand with `adminJson()` in a controller action, if a Result's shape does not match what an endpoint needs to return, change the Result and the Handler, not the controller. | Layer | Location | Responsibility | |------------|---------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| | Payload | `src/Payload/Common/` or colocated with a Handler | Typed request DTO. `fromRequest()` is resolved automatically by `ExtJsValueResolver` before the controller action runs, the only place request data is read. | | Handler | `src/Handler/**` | One invokable (`__invoke`) class per action. Holds all business logic. Transport-agnostic, never receives the HTTP `Request`. | | Result | colocated with its Handler | Typed return value, mapped to a JSON response by the controller. | | Service | `src/Service/**` | Logic shared across multiple Handlers (grid data assembly, workflow resolution, element resolution). | | Repository | `src/Repository/**` | Persistence only. | | Enricher | `src/Enricher/**` | Adds admin-only presentation data (permissions, admin styles) to tree/editor node data, shared across Handlers. | **Error handling:** Handlers always throw on failure, they never return a `success: false` or `errorMessage` field. `AdminExceptionListener` converts any exception raised during an admin XHR request into `{success: false, message, ...}` JSON at the exception's real HTTP status. #### AdminOperationFailedException For an expected, recoverable business-rule failure that the admin UI handles locally as `success: false` at HTTP 200, not a real HTTP error, throw `OpenDxp\Bundle\AdminBundle\Exception\AdminOperationFailedException` instead of a generic exception; the listener maps it to 200 explicitly rather than a 4xx/5xx status. #### ElementLockedException Some exceptions carry their own dedicated response shape instead of the generic `{success: false, message}` body: `OpenDxp\Bundle\AdminBundle\Exception\ElementLockedException` is mapped by the listener to a 200 response with an `editlock` payload, which the admin UI uses to show the lock dialog. ### Session Access Controllers and Payloads never touch Symfony's HTTP session (`SessionInterface`, `AttributeBagInterface`, `Request::getSession()`), not even to read it. A Payload only carries values taken from the current `Request`; anything session-derived is looked up by the Handler itself, at the point it is actually needed. Only two kinds of classes may reference session storage: 1. **A Gateway** implementing `OpenDxp\Bundle\AdminBundle\Session\SessionGatewayInterface`, living in `src/Session/Gateway/`. Each Gateway wraps exactly one session bag (see the `BAG_*` constants on `SessionGatewayInterface` for the full list of bags in use) behind a small, domain-named API, e.g. `CopySessionGateway::rememberParentId()`, not a raw `get()`/`set()`. Handlers and Services inject the Gateway they need. 2. **`OpenDxp\Bundle\AdminBundle\Session\SessionIdentityInterface`**, for the narrower case of needing only the current session id as a correlation token (lock ownership, bootstrap settings), not a session value. Carries no mutable state, so it may be injected anywhere. Controller actions never contain session code, not even a call into a Gateway. Since that means an endpoint's session footprint is otherwise invisible without opening its Handler, mark the action with an attribute instead: ```php #[SessionGatewayAware(CopySessionGateway::class)] #[Route('/copy', name: 'opendxp_admin_asset_copy', methods: ['POST'])] public function copyAction(CopyAssetPayload $payload, CopyAssetHandler $handler): JsonResponse { $handler($payload); return $this->apiOk(); } ``` Use `#[SessionIdentityAware]` (no argument) when only `SessionIdentityInterface` is involved. ### Frontend Assets JavaScript and CSS live in `public/js/` and `public/css/`. The bundle uses [Webpack Encore](https://symfony.com/doc/current/frontend/encore/simple-example.html) (`webpack.config.js`) for asset compilation. Key JS entry points: - `public/js/opendxp/events.js`: all frontend event constants - `public/js/opendxp/document/tree.js`: document tree rendering ### Configuration Namespace The bundle registers its configuration under `opendxp_admin`: ```yaml opendxp_admin: custom_admin_path_identifier: ~ custom_admin_route_name: ~ user: default_key_bindings: ~ ``` --- ## Admin Events All event constants for the admin-bundle are defined in [`src/Event/AdminEvents.php`](https://github.com/open-dxp/admin-bundle/blob/1.x/src/Event/AdminEvents.php). ### How to Subscribe Implement `EventSubscriberInterface` in your bundle and return the event constant(s) you want to handle: ```php 'onPreSendData', ]; } public function onPreSendData(ElementAdminStyleEvent $event): void { // ... } } ``` Symfony autoconfiguration registers the subscriber automatically when `EventSubscriberInterface` is implemented. ### Event Categories #### Document Events | Constant | Event Class | Description | |----------------------------------|-------------|------------------------------------------------| | `DOCUMENT_GET_PRE_SEND_DATA` | — | Before document data is sent to the frontend | | `DOCUMENT_LIST_BEFORE_LIST_LOAD` | — | Before document listing is loaded | | `DOCUMENT_LIST_AFTER_LIST_LOAD` | — | After document listing is loaded | | `DOCUMENT_GET_IS_LOCKED` | — | Before the edit lock is handled for a document | #### Asset Events | Constant | Event Class | Description | |-------------------------------|-------------|----------------------------------------------| | `ASSET_GET_PRE_SEND_DATA` | — | Before asset data is sent to the frontend | | `ASSET_LIST_BEFORE_LIST_LOAD` | — | Before asset listing is loaded | | `ASSET_LIST_AFTER_LIST_LOAD` | — | After asset listing is loaded | | `ASSET_GET_IS_LOCKED` | — | Before the edit lock is handled for an asset | #### Object Events | Constant | Event Class | Description | |--------------------------------|-------------|---------------------------------------------------| | `OBJECT_GET_PRE_SEND_DATA` | — | Before data object data is sent to the frontend | | `OBJECT_LIST_BEFORE_LIST_LOAD` | — | Before object listing is loaded | | `OBJECT_LIST_AFTER_LIST_LOAD` | — | After object listing is loaded | | `OBJECT_GET_IS_LOCKED` | — | Before the edit lock is handled for a data object | #### Element Style Events | Constant | Event Class | Description | |----------------------------------------|--------------------------|--------------------------------------------------------| | `ELEMENT_ADMIN_STYLE_GET_FOR_DOCUMENT` | `ElementAdminStyleEvent` | Customize admin style (icon, CSS class) for a document | | `ELEMENT_ADMIN_STYLE_GET_FOR_ASSET` | `ElementAdminStyleEvent` | Customize admin style for an asset | | `ELEMENT_ADMIN_STYLE_GET_FOR_OBJECT` | `ElementAdminStyleEvent` | Customize admin style for a data object | #### Login Events | Constant | Event Class | Description | |---------------------|-------------------------------|---------------------------------------| | `LOGIN_CREDENTIALS` | `Login\LoginCredentialsEvent` | After login credentials are submitted | | `LOGIN_FAILED` | `Login\LoginFailedEvent` | After a failed login attempt | #### Perspective Events | Constant | Event Class | Description | |--------------------------------|-------------|----------------------------------------------| | `PERSPECTIVE_PRE_GET_RUNTIME` | — | Before perspective runtime data is assembled | | `PERSPECTIVE_POST_GET_RUNTIME` | — | After perspective runtime data is assembled | #### Site Events | Constant | Event Class | Description | |------------------------|---------------------------|-----------------------------------------------------------------------------------| | `SITE_CUSTOM_SETTINGS` | `SiteCustomSettingsEvent` | Fired when the site panel renders or saves, allows injecting custom config fields | See [Site Custom Settings](../20_Documents/01_Site_Custom_Settings.md) for a full example. ### See Also - [AdminEvents source](https://github.com/open-dxp/admin-bundle/blob/1.x/src/Event/AdminEvents.php) - [Core events (non-admin)](https://github.com/open-dxp/opendxp/blob/1.x/doc/20_Extending_OpenDxp/11_Event_API_and_Event_Manager.md) --- ## Loading Assets in the Admin UI If you need to load custom JS or CSS into the admin or editmode UI, you have two options. ### Option 1: Via OpenDXP Bundle Interface (recommended) Add [`OpenDxpBundleAdminClassicInterface`](https://github.com/open-dxp/opendxp/blob/1.x/lib/Extension/Bundle/OpenDxpBundleAdminClassicInterface.php) to your bundle class. Use [`BundleAdminClassicTrait`](https://github.com/open-dxp/opendxp/blob/1.x/lib/Extension/Bundle/Traits/BundleAdminClassicTrait.php) to implement the four required methods: ```php use OpenDxp\Extension\Bundle\AbstractOpenDxpBundle; use OpenDxp\Extension\Bundle\OpenDxpBundleAdminClassicInterface; use OpenDxp\Extension\Bundle\Traits\BundleAdminClassicTrait; class MyBundle extends AbstractOpenDxpBundle implements OpenDxpBundleAdminClassicInterface { use BundleAdminClassicTrait; public function getJsPaths(): array { return ['/bundles/mybundle/js/admin.js']; } public function getCssPaths(): array { return ['/bundles/mybundle/css/admin.css']; } } ``` #### With Webpack Encore Use [`EncoreHelper`](https://github.com/open-dxp/opendxp/blob/1.x/lib/Helper/EncoreHelper.php) to resolve built file paths from `entrypoints.json`: ```php use OpenDxp\Helper\EncoreHelper; public function getJsPaths(): array { return EncoreHelper::getBuildPathsFromEntrypoints( $this->getPath() . '/public/build/mybundle/entrypoints.json' ); } public function getCssPaths(): array { return EncoreHelper::getBuildPathsFromEntrypoints( $this->getPath() . '/public/build/mybundle/entrypoints.json', 'css' ); } ``` ### Option 2: Via Event Listener Subscribe to events from [`BundleManagerEvents`](https://github.com/open-dxp/opendxp/blob/1.x/lib/Event/BundleManagerEvents.php): ```php 'onJsPaths', BundleManagerEvents::CSS_PATHS => 'onCssPaths', ]; } public function onJsPaths(PathsEvent $event): void { $event->addPaths(['/bundles/app/js/admin.js']); } public function onCssPaths(PathsEvent $event): void { $event->addPaths(['/bundles/app/css/admin.css']); } } ``` Assets registered via either method are loaded last on OpenDXP startup, in registration order. ### See Also - [Admin UI JavaScript](03_Admin_UI_JavaScript.md) — how to use the loaded JS to extend the UI - [BundleManagerEvents source](https://github.com/open-dxp/opendxp/blob/1.x/lib/Event/BundleManagerEvents.php) --- ## Admin UI JavaScript The OpenDXP backend UI is built with [ExtJS](https://www.sencha.com/products/extjs/). Custom JS loaded via [Admin UI Assets](02_Admin_UI_Assets.md) runs in the same context and can hook into the admin lifecycle using the event system defined in [`public/js/opendxp/events.js`](https://github.com/open-dxp/admin-bundle/blob/1.x/public/js/opendxp/events.js). ### Listening to the Ready Event The entry point for any UI extension is `opendxp.events.opendxpReady`: ```javascript document.addEventListener(opendxp.events.opendxpReady, (e) => { console.log('OpenDXP is ready', e.detail); }); ``` ### Validating Object Data Before Save Use `preventDefault()` and `stopPropagation()` to cancel a save: ```javascript document.addEventListener(opendxp.events.preSaveObject, (e) => { const confirmed = confirm(`Save ${e.detail.object.data.general.className}?`); if (!confirmed) { e.preventDefault(); e.stopPropagation(); opendxp.helpers.showNotification(t('Info'), t('saving_failed'), 'info'); } }); ``` ### Adding a Main Navigation Item Hook into `opendxp.events.preMenuBuild` to add top-level navigation: ```javascript opendxp.plugin.mybundle = Class.create({ initialize: function () { document.addEventListener(opendxp.events.preMenuBuild, this.preMenuBuild.bind(this)); }, preMenuBuild: function (e) { let menu = e.detail.menu; menu.mybundle = { label: t('myBundleLabel'), iconCls: 'opendxp_main_nav_icon_myIcon', priority: 42, items: [], shadow: false, handler: this.openMyBundle, noSubmenus: true, cls: 'opendxp_navigation_flyout', }; }, openMyBundle: function (e) { try { opendxp.globalmanager.get('plugin_opendxp_mybundle').activate(); } catch (e) { opendxp.globalmanager.add('plugin_opendxp_mybundle', new opendxp.plugin.mybundle()); } } }); var myBundle = new opendxp.plugin.mybundle(); ``` ### Adding a Submenu to an Existing Menu Push into an existing menu's `items` array: ```javascript opendxp.registerNS('opendxp.bundle.glossary.startup'); opendxp.bundle.glossary.startup = Class.create({ initialize: function () { document.addEventListener(opendxp.events.preMenuBuild, this.preMenuBuild.bind(this)); }, preMenuBuild: function (e) { let menu = e.detail.menu; const user = opendxp.globalmanager.get('user'); const perspectiveCfg = opendxp.globalmanager.get('perspective'); if (menu.extras && user.isAllowed('glossary') && perspectiveCfg.inToolbar('extras.glossary')) { menu.extras.items.push({ text: t('glossary'), iconCls: 'opendxp_nav_icon_glossary', priority: 5, itemId: 'opendxp_menu_extras_glossary', handler: this.editGlossary, }); } }, editGlossary: function () { try { opendxp.globalmanager.get('bundle_glossary').activate(); } catch (e) { opendxp.globalmanager.add('bundle_glossary', new opendxp.bundle.glossary.settings()); } } }); const opendxpBundleGlossary = new opendxp.bundle.glossary.startup(); ``` ### Adding Custom Key Bindings Define the key binding in `config.yaml`: ```yaml opendxp_admin: user: default_key_bindings: glossary: key: 'G' action: glossary # must match the function name added to keyBindingMapping alt: true shift: true ``` Then register the binding in JS using `opendxp.events.preRegisterKeyBindings`: ```javascript opendxp.bundle.glossary.startup = Class.create({ initialize: function () { document.addEventListener(opendxp.events.preRegisterKeyBindings, this.registerKeyBinding.bind(this)); }, registerKeyBinding: function (e) { const user = opendxp.globalmanager.get('user'); if (user.isAllowed('glossary')) { opendxp.helpers.keyBindingMapping.glossary = function () { opendxpBundleGlossary.editGlossary(); }; } } }); ``` ### I18n in JavaScript Translations registered server-side are available via `t()`: ```javascript t('my_translation_key') ``` See [opendxp/doc — i18n for bundles](https://github.com/open-dxp/opendxp/blob/1.x/doc/06_Multi_Language_i18n/07_Admin_Translations.md) for how to register translation keys server-side. ### See Also - [Admin UI Assets](02_Admin_UI_Assets.md) — how to load your JS files - [events.js source](https://github.com/open-dxp/admin-bundle/blob/1.x/public/js/opendxp/events.js) --- ## Perspectives Perspectives allow creating different views in the backend UI and customizing the standard layout. They can be combined with [Custom Views](https://github.com/open-dxp/opendxp/blob/1.x/doc/05_Objects/01_Object_Classes/05_Class_Settings/20_Custom_Views.md). > **Security Note** > Perspectives and Custom Views are not intended to restrict access to data — use permissions for that. You can define per-perspective: - Which trees are visible and where (left/right) - Which toolbar menus and items are shown - Which portlets are available on the dashboard - Navigation and welcome screen elements Access to individual perspectives can be restricted via user/role settings. ### Configuration File The configuration lives in `var/config/perspectives/` (YAML format). Format follows the environment configuration — see [Configuration Environments](https://github.com/open-dxp/opendxp/blob/1.x/doc/21_Deployment/03_Configuration_Environments.md). ### Configuration Reference | Key | Type | Description | |--------------------------------------------------|---------|---------------------------------------------------| | `[name]["icon"]` | string | Path to perspective icon | | `[name]["iconCls"]` | string | CSS class for the icon | | `[name]["elementTree"]` | array | Tree definitions (type, position, expanded, etc.) | | `[name]["elementTree"][i]["type"]` | string | `documents`, `objects`, `assets`, `customview` | | `[name]["elementTree"][i]["position"]` | string | `left` or `right` | | `[name]["elementTree"][i]["id"]` | integer | Custom view ID (only for type `customview`) | | `[name]["toolbar"]` | array | Per-menu visibility and item configuration | | `[name]["toolbar"][menuName]["hidden"]` | boolean | Hide the entire menu | | `[name]["toolbar"][menuName]["items"][itemName]` | boolean | Show/hide individual items | ### Example A catalog-admin perspective that shows only a product custom view and assets: **Custom view** (`var/config/perspectives/perspective.yaml`): ```yaml 4e9f892c-7734-f5fa-d6f0-31e7f9787ffc: name: Cars treetype: object position: left rootfolder: '/Product Data/Cars' showroot: false sort: 3 icon: /bundles/opendxpadmin/img/flat-white-icons/automotive.svg classes: CAR ``` **Perspective** (`var/config/perspectives/example.yaml`): ```yaml demo: elementTree: - type: customview position: left sort: 0 expanded: false hidden: false id: 4e9f892c-7734-f5fa-d6f0-31e7f9787ffc - type: assets position: right sort: 0 expanded: false hidden: false iconCls: opendxp_nav_icon_perspective toolbar: file: hidden: true marketing: hidden: true extras: hidden: true settings: hidden: true search: hidden: false items: quickSearch: false documents: true assets: false objects: false ``` ### Perspective Events Subscribe to `AdminEvents::PERSPECTIVE_PRE_GET_RUNTIME` or `AdminEvents::PERSPECTIVE_POST_GET_RUNTIME` to modify perspective data programmatically. See [01_Events.md](01_Events.md) for subscription examples. ### See Also - [AdminEvents](01_Events.md) - [Custom Views](https://github.com/open-dxp/opendxp/blob/1.x/doc/05_Objects/01_Object_Classes/05_Class_Settings/20_Custom_Views.md) --- ## Custom Permissions You can add custom permission keys to OpenDXP that appear in the user/role settings panel and can be checked both server-side and client-side. ### Step 1: Register the Permission Add your permission key to the `users_permission_definitions` table: ```sql INSERT INTO users_permission_definitions (key) VALUES ('my_custom_permission'); ``` After this, the permission appears in the Users/Roles admin panel and can be assigned. ### Step 2: Check the Permission Server-Side Inside an admin controller that extends `UserAwareController`: ```php if ($this->getOpenDxpUser()?->isAllowed('my_custom_permission')) { // authorized } ``` ### Step 3: Check the Permission Client-Side In your bundle's JavaScript (loaded via [Admin UI Assets](02_Admin_UI_Assets.md)): ```javascript const user = opendxp.globalmanager.get('user'); if (user.isAllowed('my_custom_permission')) { // user has the permission, show/enable UI element } ``` ### Using Symfony's Authorization Layer For `#[IsGranted]` and `Security::isGranted()` instead of manual `isAllowed()` calls, see [Permission Voters](https://github.com/open-dxp/opendxp/blob/1.x/doc/19_Development_Tools_and_Details/10_Security_Authentication/10_Permission_Voters.md) in opendxp core. ### See Also - [Admin UI JavaScript](03_Admin_UI_JavaScript.md) - [Users & Roles](https://github.com/open-dxp/opendxp/blob/1.x/doc/22_Administration_of_OpenDxp/07_Users_and_Roles.md) --- ## Deeplinks Into the Admin Interface OpenDXP supports deeplinks that open a specific element directly inside the admin UI from an external application. ### URL Schema ``` https://YOUR-HOST/admin/login/deeplink?TYPE_ID_SUBTYPE ``` ### Examples #### Documents ```text https://acme.com/admin/login/deeplink?document_123_page https://acme.com/admin/login/deeplink?document_45_snippet https://acme.com/admin/login/deeplink?document_67_link https://acme.com/admin/login/deeplink?document_8_hardlink https://acme.com/admin/login/deeplink?document_9_email ``` #### Assets ```text https://acme.com/admin/login/deeplink?asset_23_image https://acme.com/admin/login/deeplink?asset_34_document https://acme.com/admin/login/deeplink?asset_56_folder https://acme.com/admin/login/deeplink?asset_78_video ``` #### Data Objects ```text https://acme.com/admin/login/deeplink?object_24_object https://acme.com/admin/login/deeplink?object_98_variant https://acme.com/admin/login/deeplink?object_66_folder ``` ### Behaviour If the user is not yet logged in, the deeplink URL redirects to the login page first and then opens the target element after successful authentication. --- ## Custom Admin Login Entry Point The default admin login is served at `/admin`. You can change this to a custom path to reduce exposure of the admin panel. ### Configuration Add the custom identifier to `config/config.yaml`: ```yaml opendxp_admin: custom_admin_path_identifier: min20CharCustomToken ``` > `custom_admin_path_identifier` must be at least 20 characters long. ### Custom Route Add a custom route entry in `config/routes.yaml`: ```yaml my_custom_admin_entry_point: path: /my-custom-login-page controller: OpenDxp\Bundle\CoreBundle\Controller\PublicServicesController::customAdminEntryPointAction ``` When this route is called, an admin cookie is set in the browser which is then validated for all subsequent `/admin` calls. ### Custom Route Name If you want to use a different route name (e.g. for the "login as user" link in user administration): ```yaml opendxp_admin: custom_admin_route_name: myCustomAdminRoute ``` --- ## Grid Export Every grid of the admin exports its rows through one export. The editor picks CSV or XLSX, the header and, in a grid with a checkbox column, whether only the selected rows go into the file. The export holds the rows that the grid shows: its filters, its search and its sorting. The admin writes an export in batches, one request per batch, and shows the progress in a window. Above a number of rows, it asks before it starts. ### Formats - CSV starts with a UTF-8 byte order mark, so Excel reads umlauts. The editor picks the delimiter. - XLSX keeps the type of each value: numbers, dates and booleans stay numbers, dates and booleans. The header row stays visible while scrolling and filters its column. - A value that starts like a formula, for example with `=`, stays text in both formats. ### Header The editor picks the first row of the file. `GridExportHeader` names the choice in code: - Label (`LABEL`) writes the labels of the columns, as the grid shows them. This is the default. - System Key (`KEY`) writes the keys of the columns, for example the names of the fields of an object. - No Header (`NONE`) writes no header row. ### Configure the confirmation The admin asks before it exports more rows than this: ```yaml opendxp_admin: grid_export: confirm_threshold: 1000 ``` ### Run exports in the background With background jobs, every export runs as a job run of the Generic Execution Engine. The editor goes on working, and a worker writes the file. The menu of the job runs shows the progress and offers the download at the end. The job run disappears once the file is downloaded. ```yaml opendxp_admin: background_jobs: enabled: true ``` - The option is off by default. A worker consumes the transport `opendxp_generic_execution_engine`. Without a worker, the export does not start. - An export runs in the browser when the engine is not installed. - The job run uses the execution context `admin_grid_export`. It fails at its first error. ### Add a source A source provides the rows of one grid. It implements `GridExportSourceInterface`, and the attribute `#[AsGridExportSource]` registers it: ```php createListing($query)->getTotalCount(); } public function getRows(GridExportQuery $query, int $offset, int $limit): iterable { $listing = $this->createListing($query); $listing->setOffset($offset); $listing->setLimit($limit); foreach ($listing as $product) { yield [ 'sku' => $product->getSku(), 'price' => $product->getPrice(), ]; } } private function createListing(GridExportQuery $query): Product\Listing { $listing = new Product\Listing(); if ($query->selectedIds !== []) { $listing->setCondition('oo_id IN (?)', [$query->selectedIds]); } return $listing; } } ``` - The name identifies the source in the requests of the admin. - A user needs the permission to start an export. It is an attribute of the Symfony security, like the ones of `CorePermission`. - `batchSize` limits the rows of one request. It defaults to 500. - `GridExportQuery` holds the parameters of the grid, the selected IDs, the user, the language and the timezone. A source reads the rows the same way the grid lists them. - Every row holds the value of each column under the key of the column. The export stops when a row misses a column or holds one that the source does not declare. - A value matches the type of its column. A date is a `DateTimeInterface`, and `null` stands for an empty value. ### Read the session in a source A job run has no session. A source that needs a value from the session of the admin implements `SessionGridExportSourceInterface` in addition: ```php public function getSessionParameters(GridExportQuery $query): array { return ['currency' => $this->requestStack->getSession()->get('currency')]; } ``` - The export calls `getSessionParameters()` once when it starts, before it asks for the columns. - `GridExportQuery::$sessionParameters` holds the values. The source reads them there in the browser and in a job run. - The export keeps the query in the TmpStore. A value is a scalar, an array or `null`, but no object. - The objects source keeps the definitions of the operator columns there. An operator column without a definition stops the export. ### Start an export in the admin `opendxp.element.gridexport.runner` asks for the settings, writes the batches and downloads the file. With the Generic Execution Engine, it starts a job run instead: ```javascript new opendxp.element.gridexport.runner({ source: 'products', getParameters: function () { return opendxp.element.gridexport.runner.getStoreParameters(this.store); }.bind(this), filters: {filter: ''}, getSelectedIds: function () { return this.grid.getSelectionModel().getSelection().map(function (record) { return record.get('id'); }); }.bind(this) }).start(); ``` - `getStoreParameters()` returns what the store of a grid sends to load its rows: the extra parameters, the filters and the sorting. - `filters` maps each parameter that filters the grid to its value without a filter. When a parameter holds another value, the admin asks whether the export holds only the filtered rows. With "All rows", the export sets these parameters back to their value without a filter. - `getSelectedIds` belongs only to a grid with a checkbox column. When the editor selected rows, the admin asks whether the export holds only them. - `warnings` shows a note per format on top of the dialog, for example `{csv: t('my_csv_note')}`. - `settings` adds fields of the grid to the dialog. Their values go into the parameters. ### Test a source `GridExports::export()` runs an export and returns its file. `GridExportFile` reads its rows: ```php use OpenDxp\Bundle\AdminBundle\Test\GridExport\GridExports; it('exports the price of a product', function () { ProductFactory::createOne(['sku' => 'A-1', 'price' => 9.5]); $file = GridExports::export($this->admin, 'products'); expect($file) ->getColumn('Price') ->toBe(['9.5']); }); ``` --- ## Extension Points This section documents how other bundles and applications can extend or customize the admin UI provided by this bundle. ### Overview The admin-bundle exposes extension points at two levels: **PHP (server-side)** - Event system via `AdminEvents` constants and typed event classes - Custom permissions registered in the database **JavaScript (client-side)** - JS/CSS injection into the admin UI via bundle interface or event listeners - ExtJS UI events for adding menus, panels, key bindings ### Topics | # | Topic | Summary | |---------------------------------|---------------------|------------------------------------------------------------------| | [01](01_Events.md) | Events | All `AdminEvents` constants, when they fire, subscriber examples | | [02](02_Admin_UI_Assets.md) | Admin UI Assets | How to load custom JS and CSS into the admin backend | | [03](03_Admin_UI_JavaScript.md) | Admin UI JavaScript | ExtJS events, adding navigation items, key bindings | | [04](04_Perspectives.md) | Perspectives | Configuring different backend UI layouts | | [05](05_Permissions.md) | Permissions | Adding custom permission keys | | [06](06_Deeplinks.md) | Deeplinks | Linking directly into admin from external apps | | [07](07_Custom_Admin_Login.md) | Custom Admin Login | Changing the `/admin` entry point | | [08](08_Grid_Export.md) | Grid Export | Exporting the rows of a grid, adding a source for a grid | ### How Events Work The admin-bundle follows the standard Symfony event dispatcher pattern. Event constants are defined as `public const string` on `AdminEvents`. Event classes live in `src/Event/` and extend `Symfony\Contracts\EventDispatcher\Event`. Other bundles subscribe to admin events by implementing `EventSubscriberInterface`: ```php use OpenDxp\Bundle\AdminBundle\Event\AdminEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class MyListener implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ AdminEvents::SOME_EVENT => 'onSomeEvent', ]; } public function onSomeEvent(SomeAdminEvent $event): void { // ... } } ``` Register the listener in your bundle's `services.yaml` — Symfony autoconfiguration picks up `EventSubscriberInterface` automatically. --- ## Site Custom Settings The site configuration panel in the admin UI can be extended with custom fields by subscribing to the `AdminEvents::SITE_CUSTOM_SETTINGS` event. This allows other bundles to add their own configuration fields (inputs, dropdowns, checkboxes) that are stored per-site in `Site::getCustomSettings()`. ### When the Event Fires The event fires in two situations: 1. **GET** — when the site panel renders (`getSiteCustomSettingsAction`), to know which fields to display 2. **PUT** — when the site is saved (`updateSiteAction`), to know which request values to persist ### API Reference #### `AdminEvents::SITE_CUSTOM_SETTINGS` ```php use OpenDxp\Bundle\AdminBundle\Event\AdminEvents; AdminEvents::SITE_CUSTOM_SETTINGS // 'opendxp.admin.site.customSettings' ``` #### `SiteCustomSettingsEvent` | Method | Description | |---------------------------------------------------|-----------------------------------------| | `getSite(): Site` | The site being configured | | `addConfigNode(config, scope, name, label): void` | Register a custom field | | `getConfigNodes(): array` | All registered fields, grouped by scope | #### `addConfigNode()` Parameters | Parameter | Type | Description | |-----------|-----------------------|------------------------------------------------------------------------------------------| | `$config` | `NodeConfigInterface` | Typed DTO — determines field type and available options | | `$scope` | `string` | Groups fields in the panel (e.g. `'app'`, `'seo'`); used as key when reading back values | | `$name` | `string` | Field identifier within the scope | | `$label` | `string` | Display label in the UI | #### Config DTOs (`src/Dto/SiteCustomSettings/`) Each DTO corresponds to one ExtJS field type and exposes only the options that are valid for it: | DTO | ExtJS type | Options | |----------------------|-------------|---------------------------------------------------| | `InputNodeConfig` | `textfield` | `required` | | `TextNodeConfig` | `textarea` | `required` | | `CheckboxNodeConfig` | `checkbox` | `checkedValue`, `uncheckedValue` | | `DropdownNodeConfig` | `combobox` | `store`, `required`, `displayField`, `valueField` | ### Stored Data Values are persisted via `Site::setCustomSettings()` after save, grouped by scope. #### Reading Values `getCustomSettings()` accepts an optional scope argument: ```php $site = Site::getById($id); // read a single scope — returns [] if the scope doesn't exist $appSettings = $site->getCustomSettings('app'); $zone = $appSettings['zone'] ?? null; // read all scopes at once $all = $site->getCustomSettings(); // $all === ['app' => ['zone' => 'store'], 'seo' => ['tracking_id' => 'UA-123']] ``` ### Example: Adding a Zone Dropdown ```php 'addZoneConfig', ]; } public function addZoneConfig(SiteCustomSettingsEvent $event): void { $event->addConfigNode( config: new DropdownNodeConfig( store: [ ['label' => 'Zone 1', 'value' => 'zone_1'], ['label' => 'Zone 2', 'value' => 'zone_2'], ], required: true, ), scope: 'app', name: 'zone', label: 'Zone', ); } } ``` ### Multiple Scopes Multiple bundles can each add their own scoped fields independently: ```php // Bundle A $event->addConfigNode(new InputNodeConfig(), 'seo', 'tracking_id', 'GA Tracking ID'); // Bundle B $event->addConfigNode(new CheckboxNodeConfig(), 'myapp', 'feature_enabled', 'Enable Feature'); ``` Results in: ```php $site->getCustomSettings() === [ 'seo' => ['tracking_id' => 'UA-123456'], 'myapp' => ['feature_enabled' => '1'], ] ``` ### See Also - [`AdminEvents::SITE_CUSTOM_SETTINGS` source](https://github.com/open-dxp/admin-bundle/blob/1.x/src/Event/AdminEvents.php) - [`SiteCustomSettingsEvent` source](https://github.com/open-dxp/admin-bundle/blob/1.x/src/Event/SiteCustomSettingsEvent.php) - [Config DTOs source](https://github.com/open-dxp/admin-bundle/blob/1.x/src/Dto/SiteCustomSettings/) - [Admin Events overview](../10_Extension_Points/01_Events.md) --- ## Documents Admin UI features specific to document and site management. | Topic | Description | |----------------------------------------------------|-------------------------------------------------------------------| | [Site Custom Settings](01_Site_Custom_Settings.md) | Inject custom fields into the site configuration panel via events | --- ## Testing(Testing) The admin bundle ships classes to test a grid export source, in the namespace `OpenDxp\Bundle\AdminBundle\Test\GridExport`. This page builds on [Testing](https://docs.opendxp.io/docs/core-framework/Development_Tools_and_Details/Testing). ### Test API | Class | What it gives | |------------------|-------------------------------------------------------------------------------------------------------------------------------------------| | `GridExports` | `export()` runs an export of a source for a user and returns its file. | | `GridExportFile` | `getRows()`, `getHeader()` and `getColumn()` read the rows of a CSV or XLSX file. `getWorksheet()` returns the sheet XML of an XLSX file. | [Test a source](../10_Extension_Points/08_Grid_Export.md#test-a-source) shows a test. ### The suite of this bundle | Test case | Directory | Why it differs | |----------------------------------|----------------------------|---------------------------------------------------------------------------------------------| | `GenericExecutionEngineTestCase` | `Feature/GridExportJobRun` | The tests handle job messages like a worker, in the environment `generic_execution_engine`. | | `LoginLinkTestCase` | `Feature/LoginLink` | It resolves the host of a login link against sites and providers. | The logic of the bundle lives in `src/Handler/` and `src/Service/`, not in the controllers. Test a handler or a service directly. Test through a request when the request itself matters, for example the permission check of a controller or what the tree lists for a user. A payload reads a request in `fromRequest()`. Test that method in `tests/Unit` with a `Request` of your own. --- ## Changelog(Admin) ### 1.5.5 - [SECURITY] [OPENDXP-SA-2026-027] The public route that serves a rendered version diff hands out only the diff files, not every file that lies in the temp directory - [SECURITY] [OPENDXP-SA-2026-028] Deleting or editing a version requires the `versions` permission of the element, as listing its versions already does - [SECURITY] [OPENDXP-SA-2026-028] Publishing a version, comparing two document versions or loading a document version into the editor requires the `versions` permission of the element - [SECURITY] [OPENDXP-SA-2026-029] Creating or updating an object brick requires the `objectbricks` permission, like importing and deleting one already does - [SECURITY] [OPENDXP-SA-2026-030] Uploading or deleting the custom logo requires the `system_appearance_settings` permission, like changing the other appearance settings already does - [SECURITY] [OPENDXP-SA-2026-031] Importing quantity value units requires the `quantityValueUnits` permission, like managing them in the unit proxy already does - [ENHANCEMENT] Tabs of the object editor open faster. A text without an admin translation is looked up directly in the catalogue, instead of in a list of all its keys - [ENHANCEMENT] A localized field with a language dropdown builds a language when it is selected, not every language when the tab opens - [BUGFIX] The admin checks for new notifications only once the current user is loaded, so switching the browser tab while the admin starts throws no error - [BUGFIX] A panel with an even padding gets the same padding inside its body, so its content no longer touches the edge of the white area - [BUGFIX] An admin request that ends in a message for the user, such as a failed validation, an element that another session is editing or a configuration that cannot be written, is logged at info or warning level, no longer as a critical uncaught exception - [BUGFIX] The log entry of a failed admin operation names the error that caused it - [BUGFIX] The template dropdown of a document type lists the available templates ### 1.5.4 - [SECURITY] [OPENDXP-SA-2026-017] The date filter of the note list takes its property as a column name, never as SQL - [BUGFIX] The 2FA code field shows the typed digits, and browsers no longer fill the saved password into it - [CHORE] Check dependencies, code and commits for security issues ### 1.5.3 - [BUGFIX] Saving the own profile changes only the fields of the profile form - [BUGFIX] Only an admin resets the 2FA of an admin - [BUGFIX] A user can no longer delete its own user - [BUGFIX] The YouTube preview of a video field also plays when the admin sends a strict `Referrer-Policy`, such as `same-origin` ### 1.5.2 - [BUGFIX] Trees without a root node show the whole expander of top-level folders - [BUGFIX] The custom logo also shows when the admin storage is on S3 - [BUGFIX] Block items keep their data after an auto save - [BUGFIX] Closing an object removes the save listener of its field collections - [BUGFIX] Saving an object whose draft no longer fits the changes keeps the changes - [CHORE] Require `open-dxp/opendxp` ^1.5.3 ### 1.5.1 - [ENHANCEMENT] The slug field offers only the sites of its language and shows a row for every site with another prefix - [ENHANCEMENT] The slug field shows the message of a slug generator that fails, and the object still opens - [ENHANCEMENT] `opendxp_callout` with `opendxp_callout_info`, `opendxp_callout_warning` and `opendxp_callout_error` shows a notice in the admin. `opendxp_grid_export_warning` is deprecated and 2.0 removes it, use `opendxp_callout opendxp_callout_warning` instead - [CHORE] Require `open-dxp/opendxp` ^1.5.1 - [BUGFIX] The image editor shows an image whose preview thumbnail is not generated yet instead of a broken image [#157](https://github.com/open-dxp/admin-bundle/issues/157) - [BUGFIX] Correct German translation of `no_items_found` ### 1.5.0 - [SECURITY] [OPENDXP-SA-2026-005] The notification grid filters only by title and date - [CHORE] Conflict with `open-dxp/advanced-object-search-bundle` <1.1. Its result grid uses the export routes that 1.5 removes. - [BUGFIX] Notes on documents and on objects offer the note types configured for their own element type [#152](https://github.com/open-dxp/admin-bundle/pull/152) - [SECURITY] [OPENDXP-SA-2026-007] The object and asset grids open a workspace only for its own path and the paths below it. A workspace on `/shop_de` does not open `/shopXde`, and a quote in the name of a workspace does not break the query [#151](https://github.com/open-dxp/admin-bundle/pull/151) - [BUGFIX] The object and asset grids hide a closed folder also when another closed folder holds an open one [#151](https://github.com/open-dxp/admin-bundle/pull/151) - [ENHANCEMENT] Login links use the host of the request whenever OpenDXP trusts it, also a host from `opendxp.security.trusted_hosts`. See [Domain and Host Handling](https://github.com/open-dxp/opendxp/blob/1.x/doc/02_MVC/04_Routing_and_URLs/06_Domain_and_Host_Handling.md#trusted-hosts) - [NEW FEATURE] A data type shows its value in several grid columns with `GridColumnsInterface`. See [Adding Object Datatypes](https://github.com/open-dxp/opendxp/blob/1.x/doc/20_Extending_OpenDxp/13_Bundle_Developers_Guide/11_Adding_Object_Datatypes.md#grid-columns) - [BUGFIX] A grid filters by a classification store key and a slug at the same time - [BUGFIX] A grid filters a number of a classification store key between a lower and an upper bound - [NEW FEATURE] [HIGHLIGHT] Every grid of the admin exports through one export. See [Grid Export](docs/10_Extension_Points/08_Grid_Export.md) > Every grid in the admin uses the same export. - [NEW FEATURE] `GridExports::export()` runs a grid export in a test - [NEW FEATURE] A grid export runs in the background with `opendxp_admin.background_jobs`. See [Grid Export](docs/10_Extension_Points/08_Grid_Export.md#run-exports-in-the-background) - [BUGFIX] Progress windows stay in the bottom right corner when the browser window is resized - [BUGFIX] A data object closed right after opening logs no error in the console - [DEPRECATION] The grid view `patchedgridview` is deprecated. A grid uses the default view of Ext JS. - [DEPRECATION] The navigation model `quicksearch.boundlist` is deprecated. A bound list uses the default navigation model of Ext JS. - [CHORE] Requests from the admin no longer send the headers `X-opendxp-extjs-version-major` and `X-opendxp-extjs-version-minor` - [NEW FEATURE] [HIGHLIGHT] A large tree folder has a bar to search its children by any part of the key and to page through children and search results [open-dxp/opendxp#228](https://github.com/open-dxp/opendxp/issues/228) > Large folders in the tree get a search bar. Find children by any part of their key, and page through the children and the search results. - [CHORE] Require `openspout/openspout` ^5.0. `phpoffice/phpspreadsheet` goes with 2.0 - [CHORE] Remove the old export routes of the object, asset, email log and translation grids - [NEW FEATURE] The URL slug field shows the prefix of its slug generator, formats what an editor types and locks a stored slug. The domain of a site slug stands next to it [open-dxp/opendxp#159](https://github.com/open-dxp/opendxp/issues/159) - [NEW FEATURE] [HIGHLIGHT] Download the images of a folder or a selection as a ZIP of thumbnails. "Download as ZIP" in the asset tree, the folder toolbar and the list view offers "Originals" and "Thumbnails", which asks for one of the thumbnails offered for download [#128](https://github.com/open-dxp/admin-bundle/issues/128) > Download the images of a folder or a selection as a ZIP, either as originals or as thumbnails. - [BUGFIX] The thumbnail download of the image detail view hands out only thumbnails that are offered for download [#128](https://github.com/open-dxp/admin-bundle/issues/128) - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [CHORE] Stop registering the payload and result classes in `src/Handler` as services. They are data objects, and a service definition for them could not be built. - [ENHANCEMENT] The object grid counts its search as an active filter, and "Clear filters" clears the search as well [#129](https://github.com/open-dxp/admin-bundle/issues/129) - [ENHANCEMENT] Hide the AnyGetter grid operator from users who are not admins [#28](https://github.com/open-dxp/admin-bundle/issues/28) - [BUGFIX] Opening a deeplink works in a long running process, for example FrankenPHP in worker mode. - [BUGFIX] In a long running process, every session keeps its own CSRF token. - [DEPRECATION] Printing the Twig global `csrfToken` outside the admin is deprecated. It throws an exception in 2.0. - [DEPRECATION] Building the AnyGetter grid operator without a `user` in its context is deprecated. It throws an exception in 2.0. - [BUGFIX] A classification store key takes only a name that is valid for a data object field [#126](https://github.com/open-dxp/admin-bundle/pull/126) - [BUGFIX] The grids of the classification store configuration show why a change could not be saved and take the change back [#126](https://github.com/open-dxp/admin-bundle/pull/126) - [BUGFIX] A page that inherits its content from a content main document keeps that content when it is saved [#135](https://github.com/open-dxp/admin-bundle/pull/135) ### 1.4.3 - [BUGFIX] Object grid now applies the requested grid language before the listing is loaded and before inline edits are saved (regression from #91) [#122](https://github.com/open-dxp/admin-bundle/issues/122) - [BUGFIX] Object grid batch editing now saves localized fields in the requested grid language instead of the admin UI language. Localized classification store keys edited with grid language "default" are stored under "default" again (regression from #91). Batch append and remove on classification store keys now read the existing value in the requested language [#122](https://github.com/open-dxp/admin-bundle/issues/122) ### 1.4.2 - [ENHANCEMENT] Comply with OpenStreetMap tile and Nominatim usage policies [#118](https://github.com/open-dxp/admin-bundle/pull/118) - [ENHANCEMENT] One-time login links (lost password, user invitation, token login) now use the requested host if it belongs to a registered site, instead of always the configured main domain. Unknown hosts fall back to the general host resolver, so the `Host` header cannot be used to poison the links. [#119](https://github.com/open-dxp/admin-bundle/pull/119) - [ENHANCEMENT] Hide error box on login UI if error is empty or not set [#120](https://github.com/open-dxp/admin-bundle/pull/120) ### 1.4.1 - [ENHANCEMENT] Refine grid logic with strict comparisons and column auto-sizing adjustments [#112](https://github.com/open-dxp/admin-bundle/pull/112) - [BUGFIX] Prevent passing `rid` on scratch user creation [#109](https://github.com/open-dxp/admin-bundle/pull/109) - [BUGFIX] Clean up leftover rows of the previous document type during type conversion [#113](https://github.com/open-dxp/admin-bundle/pull/113) - [BUGFIX] Use the document tree instead of pretty URLs for the move collision check, so a document is no longer blocked by its own pretty URL [#114](https://github.com/open-dxp/admin-bundle/pull/114) - [BUGFIX] Tolerate empty / non-integer `oid` query parameter in `getClassDefinitionForColumnConfig` (regression from #91) [#115](https://github.com/open-dxp/admin-bundle/pull/115) ### 1.4.0 - [NEW FEATURE] Replace controller logic with dedicated handler and service classes (CQRS-Lite) [#91](https://github.com/open-dxp/admin-bundle/pull/91) - [NEW FEATURE] Add "use original recipients" option, fix resend and forward recipients [#102](https://github.com/open-dxp/admin-bundle/pull/102) - [NEW FEATURE] Add CSV export for email logs [#104](https://github.com/open-dxp/admin-bundle/pull/104) - [NEW FEATURE] Add email log cleanup to the global email log panel [#105](https://github.com/open-dxp/admin-bundle/pull/105) - [ENHANCEMENT] Introduce system_uuid & centralize system identity handling [#106](https://github.com/open-dxp/admin-bundle/pull/106) - [BUGFIX] Notification undefined elmentId [#100](https://github.com/open-dxp/admin-bundle/pull/100) - [BUGFIX] Handle root path in `optimizedConcatNotLike` [#101](https://github.com/open-dxp/admin-bundle/pull/101) - [BUGFIX] Fix typo in target group editable selection [#103](https://github.com/open-dxp/admin-bundle/pull/103) ### 1.3.5 - [BUGFIX] Fix missing OpenDXP CSS vars [#99](https://github.com/open-dxp/admin-bundle/pull/99) - [BUGFIX] Add guards for read/get operations in controllers and assets [#94](https://github.com/open-dxp/admin-bundle/pull/94) ### 1.3.4 - [CHORE] Remove unused grid configuration processing logic from DataObjectController [#89](https://github.com/open-dxp/admin-bundle/pull/89) - [BUGFIX] Resolve persistent thumbnail spinners in asset folder preview [#90](https://github.com/open-dxp/admin-bundle/pull/90) - [BUGFIX] Standardize Content-Disposition header formatting across controllers [#92](https://github.com/open-dxp/admin-bundle/pull/92) - [ENHANCEMENT] Add stricter unserialize options; refactor variable naming in TranslationController [#88](https://github.com/open-dxp/admin-bundle/pull/88) - [ENHANCEMENT] Added css color variables prefix [@cbl6499](https://github.com/open-dxp/admin-bundle/pull/87) ### 1.3.3 - [ENHANCEMENT] Add forceResize checkbox to video thumbnail settings [#82](https://github.com/open-dxp/admin-bundle/pull/82) - [BUGFIX] Executing workflow transitions [#80](https://github.com/open-dxp/admin-bundle/pull/80) - [BUGFIX] Array thumbnail parameter in getImageThumbnailAction [#78](https://github.com/open-dxp/admin-bundle/pull/78) - [BUGFIX] Remove duplicate AdminExtension service definition from services.yaml [#84](https://github.com/open-dxp/admin-bundle/pull/84) ### 1.3.2 - [BUGFIX] Remove redundant translation cache clearing from TranslationController [#67](https://github.com/open-dxp/admin-bundle/pull/67) - [BUGFIX] Ue new documentation URLs in toolbar links [#70](https://github.com/open-dxp/admin-bundle/pull/70) - [BUGFIX] Fix invalid infinite loop detection when linking to another type of element in document link [#74](https://github.com/open-dxp/admin-bundle/pull/74) - [ENHANCEMENT] PHP 8.5 support added [#76](https://github.com/open-dxp/admin-bundle/pull/76) - [ENHANCEMENT] Remove POEditor support and and normalize translation files [#75](https://github.com/open-dxp/admin-bundle/pull/75) - [ENHANCEMENT] Update admin UI styles, adjust notification and avatar elements for improved alignment [#72](https://github.com/open-dxp/admin-bundle/pull/72) ### 1.3.1 - [BUGFIX] Add guard clause to prevent rendering site settings without a valid site ### 1.3.0 - [NEW FEATURE] Site custom settings [#61](https://github.com/open-dxp/admin-bundle/pull/61) - [ENHANCEMENT] Replace SystemSettingsConfig usage with GeneralHostResolver in LoginController and UserController [#62](https://github.com/open-dxp/admin-bundle/pull/62) ### 1.2.3 - [BUGFIX] Translations: Fix data request - streamline filtering and improve readability [#50](https://github.com/open-dxp/admin-bundle/pull/50) - [BUGFIX] Correct languages when creating admin translation (#53) [#54](https://github.com/open-dxp/admin-bundle/pull/54) - [ENHANCEMENT] Refactor SQL queries: enforce parameterized bindings and consistent style [#49](https://github.com/open-dxp/admin-bundle/pull/49) - [CHORE] Strict equality checks across admin bundle [#55](https://github.com/open-dxp/admin-bundle/pull/55) - [CHORE] Update constant declarations to use type hints and visibility modifiers [#56](https://github.com/open-dxp/admin-bundle/pull/56) ### 1.2.2 - [CHORE] Update branding names [#45](https://github.com/open-dxp/admin-bundle/pull/45) - [CHORE] Remove outdated references to GitHub issues and comments. [#46](https://github.com/open-dxp/admin-bundle/pull/46) - [BUGFIX] Fixed saving email documents (#47) [#48](https://github.com/open-dxp/admin-bundle/pull/48) ### 1.2.1 - [CHORE] Update Rector configuration: add ForeachItemsAssignToEmptyArrayToAssignRector and update comments [#37](https://github.com/open-dxp/admin-bundle/pull/37) - [CHORE] Apply changes from upstream [#40](https://github.com/open-dxp/admin-bundle/pull/40) - [ENHANCEMENT] Various Ext JS Improvements [#38](https://github.com/open-dxp/admin-bundle/pull/38) - [CHORE] Replace `$request->get()` [#39](https://github.com/open-dxp/admin-bundle/pull/39) - [BUGFIX] #41 Fix CSS outline property value [#42](https://github.com/open-dxp/admin-bundle/pull/42) - [BUGFIX] Fix outline property in editmode.css [#43](https://github.com/open-dxp/admin-bundle/pull/43) - [CHORE] Update BC layer comment to reflect OpenDxp 2.0 target [#44](https://github.com/open-dxp/admin-bundle/pull/44) ### 1.2.0 - [ENHANCEMENT] UI refactoring [#25](https://github.com/open-dxp/admin-bundle/pull/25) - [ENHANCEMENT] Removed hover icon color styling for main navigation [#26](https://github.com/open-dxp/admin-bundle/pull/26) - [NEW FEATURE] Video overlay: poster image, title description for every type [#24](https://github.com/open-dxp/admin-bundle/pull/24) - [CHORE] PHPStan 2 [#30](https://github.com/open-dxp/admin-bundle/pull/30) - [CHORE] Apply Rector Fixes with coverage level 0 [#32](https://github.com/open-dxp/admin-bundle/pull/32) - [CHORE] Add changes from upstream (1.x <- 1.7.15) [#27](https://github.com/open-dxp/admin-bundle/pull/27) - [CHORE] Adjust Test Setup [#34](https://github.com/open-dxp/admin-bundle/pull/34) - [CHORE] Update ClassController & SettingsController [#36](https://github.com/open-dxp/admin-bundle/pull/36) - [CHORE] Remove dark scheme from root [#35](https://github.com/open-dxp/admin-bundle/pull/35) - [CHORE] Replace custom utilities with reusable helper methods across admin bu… [#33](https://github.com/open-dxp/admin-bundle/pull/33) ### 1.1.2 - [BUGFIX] Fix infinite spinner when moving objects in the tree ([#22](https://github.com/open-dxp/admin-bundle/pull/22)) - [CHORE] Retrieved changes from base: 1.7.14 ### 1.1.1 - [CHORE] Retrieved changes from base: 1.7.12, 1.7.13 ### 1.1.0 - [CHORE] Update package name [#9](https://github.com/open-dxp/admin-bundle/pull/9) - [CHORE] Update core dependency constraint [#10](https://github.com/open-dxp/admin-bundle/pull/10) - [CHORE] Update README.md [#11](https://github.com/open-dxp/admin-bundle/pull/11) - [CHORE] Introduce composer alias [#12](https://github.com/open-dxp/admin-bundle/pull/12) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Test [#1](https://github.com/open-dxp/admin-ui-classic-bundle/pull/1) - [CHORE] Adopt latest changes from base [#2](https://github.com/open-dxp/admin-ui-classic-bundle/pull/2) - [ENHANCEMENT] PHP 8.4 & Symfony 7.3 [#3](https://github.com/open-dxp/admin-ui-classic-bundle/pull/3) - [ENHANCEMENT] Adopt layout changes [#4](https://github.com/open-dxp/admin-ui-classic-bundle/pull/4) - [BUGFIX] Fixes [#5](https://github.com/open-dxp/admin-ui-classic-bundle/pull/5) - [CHORE] Fix tests [#6](https://github.com/open-dxp/admin-ui-classic-bundle/pull/6) --- ## Admin Bundle Documentation This is the documentation root for the **OpenDXP Admin Bundle**. The Admin Bundle provides the backend UI for OpenDXP (based on ExtJS) and defines the extension points that other bundles use to customize the admin interface. --- ### Sections #### [00 Architecture](00_Architecture/README.md) Bundle overview, relationship to opendxp core, and source structure. #### [10 Extension Points](10_Extension_Points/README.md) How other bundles and applications can extend the admin UI. | Topic | Description | |----------------------------------------------------------------------|-------------------------------------------------------------------| | [Events](10_Extension_Points/01_Events.md) | All `AdminEvents` constants — when they fire and how to subscribe | | [Admin UI Assets](10_Extension_Points/02_Admin_UI_Assets.md) | Loading custom JS and CSS into the admin UI | | [Admin UI JavaScript](10_Extension_Points/03_Admin_UI_JavaScript.md) | ExtJS event system, adding menus, key bindings | | [Perspectives](10_Extension_Points/04_Perspectives.md) | Configuring backend UI perspectives | | [Permissions](10_Extension_Points/05_Permissions.md) | Adding custom permissions | | [Deeplinks](10_Extension_Points/06_Deeplinks.md) | Deeplinks into the admin interface | | [Custom Admin Login](10_Extension_Points/07_Custom_Admin_Login.md) | Custom admin login entry point | | [Grid Export](10_Extension_Points/08_Grid_Export.md) | Exporting the rows of a grid, adding a source for a grid | #### [20 Documents](20_Documents/README.md) Admin UI features specific to document and site management. | Topic | Description | |-----------------------------------------------------------------|------------------------------------------------------| | [Site Custom Settings](20_Documents/01_Site_Custom_Settings.md) | Adding custom fields to the site configuration panel | #### [90 Testing](90_Testing/README.md) The test API for grid export sources, and the suite of this bundle. --- ### Quick Reference - **Event constants:** `src/Event/AdminEvents.php` - **opendxp core docs:** MVC, models, routing, deployment → see opendxp `doc/` (location depends on setup, see `CLAUDE.md`) --- ## Installation of Advanced Object Search :::info This bundle is only supported on OpenDXP Core Framework 1.x. This bundle requires minimum version of OpenSearch 2.7. or Elasticsearch 8.0.0. ::: ### Installation To install Advanced Object Search Bundle, follow the three steps below: 1. Install the required dependencies: ```bash composer require open-dxp/advanced-object-search-bundle ``` 2. Make sure the bundle is enabled in the `config/bundles.php` file. The following lines should be added: ```php return [ // ... OpenDxp\Bundle\AdvancedObjectSearchBundle\OpenDxpAdvancedObjectSearchBundle::class => ['all' => true], // ... ]; ``` 3. Install the bundle: ```bash bin/console opendxp:bundle:install OpenDxpAdvancedObjectSearchBundle ``` **Warning:** Before proceeding, please make sure your classes are not using any object data type named as `checksum` as this is currently a reserved field name for the search index. ### Required Backend User Permission To access the Advanced Object Search feature, a user needs to meet at least one of the following criteria: * Be an `admin` user. * Have `bundle_advancedsearch_search` permission. --- ## Extending Filters The advanced object search enables the definition of custom search filters that can be used to filter the result. This gives the possibility to filter lists of products by article numbers, types or colors e.g. without having to create a complete custom advanced object search for it. In order to create a custom filter for an advanced object search you have to follow these two steps: - create an event listener that adds the necessary condition(s) to the search - create the corresponding javascript filter that handles the input and is shown in the toolbar of the result tab ### Event Listeners To add your custom condition(s) to the search, you have two possibilities - add the condition(s) to the index search directly - add the condition(s) to the opendxp listing which will load all objects the index search found For convenience reasons you can extend the ``OpenDxp\Bundle\AdvancedObjectSearchBundle\Event\AbstractFilterListener`` and register it as an event subscriber in your container. This class provides you with two methods - ``public function onIndexSearch(FilterSearchEvent $event)`` to add condition(s) to the index search - ``public function onListing(FilterListingEvent $event)`` to add the condition(s) to the opendxp listing If you use the ``AbstractFilterListener`` you have to implement the ``supports(): bool`` method, which defines if the listener should actually add condition(s) to the current search. For example if you build an event listener to filter by article numbers, you only want to add the condition if an article number is in the query parameters. Here is an example for such a ``supports(): bool`` method ```php class ArticleNumber extends AbstractFilterListener { protected function supports(): bool { return !empty($this->getParameters()->get("articleNumber")); } } ``` #### Index Search Conditions Condition(s) can be added to the index search directly by creating an event listener that listens to the ``advanced_object_search.index_filter`` event (``OpenDxp\Bundle\AdvancedObjectSearchBundle\Event::INDEX_FILTER``). As mentioned before the ``AbstractFilterListener`` already takes care of that for you, if you extend it. Here is an example for the article number filter again, if your product has a field called ``artno``. As defined in the previous example, this condition will only be added if the ``articleNumber`` query parameter is present. ```php class ArticleNumber extends AbstractFilterListener { protected function addIndexSearchFilter(FilterSearchEvent $event) { $path = "artno." . DefaultAdapter::INDEX_MAPPING_PROPERTY_STANDARD; $query = new BoolQuery(); $query->add( new MatchQuery($path, $this->getParameters()->get("articleNumber")) ); $event->getSearch()->addPostFilter($query); } } ``` #### Listing Conditions In some cases you might have to join your result with another table before you can actually achieve the filter that you want. For that you can use the listing filter. The index search only returns the object ids which were found. These will be loaded using a basic opendxp listing of that class which enables you to add more mysql queries to that listing. For that you can use the ``advanced_object_search.listing_filter`` event (``OpenDxp\Bundle\AdvancedObjectSearchBundle\Event::LISTING_FILER``). Here is an example to filter for the article number as well, but with the listing instead of the index search. Keep in mind that this resolves in more overhead and less performant searches, only use this if you actually have to join your result to filter. If the data is available in index search use Index Search Conditions instead. ```php class ArticleNumber extends AbstractFilterListener { protected function addListingFiler(FilterListingEvent $event) { $listing = $event->getListing(); $listing->addConditionParam("artno = :artno", ["artno" => $this->getParameters()->get("articleNumber")]); } } ``` #### Javascript Filter Now that the result can be filtered by an article number, you have to create an input with javascript to be able to type in an article number. For that you have to create a javascript class that extends ``opendxp.bundle.advancedObjectSearch.searchConfig.ResultExtension`` and register it in the extension bag when the result page of an advanced object search is opened. Here is a basic implementation of such an extension that creates a simple input if the field ``artno`` is present in the result. ```js opendxp.registerNS("opendxp.bundle.AppBundle.AdvancedObjectSearch.Extension.*"); opendxp.bundle.AppBundle.AdvancedObjectSearch.Extension.ArticleNumber = Class.create(opendxp.bundle.advancedObjectSearch.searchConfig.ResultExtension, { supports: function(extensionBag) { // this filter will be displayed in the search if the field "artno" is present in the result tab return extensionBag.hasField("artno"); }, getLayout: function() { // create a simple input if (!this.input) { this.input = new Ext.create("Ext.form.Text", { listeners: { specialkey: function (field, e) { if (e.getKey() === e.ENTER) { this.getExtensionBag().update(); } }.bind(this) } }); this.input.setValue(this.getExtensionBag().getPredefinedFilter("articleNumber")); } return this.input; }, getFilterData: function () { var value = null; if (this.input) { value = this.input.getValue(); } // extract the value of your input, return value has to be an object // all custom filter return values will be merged // e.g. return { articleNumber: 'mynumber'} and return { articleType: 'concrete' } will result in // the query parameters { articleNumber: 'mynumber', articleType: 'concrete' } return { articleNumber: value }; } }); ``` The extension has to be registered in the extension bag of a result panel. This can be done in the ``onAdvancedObjectSearchResult`` of the opendxp plugin of your bundle. ```js opendxp.registerNS("opendxp.bundle.AppBundle.*"); opendxp.bundle.AppBundle.Bundle = Class.create({ getClassName: function() { return "opendxp.bundle.AppBundle.Bundle"; }, initialize: function() { document.addEventListener(opendxp.events.onAdvancedObjectSearchResult, this.onAdvancedObjectSearchResult.bind(this)); }, onAdvancedObjectSearchResult: function (e) { let extensionBag = e.detail.extensionBag; // here you can register all the extension that you implement extensionBag.addExtension(new opendxp.bundle.AppBundle.AdvancedObjectSearch.Extension.ArticleNumber()); } }); var AppBundle = new opendxp.bundle.AppBundle.Bundle(); ``` --- ## Exclude Fields It is possible to exclude specified fields from the search index by extending the services.yaml: ```yaml opendxp_advanced_object_search: index_configuration: exclude_classes: - CustomerSegment - CustomerSegmentGroup exclude_fields: OfferToolOffer: - offernumber OfferToolOfferItem: - productName - productNumber ``` Please Note: Currently is not possible to exclude any specific field under a structured fieldset like `Object Bricks` and `Field collections`, but it is only possible to exclude the field entirely for a specific class. --- ## Migrating to OpenDXP(Advanced-object-search) ### Migrate from `pimcore/advanced-object-search` to `open-dxp/advanced-object-search-bundle` * Renamed bundle to `open-dxp/advanced-object-search-bundle` * Changed top-level PHP namespace to `OpenDxp\Bundle\AdvancedObjectSearchBundle` * Changed bundle name to `OpenDxpAdvancedObjectSearchBundle` * Changed top-level config node to `opendxp_advanced_object_search` --- ## OpenSearch Client Setup :::info This bundle requires minimum version of OpenSearch 2.7. ::: Following configuration is required to set up OpenSearch. The OpenSearch client configuration takes place via [OpenDXP Opensearch Client](https://github.com/open-dxp/opensearch-client-bundle) and has two parts: 1) Configuring an OpenSearch client. 2) Define the client to be used by Advanced Object Search bundle. ```yaml # Configuring an OpenSearch client opendxp_open_search_client: clients: default: hosts: ['https://opensearch:9200'] password: 'admin' username: 'admin' ssl_verification: false # Define the client to be used by advanced object search opendxp_advanced_object_search: client_name: default # default is default value here, just need to be specified when other client should be used. ``` If nothing is configured, a default client connecting to `localhost:9200` is used. For the further configuration of the client, please refer to the [OpenDXP OpenSearch Client documentation](https://github.com/open-dxp/opensearch-client-bundle/blob/1.x/doc/02_Configuration.md). --- ## Elasticsearch Client Setup :::info This bundle requires minimum version of Elasticsearch 8.0. ::: Following configuration is required to set up Elasticsearch. The Elasticsearch client configuration takes place via [OpenDXP Elasticsearch Client](https://github.com/open-dxp/elasticsearch-client-bundle) and has two parts: 1) Configuring an Elasticsearch client. 2) Define the client to be used by Advanced Object Search bundle. ```yaml # Configuring an Elasticsearch client opendxp_elasticsearch_client: es_clients: default: hosts: ['elastic:9200'] username: 'elastic' password: 'somethingsecret' logger_channel: 'opendxp.elasicsearch' # Define the client to be used by advanced object search opendxp_advanced_object_search: client_name: default # default is default value here, just need to be specified when other client should be used. client_type: 'elasticsearch' # default is 'openSearch' ``` If nothing is configured, a default client connecting to `localhost:9200` is used. For the further configuration of the client, please refer to the [OpenDXP Elasticsearch Client documentation](https://github.com/open-dxp/elasticsearch-client-bundle/blob/1.x/README.md). --- ## Changelog(Advanced-object-search) ### 1.1.0 - [BUGFIX] The result grid exports through the grid export of the admin. See [Grid Export](https://github.com/open-dxp/admin-bundle/blob/1.x/docs/10_Extension_Points/08_Grid_Export.md) - [CHORE] Remove the old export route of the result grid - [CHORE] Require `open-dxp/admin-bundle` ^1.5 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [CHORE] Update branding names [#2](https://github.com/open-dxp/advanced-object-search-bundle/pull/2) - [ENHANCEMENT] Add php 8.5 support [#3](https://github.com/open-dxp/advanced-object-search-bundle/pull/3) - [CHORE] Streamline CI workflows, update configurations, and refactor project setup [#4](https://github.com/open-dxp/advanced-object-search-bundle/pull/4) ### 1.0.0 - [NEW FEATURE] Initial release --- ## Migrating to OpenDXP(Installation_and_Upgrade) ### Migrating from `pimcore/data-hub` to `open-dxp/data-hub-bundle` * Renamed bundle to `OpenDxpDataHubBundle` (composer package: `open-dxp/data-hub-bundle`) * Renamed top-level PHP namespace to `OpenDxp\Bundle\DataHubBundle` * Renamed top-level config node to `opendxp_data_hub` * Deprecations * Removed deprecated constant `OpenDxp\Bundle\DataHubBundle\Configuration\Dao::LEGACY_FILE` * Removed deprecated `datahub:graphql:rebuild-definitions` command. Use `OpenDxp\Bundle\DataHubBundle\Command\Configuration\RebuildWorkspacesCommand` instead. --- ## Installation(Installation_and_Upgrade) ### Bundle Installation To install OpenDxp Datahub follow the three steps below: 1. Install the required dependencies: ```bash composer require open-dxp/data-hub-bundle ``` 2. Make sure the bundle is enabled in the `config/bundles.php` file. The following lines should be added: ```php use OpenDxp\Bundle\DataHubBundle\OpenDxpDataHubBundle; // ... return [ // ... OpenDxpDataHubBundle::class => ['all' => true], // ... ]; ``` 3. Install the bundle: ```bash bin/console opendxp:bundle:install OpenDxpDataHubBundle ``` ### Required Backend User Permission To access Datahub, user needs to meet one of following criteria: * be an `admin` * have `plugin_datahub_config` permission --- ## Basic Principle OpenDxp Datahub allows defining multiple endpoints that allow data delivery and consumption. These endpoints are configured via so called configurations that can be added in the OpenDxp admin user interface: ### Adding a New Configuration 1. Open the Datahub configuration panel: ![Configuration Overview](./img/graphql/configuration3.png) 2. Choose an endpoint technology: ![Add Configuration](./img/add_config.png) 3. Get the configuration done by defining the followings: - General settings - Schema configuration - Security definitions - Additional settings Here you can find an example for [GraphQL](./10_GraphQL/README.md). --- ## General Settings ##### Some Aspects: * `Active`: You can temporarily disable the configuration using the checkbox. * `SQL Condition (Deprecated)`: You can add a condition all data object queries have to satisfy in addition to the [workspace settings](./03_Security_Settings.md). SQL Condition is currently deprecated but still enabled by default. If you want to disable it, you can do so in the symfony configuration tree: ```yaml opendxp_data_hub: graphql: allow_sqlObjectCondition: false ``` :::caution Please note that this option will be also removed in the next major version. ::: --- ## Schema Settings Schema settings define which data entities (Data Object classes, Assets, Documents) should be exposed via the endpoint. For Assets and Documents, default schemas are provided, for Data Object classes the schema can be defined in the field configuration. ![Add](../../img/graphql/schema_add.png) ### Query Schema Here you can configure which Data Objects Classes can be exposed. #### Available Fields Configuration When adding a new entity with the `Add` button, you can access the `Available Fields Configuration` window with a right-click on the `Settings` icon. You can then define all the target Data Object Class fields you want to make available. In addition, you can employ a set of operators. ![Schema Settings](../../img/graphql/schema.png) :::info Please note that not all data types are supported yet! ::: You will get a notice if you try to add an unsupported data type. ### Mutation Schema Here you can decide if Data Objects for the selected class can be created, updated or deleted from the endpoint. :::caution Be aware that a Data Object deleted from an endpoint will be definitively deleted of OpenDxp. ::: #### Available Fields Configuration As for the `Query Schema` field, you can select the fields you want to expose and/or make available for changes in the `Available Fields Configuration` you can open by clicking on the `Settings` icon. ### Generic Types Here you can define which data types can be created, read, updated or deleted from an endpoint. --- ## Security Settings The security settings define how the endpoint is secured and which data is accessible. ![security1.png](../../img/graphql/security1.png) ### Authentication Here you can define how users are authenticated when accessing the endpoint. ##### Supported Methods * API Key: needs to be sent with every request. ##### API Key To automatically create an API key use the button next to the input. For each click on the button a new API key is generated and will be added to the input field in addition to the list of existing keys. ### Introspection Settings Introspection provides an information about queries which are supported by GraphQl schema. If introspection is enabled, the endpoint will provide a schema definition which can be used by GraphiQL or other tools to provide auto-completion and documentation. If introspection is disabled, the schema definition will not be provided and therefore no auto-completion or documentation will be available. This is currently enabled by default. It can be disabled via security settings tab directly in the backend or in the symfony configuration tree: ``` opendxp_data_hub: graphql: allow_introspection: false ``` ### Workspace Settings Defines workspaces for data that should be accessible via the endpoint. The definition is similar to OpenDxp user [workspace permissions](https://docs.opendxp.io/docs/core-framework/Administration_of_OpenDxp/Users_and_Roles) :::warning If no workspace is selected, no directories are accessible. ::: Available permissions: * Create * Read * Update * Delete ### Error Handling - Configuration Values The default behavior for associated/related objects, documents or assets that are not visible for the endpoint is, to simply null it out. You can change that via a configuration setting in symfony configuration tree: * 1 = the entire query will fail * 2 = null it out/skip it for multi-relations (default) ``` opendxp_data_hub: graphql: not_allowed_policy: 2 ``` It is also possible to disable the permission checks entirely by setting the configuration option in the security definition tab. --- ## Custom Permissions(Configuration) When creating custom queries or creating other custom extensions to Datahub, it might be useful to add additional permissions to define access rules for certain data entities (like it is possible to define access for Documents, Assets, etc.). ### Adding Custom Permissions If you want to create custom permissions, you can create an event-listener for the event `OpenDxp\Bundle\DataHubBundle\ConfigEvents::SPECIAL_ENTITIES` and add them as follows. The EventListener adds a new Entity of type `OpenDxp\Bundle\DataHubBundle\Model\SpecialEntitySetting` with the corresponding permissions it allows: - Read Possible: defines if `read` checkbox is available - Create Possible: defines if `create` checkbox is available - Update Possible: defines if `update` checkbox is available - Delete Possible: defines if `delete` checkbox is available - Read Allowed: define default value for `read` - Create Allowed: define default value for `create` - Update Allowed: define default value for `update` - Delete Allowed: define default value for `delete` ##### Sample Implementation ```php use OpenDxp\Bundle\DataHubBundle\ConfigEvents; use OpenDxp\Bundle\DataHubBundle\Event\Config\SpecialEntitiesEvent; use OpenDxp\Bundle\DataHubBundle\Model\SpecialEntitySetting; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class GraphQlCustomListener implements EventSubscriberInterface { public static function getSubscribedEvents() { return [ ConfigEvents::SPECIAL_ENTITIES => 'specialEntities' ]; } public function specialEntities(SpecialEntitiesEvent $event) { $custom = new SpecialEntitySetting( 'custom', true, true, true, false, $event->getConfig()['schema']['specialEntities']['custom']['read'] ?? false, $event->getConfig()['schema']['specialEntities']['custom']['crate'] ?? false, $event->getConfig()['schema']['specialEntities']['custom']['update'] ?? false, $event->getConfig()['schema']['specialEntities']['custom']['delete'] ?? false ); $event->addSpecialSetting($custom); } } ``` --- ## Customizing the Endpoint The standard endpoint is ``` /opendxp-graphql-webservices/{clientname}?apikey={yourApiKey} ``` So if your configuration name is _blogdemo_ and your apikey _123456_ then your endpoint would be ``` /opendxp-graphql-webservices/blogdemo?apikey=12345 ``` Here is a configuration example showing how to override the standard endpoint: ```yml # app/config/routing.yml # Changing URL to the explorer environement admin_opendxpdatahub_config: path: /opendxp-datahub-webservices-my-endpoint/explorer/{clientname} defaults: { _controller: OpenDxp\Bundle\DataHubBundle\Controller\GraphQLExplorerController::explorerAction } # Changing endoint URL admin_opendxpdatahub_webservice: path: /opendxp-graphql-webservices-my-endpoint/{clientname} defaults: { _controller: OpenDxp\Bundle\DataHubBundle\Controller\WebserviceController::webonyxAction } ``` --- ## Document Queries ### Supported Document Types * Email * Hardlink * Link * Page * Snippet ### Supported Page Element Types * Areablock * Checkbox * Date * Embed * Image * Input * Link * Multiselect * Numeric * Pdf * Relation * Relations * Renderlet * Scheduled Block * Select * Table * Textarea * Video * Wysiwyg * ... ### Document Query Samples #### Fetch Document Page and Get Date Editable ```graphql { getDocument(id: 25) { ... on document_page { fullpath editables { ...on document_editableDate { _editableName # unix timestamp timestamp # as formatted string formatted(format:"Y-m-d") } } } } } ``` #### Fetch Document Page and Get All Editables, Including the Inherited Editables ```graphql { getDocument(id: 207) { ... on document_page { id, editables(getInheritedValues: true ){ __typename } } } } ``` #### Fetch Document Page and get processed Wysiwyg editable content * Field `text` contains the HTML as it is stored in OpenDxp for this Wysiwyg editable. * Field `frontend` contain the processed HTML where OpenDxp Element links are rewritten where necessary. ```graphql { getDocument(id: 207) { ... on document_page { id, editables(getInheritedValues: true){ __typename ...on document_editableWysiwyg { text frontend } } } } } ``` #### Fetch Full Rendered Document Page The `rendered` field can be used to retrieve a rendered version of the page. Available options: * `attributes`: Attributes passed into the controller/action * `query`: Query Params passed into the controller/action * `options`: Options passed into the renderer * `use_layout`: Enable/disable Layout Rendering ```graphql { getDocument(id: 207) { ... on document_page { id, rendered( attributes: [{key: "myControllerAttributeName", value: "Hello World!"}], use_layout: true, options: [{key: "ignore_errors", value: "1"}] ) } } } ``` ### Fetch Document Page via Data Object Relation and Get More Editable Data * get data object ID 61 * get many-to-one relation * get target page document * get link editable * get referenced page document / or news object * get input editables of referenced page document / or shorttext of news object ```graphql { getTest3(id: 61) { manytoone { ... on document_page { fullpath editables { ... on document_editableLink { _editableType _editableName data { internal path target { __typename ... on document_page { id fullpath editables { ... on document_editableInput { name text } } } ... on object_news { shortText } } } } } } } } } ``` #### Fetch Link Document Get Link Document and resolve the target news text. ```graphql { getDocument(id: 76) { ... on document_link { fullpath object { ...on object_news { shortText } } } } } ``` ### Fetch Document Properties see [Element Properties](./11_Query_Samples/05_Sample_Element_Properties.md) ### Fetch Document Translation Links ```graphql { getDocument(id: 76) { ... on document_page { id translations { id language target { ... on document_headlessdocument { fullpath } } } } } } ``` #### Fetch Language Specific Document Translation Link ```graphql { getDocument(id: 76) { ... on document_page { id translations(defaultLanguage: "de") { ... } } } } ``` --- ## Asset Queries Asset queries support getting single assets, single asset folders and asset listings. ### Get Single Asset Base structure for getting single asset: ```graphql { getAsset(id: 4) { ... } } ``` See also following examples: - [Sample GetAsset](./11_Query_Samples/11_Sample_GetAsset.md) - [Sample Asset Metadata](./11_Query_Samples/12_Sample_Asset_Metadata.md) ### Get Single Asset Folder Base structure for getting single asset folder (same as for assets): ```graphql { getAssetFolder(id: 4) { ... } } ``` ### Get List of Assets Base structure for getting a list of assets, restricted by IDs: ```graphql { getAssetListing(ids: "4,5") { edges { ... ``` See also following examples: - [Sample GetAssetListing](./11_Query_Samples/13_Sample_GetAssetListing.md) ##### Pagination Pagination can be applied as query parameters. ```graphql { # 'first' is the limit # 'after' the offset getAssetListing(first: 3, after: 1) { edges { ... } } } ``` ##### Simple Sorting Sorting can be applied as query parameters, for example sort by filename, descending. ```graphql { getManufacturerListing(sortBy: "filename", sortOrder: "DESC") { edges { node { id name } } } } ``` ##### Filtering You can use OpenDxp's webservice filter logic as described [here](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Web_Services/Query_Filters.html) for filtering listing requests. For details see [filtering documentation page](./10_Filtering.md) ### Localization of Queries Queries can be localized For details see the [localization documentation page](./08_Localization.md). ### Thumbnails You can request thumbnails for assets using a simple query like this: ##### Video assets thumbnails You need to specify the name of the video thumbnail configuration you want to use. Additionally, you can use the `format` parameter to request a specific format. ```graphql query { getAsset(id:353) { id, thumbnail:fullpath(thumbnail: "content"), } } ``` ##### Image assets thumbnails You need to specify the name of the video thumbnail configuration you want to use. Use the `format` parameter to request a specific format. Specifying the `deferred` parameter will defer the thumbnail generation until it gets requested for the first time. ```graphql query { getAsset(id:289) { id, thumbnail:fullpath(thumbnail: "events_header", deferred:true) } } ``` --- ## DataObject Queries ### Suppored Data Types Also check out the OpenDxp's [data type documentation](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Objects/Object_Classes/Data_Types/index.html). * Advanced Many-to-Many Relation * Advanced Many-to-Many Object Relation * Block * Boolean Select * [Calculated Value](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Objects/Object_Classes/Data_Types/Calculated_Value_Type.html) * Checkbox * Classification Store * Country * Countries (Multiselect) * Date * DateTime * Email * External Image * Gender * [Field-Collections](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Objects/Object_Classes/Data_Types/Fieldcollections.html) * Firstname * Geobounds * Geopoint * Geopolygon * Image * Image Advanced * Input * InputQuantityValue * Language * Languages (Multiselect) * Lastname * Link * Many-to-One Relation * Many-to-Many Relation * Many-to-Many Object Relation * Multiselect * Newsletter Active * Newsletter Confirmed * Numeric * Quantity Value * Reverse Many-to-Many Object Relation * RgbaColor * Select * Slider * StructuredTable * Table * Textarea * Time * [URL Slug](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Objects/Object_Classes/Data_Types/Others.html) * Video * Wysiwyg ### Available Query Operators Check out the [operators section](../08_Operators/README.md) for more information. ### Get single Data Object Base structure for getting single data object: ```graphql { getNews(id: 4) { ... } } ``` ### Get List of Data Objects Base structure for getting a list of data objects, restricted by IDs: ```graphql { getNewsListing(ids: "4,5") { edges { ... ``` Base structure for getting a list of data objects, restricted by fullpath: ```graphql { getNewsListing(fullpaths: "/NewsArticle,/NewsArticle2") { totalCount edges { node { id } } } } ``` Sometimes it can happen that the fullpath already contains a comma. To make sure the comma is not interpreted as a list separator in this case, you can quote the path: ```graphql { getNewsListing(fullpaths: "'/NewsArticle,Headline','/NewsArticle2'") { totalCount edges { node { id } } } } ``` ##### Pagination Pagination can be applied as query parameters. ```graphql { # 'first' is the limit # 'after' the offset getManufacturerListing(first: 3, after: 1) { edges { node { id name } } } } ``` ##### Simple Sorting Sorting can be applied as query parameters, for example sort by name, descending. ```graphql { getManufacturerListing(sortBy: "name", sortOrder: "DESC") { edges { node { id name } } } } ``` ##### Filtering You can use OpenDxp's webservice filter logic as described [here](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Web_Services/Query_Filters.html) for filtering listing requests. For details see [filtering documentation page](./10_Filtering.md) ### Localization of Queries Queries can be localized For details see the [localization documentation page](./08_Localization.md). ### Extend Data Object Queries It is possible to add custom query data types and query operators. For details see detail documentation pages: * [Add a custom query datatype](./15_Add_Custom_Query_Datatype.md) * [Add a custom query operator](./16_Add_Custom_Query_Operator.md) ### More Examples See following list for more examples with data object queries: - [Manufacturer Listing with sorting and paging](./11_Query_Samples/20_Sample_Manufacturer_Listing.md) - [Many-to-Many Object Relation](./11_Query_Samples/21_Sample_ManyToMany_Object_Relation.md) - [Advanced Many-to-Many Object Relation](./11_Query_Samples/22_Sample_Advanced_ManyToMany_Object_Relation.md) - [Advanced Many-to-Many Relation Metadata](./11_Query_Samples/23_Sample_Advanced_ManyToMany_Relation_Metadata.md) - [Field-Collections on Data Objects](./11_Query_Samples/24_Sample_Fieldcollections.md) - [Objects Parent/Children/Siblings](./11_Query_Samples/25_Sample_Parent_Children_Siblings.md) - [Get linked data](./11_Query_Samples/26_Sample_Get_Linked_Data.md) - [Translate Values](./11_Query_Samples/27_Sample_Translate_Values.md) --- ## Localization(Query) #### Default Language You can change the default language for localized fields by passing the `defaultLanguage` argument for single and listing queries. ###### Sample Request ```graphql { getNewsListing(defaultLanguage: "de") { ... } ``` #### Define Language on Field Level However, you can always provide an alternative language for a specific field. ###### Sample Request ```graphql { getUser(id: 50, defaultLanguage: "en") { myAdvancedObjects { element { id classname title, deTitle: title(language: "de"), shortText(language: "de") } metadata { name value } } } } ``` ###### Response ```graphql { "data": { "getUser": { "myAdvancedObjects": [ { "element": { "id": "8", "classname": "news", "title": "In enim justo", "deTitle": "Li Europan lingues es membres", "shortText": "Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular." }, "metadata": [ { "name": "altname", "value": "Ratman" }, { "name": "name", "value": "Canine" } ] }, { "element": { "id": "3", "classname": "news", "title": "Lorem ipsum dolor sit amet", "deTitle": "Er hörte leise Schritte hinter sich", "shortText": "Das bedeutete nichts Gutes. Wer würde ihm schon folgen, spät in der Nacht und dazu noch in dieser engen Gasse mitten im übel beleumundeten Hafenviertel?" }, "metadata": [ { "name": "altname", "value": "Spike" }, { "name": "name", "value": "Doctor" } ] } ] } } } ``` #### Fallback Language You can disable getting the value of the fallback language by passing the `getFallbackLanguageValue` argument. Set it to `false` to disable the fallback language. ###### Sample Request ``` query { getCar(id: 1229) { name(language:"de", getFallbackLanguageValue:false) } } ``` --- ## Filter Listings You can use __OpenDxp's webservice filter logic__ as described [here](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Web_Services/Query_Filters.html) to filter listing. ### Sample Get all `Manufacturer` objects which have 'ca' in their name field. ![Filtered Grid](../../img/graphql/filtering.png) ##### Request ```graphql { getManufacturerListing(filter: "{\"name\": {\"$like\" :\"%ca%\"}}") { edges { node { id name } }, totalCount } } ``` ##### Response ```json { "data": { "getManufacturerListing": { "edges": [ { "node": { "id": "45", "name": "Cadillac" } }, { "node": { "id": "80", "name": "AC Cars" } }, { "node": { "id": "153", "name": "MG Cars" } } ], "totalCount": 3 } } } ``` --- ## Get Element Properties ![Sample Document Properties](../../../img/graphql/element_properties.png) #### Request Properties can be filtered by providing the `keys` argument. All properties will be returned by default. ```graphql { getDocument(id: 38) { ... on document_page { fullpath properties(keys: ["newsletter_confirm_mail", "myobject", "mylogo"]) { __typename ... on property_text { name text } ... on property_select { name text } ... on property_document { name type document { __typename ... on document_email { id fullpath controller action } } } ... on property_asset { name asset { fullpath logothumb: fullpath(thumbnail: "content") filesize } } ... on property_object { name object { ... on object_Car { id name color } } } } } } } ``` #### Response ```json { "data": { "getDocument": { "fullpath": "/en/More-Stuff/Developers-Corner/Editable-Roundup", "properties": [ { "__typename": "property_document", "name": "newsletter_confirm_mail", "type": "document", "document": { "__typename": "document_email", "id": "105", "fullpath": "/en/mails/newsletter_confirm", "controller": "@AppBundle\\Controller\\DefaultController", "action": "genericMail" } }, { "__typename": "property_asset", "name": "mylogo", "asset": { "fullpath": "/Brand%20Logos/Alfa_Romeo_logo.png", "logothumb": "/Brand%20Logos/image-thumb__290__content/Alfa_Romeo_logo.webp", "filesize": 101613 } }, { "__typename": "property_object", "name": "myobject", "object": { "id": "273", "name": "Gulietta Sprint Speciale", "color": [ "green" ] } } ] } } } ``` --- ## Classification Store ### Supported Data Types * BooleanSelect * Calculated Value * Checkbox * Country * Countries (Multiselect) * Date * DateTime * Input * InputQuantityValue * Language * Languages (Multiselect) * Multiselect * Numeric * QuantityValue * RgbaColor * Select * Slider * Textarea * Time * Wysiwyg ### Request Example `csfield` is the classification store field. ```graphql { { getCstest(id: 107) { id classname qvfield { unit { abbreviation } value } csfield(language: "default") { id name description features { __typename ... on csFeatureInput { type id name description text } ... on csFeatureQuantityValue { type id description quantityvalue { unit { abbreviation longname } value } } ... on csFeatureTextarea { text name } } } } } ``` ### Response Example ```json { "data": { "getCstest": { "id": "107", "classname": "cstest", "qvfield": { "unit": { "abbreviation": "cm" }, "value": 3 }, "csfield": [ { "id": 2, "name": "Group1", "description": "Some group description", "features": [ { "__typename": "csFeatureInput", "type": "input", "id": 2, "name": "The name of my key definition", "description": "The description ...", "text": "C" }, { "__typename": "csFeatureQuantityValue", "type": "quantityValue", "id": 3, "description": "A quantityValue key definition", "quantityvalue": { "unit": { "abbreviation": "mm", "longname": "millimeter" }, "value": 2 } }, { "__typename": "csFeatureTextarea", "text": "Hello, I am a textarea", "name": "key4" } ] } ] } } } ``` --- ## Get Translation By Key If you want to access one translation. #### Request ``` { getTranslation (key: "BMW") { translations domain key type } } ``` #### Response ``` { "data": { "getTranslation": { "translations": "{\"de\":\"\",\"en\":\"\",\"fr\":\"\"}", "domain": "messages", "key": "BMW", "type": "simple" } } } ``` --- ## Get Asset By Id If you want to access an Asset directly. :::caution Note that the data will be base64 encoded and quite time-consuming to deliver. ::: #### Request :::info Note that for the fullpath and the base64 encoded data you can specify a thumbnail config. You can use the `format` argument to retrieve the values for a specific format like `webp`. ::: ``` { getAsset(id: 4) { id # original fullpath, # thumbnail URL for exampleCover config assetThumb: fullpath(thumbnail: "exampleCover") # thumbnail URL for content config assetThumb2: fullpath(thumbnail: "content", format: "webp") resolutions(thumbnail: "content", types: [2,5]) { resolution url } srcset(thumbnail: "content") { url descriptor # if types is not defined, then default resolutions @2x will be returned resolutions(types: [2,5]) { url resolution } } type mimetype # original file size filesize # base 64 encoded "content" thumbnail data(thumbnail:"content") } } ``` #### Response ``` { "data": { "getAsset": { { "data": { "getAsset": { "id": "4", "fullpath": "/Car%20Images/jaguar/auto-automobile-automotive-192499.jpg", "assetThumb": "/Car%20Images/jaguar/4/image-thumb__4__exampleCover/auto-automobile-automotive-192499.jpg", "assetThumb2": "/Car%20Images/jaguar/4/image-thumb__4__content/auto-automobile-automotive-192499.webp", "resolutions": [ { "url": "//Car%20Images/jaguar/image-thumb__4__content/auto-automobile-automotive-192499~-~768w@2x.jpg", "resolution": 2 }, { "url": "//Car%20Images/jaguar/image-thumb__4__content/auto-automobile-automotive-192499~-~768w@5x.jpg", "resolution": 5 } ] "srcset": [ { "descriptor": "768w", "url": "//Car%20Images/jaguar/image-thumb__4__content/auto-automobile-automotive-192499~-~768w.webp" "resolutions": [ { "url": "//Car%20Images/jaguar/image-thumb__4__content/auto-automobile-automotive-192499~-~768w@2x.webp", "resolution": 2 }, { "url": "//Car%20Images/jaguar/image-thumb__4__content/auto-automobile-automotive-192499~-~768w@5x.webp", "resolution": 5 } ] } ], "type": "image", "mimetype": "image/jpeg", "filesize": 113895, "data": "UklGRjh............." } } } ``` --- ## Get Asset Metadata ![Metadata](../../../img/graphql/asset_metadata.png) #### Request Get the custom asset metadata for language `de` ```graphql { getAsset(id: 4, defaultLanguage: "de") { id fullpath type mimetype filesize metadata { name type data language } } } ``` #### Response ```json { "data": { "getAsset": { "id": "4", "fullpath": "/Car%20Images/jaguar/auto-automobile-automotive-192499.jpg", "type": "image", "mimetype": "image/jpeg", "filesize": 113895, "metadata": [ { "name": "author", "type": "input", "data": "Mike", "language": "" }, { "name": "authorLink", "type": "input", "data": "https://www.pexels.com/@mikebirdy", "language": "" }, { "name": "copyright", "type": "input", "data": "Mike (https://www.pexels.com/@mikebirdy) | Pexels License", "language": "" }, { "name": "license", "type": "input", "data": "Pexels License", "language": "" }, { "name": "licensePath", "type": "input", "data": "https://www.pexels.com/photo-license/", "language": "" }, { "name": "source", "type": "input", "data": "https://www.pexels.com/photo/auto-automobile-automotive-car-192499/", "language": "" } ] } } } ``` ### Get Asset Embedded Meta Info ![Metadata](../../../img/graphql/asset_embeddedMetaInfo.png) #### Request Get the embedded meta info asset metadata for an asset ```graphql { getAsset(id: 295) { embeddedMetaInfo { name value } } } ``` #### Response ```graphql { "data": { "getAsset": { "embeddedMetaInfo": [ { "name": "FileSize", "value": "395 kB" }, { "name": "FileModifyDate", "value": "2019:06:07 12:21:26+02:00" }, { "name": "FileAccessDate", "value": "2019:06:07 12:21:26+02:00" }, { "name": "FileInodeChangeDate", "value": "2019:06:07 12:21:26+02:00" }, { "name": "FilePermissions", "value": "rwxrwxr-x" }, { "name": "FileType", "value": "SVG" }, { "name": "FileTypeExtension", "value": "svg" }, { "name": "MIMEType", "value": "image/svg+xml" }, { "name": "ImageWidth", "value": "383.921649993" }, { "name": "ImageHeight", "value": "260.469812009" }, { "name": "ViewBox", "value": "0 0 849 576" }, { "name": "SVGVersion", "value": "1.1" }, { "name": "Xmlns", "value": "http://www.w3.org/2000/svg" }, { "name": "Style", "value": "fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:1.41421;" }, { "name": "ImageSize", "value": "383.921649993x260.469812009" }, { "name": "Megapixels", "value": "352991.9" } ], "tags": null } } } ``` --- ## Get Asset Listing #### Request :::info Note that for the fullpath and the base64 encoded data you can specify a thumbnail config. ::: ``` { getAssetListing { edges { node { __typename } } } } ``` #### Response ``` { "data": { "getAssetListing": { "edges": [ { "node": { "__typename": "asset_folder" } }, { "node": { "__typename": "asset" } }, { "node": { "__typename": "asset" } }, { "node": { "__typename": "asset" } }, { "node": { "__typename": "asset" } } ] } } } ``` --- ## Get Translation Listing #### Request Filter by domain "messages" ``` { getTranslationListing (domain: "messages") { edges { node { ... on translation { key, translations } } } } } ``` #### Response ``` { "data": { "getTranslationListing": { "edges": [ { "node": { "key": "2-door berlinetta", "translations":"{\"de\":\"2 T\ürer Sportcoup\é\",\"en\":\"\",\"fr\":\"\"}" } }, { "node": { "key": "2-door fastback coupé", "translations":"{\"de\":\"2 T\ürer Coup\é\",\"en\":\"\",\"fr\":\"\"}" } }, { "node": { "key": "2-door hardtop", "translations":"{\"de\":\"2 T\ürer Hardtop\",\"en\":\"\",\"fr\":\"\"}" } }, { "node": { "key": "2-door roadster", "translations":"{\"de\":\"2 T\ürer Roadster\",\"en\":\"\",\"fr\":\"\"}" } } ] } } } ``` --- ## Get Manufacturer Listing #### Request Manufacturer listing with limit 3 and offset 1, sorted by name. ```graphql { # 'first' is the limit # 'after' the offset getManufacturerListing(first: 3, after: 1, sortBy: "name") { edges { node { id name logo { id fullpath } } } } } ``` #### Response ``` { "data": { "getManufacturerListing": { "edges": [ { "node": { "id": "28", "name": "Alfa Romeo", "logo": { "id": "290", "fullpath": "/Brand%20Logos/Alfa_Romeo_logo.png" } } }, { "node": { "id": "240", "name": "Aston Martin", "logo": { "id": "291", "fullpath": "/Brand%20Logos/Aston_Martin_Logo_2018.png" } } }, { "node": { "id": "35", "name": "Austin-Healey", "logo": { "id": "292", "fullpath": "/Brand%20Logos/Austin-Healey-Logo.jpg" } } } ], "totalCount": 27 } } } ``` --- ## Many-to-Many Object Relation ![Data](../../../img/graphql/many_to_many_object_relation.png) #### Request Get the associated categories. ```graphql { getCar(id: 9) { name categories { ... on object_Category { id name } } } } ``` #### Response ```json { "data": { "getCar": { "name": "E-Type", "categories": [ { "id": "559", "name": "Sports Cars" }, { "id": "555", "name": "Grand Tourer" } ] } } } ``` --- ## Advanced Many-to-Many Object Relation and Metadata Data Model for class `AccessoryPart`: ![Data](../../../img/graphql/advanced_many_to_many_object_relation.png) Data: ![Data](../../../img/graphql/advanced_many_to_many_object_relation2.png) #### Request :::info Note that the response differs from `Advanced Many-to-Many Relations` as there can be only class. ::: ``` { getAccessoryPart(id:408) { id, classname advAdditionalCategories { element { id, classname } metadata { name, value } } } } ``` #### Response ``` { "data": { "getAccessoryPart": { "id": "408", "classname": "AccessoryPart", "advAdditionalCategories": [ { "element": { "id": "392", "classname": "Category" }, "metadata": [ { "name": "altName", "value": "AlternativeNameForCategory" } ] } ] } } } ``` --- ## Get Advanced Many-to-Many Relation Metadata ![Metadata](../../../img/graphql/many2many.png) Data: ![many2many_data.png](../../../img/graphql/many2many_data.png) #### Request :::info Make sure to use the correct inline fragments to access data from the related classes. The exact class name is required to access the data. E.g. for manufacturer data use `... on object_Manufacturer`. ::: ```graphql { getAccessoryPart(id:408) { id, classname additionalLinkedElements { element { ... on asset { id, fullpath } ... on object_Manufacturer { id, name } ... on document_page { id, fullpath } } metadata { name, value } } } } ``` #### Response ```json { "data": { "getAccessoryPart": { "id": "408", "classname": "AccessoryPart", "additionalLinkedElements": [ { "element": { "id": "97", "fullpath": "/en/Find-and-Buy/On-Sale" }, "metadata": [ { "name": "altName", "value": "OnSale" } ] }, { "element": { "id": "33", "fullpath": "/Car%20Images/austin%20healey/austin-healey-1019023.jpg" }, "metadata": [ { "name": "altName", "value": "CarImage" } ] }, { "element": { "id": "35", "name": "Austin-Healey" }, "metadata": [ { "name": "altName", "value": "Manufacturer" } ] } ] } } } ``` --- ## Field-Collections on Data Objects #### Configuration If you want to run this sample, please create the following configuration ![Schema](../../../img/graphql/news_configuration.png) #### Request ```graphql { { getNews(id: 767) { # id # title content { __typename ... on fieldcollection_NewsText { text } ... on fieldcollection_NewsCars { title relatedCars { __typename ... on object_Car { name color } } } } } } ``` and make sure that the `/News` folder is readable. ![Workspace](../../../img/graphql/news_workspace.png) #### Response Here you also see the use of aliases. ```json { "data": { "getNews": { "content": [ { "__typename": "fieldcollection_NewsText", "text": "

Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus.

\n\n

Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede. Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis. Etiam imperdiet imperdiet orci. Nunc nec neque. Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi. Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo. Maecenas malesuada. Praesent congue erat at massa. Sed cursus turpis vitae tortor. Donec posuere vulputate arcu. Phasellus accumsan cursus velit.

\n" }, { "__typename": "fieldcollection_NewsCars", "title": "XYZ", "relatedCars": [ { "__typename": "object_Car", "name": "Impala", "color": [ "white" ] }, { "__typename": "object_Car", "name": "Impala", "color": [ "white" ] }, { "__typename": "object_Car", "name": "Coupe De Ville", "color": [ "blue" ] }, { "__typename": "object_Car", "name": "Bel Air", "color": [ "red", "white" ] } ] } ] } } } ``` --- ## Get objects Parent/Children/Siblings For example, to get `berlina` object's (id:261) parent, children and siblings ![](../../../img/graphql/sample_parentChildrenSiblings.png) #### Request :::info Note that for `children` and `_siblings` you can use the `objectTypes` argument to filter for specific types. ::: Any combination of `variant`, `object`, `folder` is possible as a value for the `objectTypes` argument (default: `["object", "folder"]`). ```graphql { getCar(id: 261) { id name parent { ... on object_Car { id name } } children(objectTypes: ["variant", "object"]) { ... on object_Car { id name color } } _siblings { ... on object_Car { id name } } } } ``` #### Response ```json { "data": { "getCar": { "id": "261", "name": "1900", "parent": { "id": "260", "name": "1900" }, "children": [ { "id": "263", "name": "1900", "color": [ "black" ] }, { "id": "262", "name": "1900", "color": [ "silver" ] } ], "_siblings": [ { "id": "264", "name": "1900 Sprint" } ] } } } ``` --- ## Get Linked Data ### Get Car With Referenced Manufacturer and Manufacturer Logo Image Thumbnail #### Configuration :::info Note that you have to adapt your schema definition as depicted below. ::: The thumbnail will be generated using the [Thumbnail operator](../../08_Operators/Query/AssetThumbnail.md). ![Schema Definition](../../../img/graphql/manufacturer_thumbnail.png) #### Request ```graphql { getCar(id:277, defaultLanguage:"en") { name frenchName: name(language: "fr") productionYear cylinders manufacturer { ...on object_Manufacturer { id name logo { fullpath } customThumbnail } } } } ``` #### Response ```json { "data": { "getCar": { "name": "Montreal", "frenchName": null, "productionYear": 1970, "cylinders": 8, "manufacturer": { "id": "28", "name": "Alfa Romeo", "logo": { "fullpath": "/Brand%20Logos/Alfa_Romeo_logo.png", "filesize": 101613 }, "customThumbnail": "/Brand%20Logos/image-thumb__290__galleryLightbox/Alfa_Romeo_logo.webp" } } } } ``` --- ## Translate Values The following example translates the `AccessoryPart` condition value. Deeplink: [http://demo.opendxp.io/admin/login/deeplink?object_373_object](http://demo.opendxp.io/admin/login/deeplink?object_373_object) Operator Config: ![Operator Config](../../../img/graphql/operator_translated1.png) #### Request ```graphql { getAccessoryPart(id: 373, defaultLanguage: "de") { # real condition condition # processed by the website translator with the prefix as defined in the export # config and the language as specified above translatedCondition } } ``` #### Response ```json { "data": { "getAccessoryPart": { "condition": "broken", "translatedCondition": "nicht mehr zu gebrauchen :-)" } } } ``` --- ## Using Aliases Aliases are used to rename the result of a field. This is useful when you want to return multiple fields with the same name. There are two ways to use aliases: ### Alias Operator See [Alias operator](../08_Operators/Query/Alias.md) for more information. ### Alias in the Query Get a `Car` with id 82 and return the number of doors. The first value is the alias, the second value is the field name. ##### Request ```graphql { getCar(id: 82) { doors: numberOfDoors } } ``` ##### Response ```json { "data": { "getCar": { "doors": 2 } } } ``` --- ## Add a Custom Query Datatype For adding a new query data type two steps are necessary: - add a type definition - provide a resolver implementation (optional) To add a type definition, add a section similar to this one to your `services.yml` file. ```yaml opendxp.datahub.graphql.dataobjectquerytypegenerator_datatype_mycustomdatatype: class: OpenDxp\Bundle\DataHubBundle\GraphQL\DataObjectQueryFieldConfigGenerator\MyCustomDatatype tags: - { name: opendxp.datahub.graphql.dataobjectquerytypegenerator, id: typegenerator_dataobjectquerydatatype_mycustomdatatype } ``` For reference, have a look at a look at the [`Link datatype`](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/DataObjectQueryFieldConfigGenerator/Link.php). It also shows how specific attributes are resolved. If you don't provide a resolver function then the getter method is called instead. --- ## Add a Custom Query Operator For adding a new query operator two steps are necessary: - add a type definition - add the operator implementation #### Type Definition Add a section similar to this one to your `services.yml` file. ```yaml opendxp.datahub.graphql.querytypegenerator_operator_mycustomoperator: class: OpenDxp\Bundle\DataHubBundle\GraphQL\QueryOperatorConfigGenerator\MyCustomOperator tags: - { name: opendxp.datahub.graphql.dataobjectquerytypegenerator, id: typegenerator_queryoperator_mycustomoperator } ``` For reference, have a look at a look at the [`Trimmer operator`](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/Query/Operator/Trimmer.php). #### Operator Implementation You have to provide both JavaScript code dealing with the UI configuration aspects specific to your operator and the server-side PHP implementation doing the actual calculations. A JS sample can be found [here](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Resources/public/js/queryoperator/Trimmer.js). :::info Note that the namespace would be `opendxp.plugin.datahub.operator.mycustomoperator`. ::: Make sure, that your extension gets loaded. See [OpenDxp Bundles](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Extending_OpenDxp/Bundle_Developers_Guide/OpenDxp_Bundles/index.html) docs page for further details. Next thing is to provide the server-side implementation. A sample can be found [here](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/Query/Operator/Trimmer.php). Finally, we have to define how the operator instances get created. In most cases we use the `DefaultOperatorFactory` for that: ```yaml opendxp.datahub.graphql.dataobjectqueryoperator.factory.mycustomoperator: class: OpenDxp\Bundle\DataHubBundle\GraphQL\Query\Operator\Factory\DefaultOperatorFactory arguments: $className: OpenDxp\Bundle\DataHubBundle\GraphQL\Query\Operator\MyCustomOperator tags: - { name: opendxp.datahub.graphql.dataobjectqueryoperator_factory, id: mycustomoperator } ``` --- ## Add a Custom Query You can extend the query schema and add your custom query in the following way. See [Events and Event Listeners](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Extending_OpenDxp/Event_API_and_Event_Manager.html) if you need more information on OpenDxp's event mechanism. ```php \OpenDxp::getEventDispatcher()->addListener(\OpenDxp\Bundle\DataHubBundle\Event\GraphQL\QueryEvents::PRE_BUILD, function (\OpenDxp\Bundle\DataHubBundle\Event\GraphQL\Model\QueryTypeEvent $event) { $config = $event->getConfig(); $outputType = new \GraphQL\Type\Definition\ObjectType([ 'name' => "CustomQueryResultType", 'fields' => [ 'outputFieldA' => [ 'type' => \GraphQL\Type\Definition\Type::string(), 'resolve' => function ($source, $args, $context, \GraphQL\Type\Definition\ResolveInfo $info) { return "A-value for item " . $source['resolvedId'] . " is " . uniqid(); } ], 'outputFieldB' => [ 'type' => \GraphQL\Type\Definition\Type::string(), 'resolve' => function ($source, $args, $context, \GraphQL\Type\Definition\ResolveInfo $info) { return "B-value for item " . $source['resolvedId'] . " is " . uniqid(); } ] ] ] ); $operation = [ 'type' => $outputType, 'args' => ['itemId' => ['type' => \GraphQL\Type\Definition\Type::nonNull(\GraphQL\Type\Definition\Type::int())]], 'resolve' => function ($source, $args, $context, \GraphQL\Type\Definition\ResolveInfo $info) { // resolve the item using the input parameters. Result will be passed // to the field-level resolvers return ['resolvedId' => $args['itemId']]; } ]; $config['fields']['performCustomQuery'] = $operation; $event->setConfig($config); }); ``` ![iExplorer](../../img/graphql/add_query.png) --- ## Document Mutations ### Supported Document Types * Email * Link * Page * ... ### Supported Page Element Types * Areablock * Block * Embed * Image (for now only target asset + alt text, no hotspots or markers) * Input * Multiselect * Scheduled Block * Select * Wysiwyg ### Mutation Modes There a two modes for document mutations. The Free-form API allows updating single editable content but requires lots of OpenDxp insight knowledge. The Tree API provides a more intuitive nested approach for creating and updating documents. #### Free-form API :::info Important Note: To be able to fully exploit this feature you have to understand OpenDxp's [editable naming strategy](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Documents/Editable_Naming_Strategies.html) ::: Update or add single or multiple editables by defining their exact name and their content. ###### Sample (Update Existing Document) ```graphql mutation { updateDocumentPage( id: 99 input: { editableUpdateStrategy: replaceAll # defaults to update editables: { input: [ { _editableName: "content:2.headline", text: "HEYYOU 3" } { _editableName: "headline", text: "NEW 2" } ] wysiwyg: [ { _editableName: "content:1.content", text: "my new wysiwyg" } ] } module: "mymodule" } ) { success document { controller } } } ``` ###### Additional Examples See following list for more examples with the free-form API approach: - [Create document with areablocks and nested block with images](./24_Mutation_Samples/01_FreeformAPI_Create_Document_with_Areablocks.md) - [Update email document](./24_Mutation_Samples/02_FreeformAPI_Update_Email_Document.md) - [Create a new link document](./24_Mutation_Samples/03_FreeformAPI_Create_new_Link_Document.md) #### Tree API If you are not familiar with OpenDxp's [editable naming strategy](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Documents/Editable_Naming_Strategies.html) you can also use the nested approach. #### Sample (Update a Page With an Areablock Using the Nested Approach) ```graphql mutation { updateDocumentPage( id: 99 input: { editables: { areablock: [ { _editableName: "content" items: [ { type: "headlines" editables: { input: [ { _editableName: "headline" text: "HEY, I AM A SUBHEADLINE" } ] } } ] } ] } controller: "@AppBundle\\Controller\\ContentController" action: "default" } ) { success document { controller elements { __typename } } } } ``` ###### Additional Examples See following list for more examples with the tree API approach: - [Create document with areablocks and nested block with images](./24_Mutation_Samples/04_TreeAPI_Create_Document_with_Areablocks.md) --- ## Asset Mutations ### Create Asset This will create an Asset with uploading data provided: ```graphql mutation { createAsset( parentId: 1, filename: "foo.png", type: "image", input: { data: "ewogICAgImZpZWxkY29sbGVjdGlvbiI6IFsKICAgICAgICB7CiAgICAgICAgICAgICJwYXJlbn...." }) { success message } } ``` ### Update Asset This will rename the Asset and update the data. Request: ```graphql mutation { updateAsset(id: 76, input: {filename:"newfilename", data:"iVBORw0KGgoAAAANSUhEUg....."}) { success message assetData { modificationDate } } } ``` ### Delete Asset ```graphql mutation { deleteAsset(id: 533) { success message } } or mutation { deleteAsset(fullpath: "/Sample Content/Background Images/foo.png") { success message } } ``` --- ## DataObject Mutations Data object mutations are used to create, update and delete data objects, documents, assets and translations. Keep in mind that for all kinds of mutations you need the `Write` permission and the mutation itself needs to be enabled in the configuration. :::info Please be aware, that not all operations are supported for all data types. ::: ![Mutation grid](../../img/graphql/mutation_grid.png) :::info Note that for `Create` and `Update` operate you can query the updated data using the same request. ::: ### Supported Mutation Datatypes Also check out the OpenDxp's [data type documentation](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Objects/Object_Classes/Data_Types/index.html). For supported mutation datatypes please check the `DataObjectMutationFieldConfigGenerator` folder in `src/GraphQL/`. ### Supported Mutation Operators See [operators section](../08_Operators/README.md) for more details. ### Create Object Request: ```graphql mutation { createNews(parentId: 429, key: "news_created_by_gql", published: false) { success message output(defaultLanguage: "de") { id creationDate fullpath title(language: "en") } } } ``` Response: ```json { "data": { "createNews": { "success": true, "message": "object created: 1196", "output": { "id": "1196", "creationDate": 1732785597, "fullpath": "/Product Data/Accessories/lights/indicator lights/chevrolet-bel air-tail lights/news_created_by_gql", "title": null } } } } ``` ### Update Object Updates german title and short text and returns the modification date. Request: ```graphql mutation { updateNews(id: 1196, defaultLanguage: "de", input: { title: "german TITLE", shortText: "new short text" } ) { success output { modificationDate, title } } } ``` Response: ```json { "data": { "updateNews": { "success": true, "output": { "modificationDate": 1732785648, "title": "german TITLE" } } } } ``` ### Delete Object Request: ```graphql mutation { deleteNews(id: 1196) { success message } } ``` Response: ```graphql { "data": { "deleteNews": { "success": true, "message": "" } } } ``` ### Extend Data Object Mutations It is possible to add custom mutation data types and mutation operators. For details see detail documentation pages: * [Add a custom mutation datatype](./25_Add_Custom_Mutation_Datatype.md) * [Add a custom mutation operator](./26_Add_Custom_Mutation_Operator.md) ### More Examples See following list for more examples with data object mutations: - [Add Relations](./24_Mutation_Samples/10_Sample_Add_Relations.md) - [Fieldcollection Mutations](./24_Mutation_Samples/15_Fieldcollection_Mutations.md) --- ## [FreeForm] Create Document With Areablocks and Nested Block With Images See demo document 99 for reference. ```graphql mutation { createDocumentPage( key: "documentkey47" parentId: 1 input: { editables: { areablock: [ { _editableName: "content" indices: [ { key: "1", type: "headlines", hidden: false } { key: "2", type: "wysiwyg-with-images", hidden: false } { key: "3", type: "image", hidden: false } ] } ] block: { _editableName: "content:2.images", indices: [1, 2] } image: [ { _editableName: "content:3.image", alt: "alt text", id: 67 } { _editableName: "content:2.images:1.image" alt: "alt text for image 1" id: 18 } { _editableName: "content:2.images:2.image" alt: "alt text for image 2" id: 22 } ] input: [ { _editableName: "content:1.headline" text: "HEY, I AM A SUBHEADLINE" } { _editableName: "headline", text: "THIS IS THE HEADLINE" } ] wysiwyg: [ { _editableName: "content:1.lead", text: "The lead text" } { _editableName: "content:2.content" text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book..." } ] } controller: "@AppBundle\\Controller\\ContentController" action: "default" } ) { success document { controller elements { __typename } } } } ``` --- ## [FreeForm] Update Email Document See demo document 144 for reference. ```graphql mutation { updateDocumentEmail( id: 144 editableUpdateStrategy: replaceAll # defaults to update input: { editables: { wysiwyg: [ { _editableName: "greeting_text" text: "Hello ... I am a Greeting Text" } ] } subject: "Email subject" } ) { success document { controller } } } ``` --- ## [FreeForm] Create a New Link Document ```graphql mutation { createDocumentLink(key: "newlinkdocument", parentId:1, input: { internal:308 internalType:"asset" } ) { success } } ``` ![Grid](../../../img/graphql/document_create_link.png) --- ## [TreeAPI] Create Document With Areablocks and Nested Block With Images Note that this produces the same result as [this example](./01_FreeformAPI_Create_Document_with_Areablocks.md) but uses the nested API instead of the free-form approach ```graphql mutation { createDocumentPage( key: "documentkey48" parentId: 1 input: { editables: { areablock: [ { _editableName: "content" items: [ { type: "headlines" hidden: false # optional replace: false # defaults to true, all editables will be replaced (of course, this only makes sense for updates) editables: { input: [ { _editableName: "headline" text: "HEY, I AM A SUBHEADLINE" } ] wysiwyg: [ { _editableName: "lead", text: "The lead text" } ] } } { type: "wysiwyg-with-images" replace: false editables: { block: [ { _editableName: "images" items: [ { replace: false # replace all elements inside the editable editables: { image: [ { _editableName: "image" alt: "alt text for image 1" id: 18 } ] } } { replace: true editables: { image: [ { _editableName: "image" alt: "alt text for image 2" id: 22 } ] } } ] } ] wysiwyg: [ { _editableName: "content" text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book..." } ] } } { type: "image" editables: { image: [ { _editableName: "image", alt: "alt text", id: 67 } ] } } ] } ] input: [{ _editableName: "headline", text: "THIS IS THE HEADLINE" }] } controller: "@AppBundle\\Controller\\ContentController" action: "default" } ) { success document { controller elements { __typename } } } } ``` --- ## Sample Add Relations This will add relations to categories relation field of Car object. Type can be omitted for mutations only allowing one type, e.g. many-to-many-objects . :::info Note: Read permissions are required for related objects to be assigned. ::: Request: ``` mutation { createCar ( key: "test-car", parentId: 1086, published: true, input: { name: "Test Car", categories: [ {id: 390, type: "object"}, {id: 392, type: "document"} ] } ) { output(defaultLanguage: "en") { id creationDate fullpath } } } ``` --- ## Fieldcollection Mutations A [Field Collection](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Objects/Object_Classes/Data_Types/Fieldcollections.html) is a list of items which can have different types. Since there is no `Union` input type in GraphQL, the approach for Fieldcollection mutations is different. The mutation processor expects a list of items for a specific type. Within the list, all items are listed with their indices and data. ### Example ``` mutation { updateNews( id: 1143 input: { content: { replace: false items: { NewsText: [{ index: 1, text: "news text" }] NewsCars: [ { index: 0, relatedCars: [{ type: "object", id: 318 }, { type: "object", id: 38 }] } { index: 2, title: "new cars", relatedCars: [{ type: "object", id: 156 }, { type: "object", id: 184 }] } ] } } } ) { success message } } ``` ### Notes #### Index The index is optional. If no index is provided then an autoincrement is used. #### Replace vs. Overwrite If `replace` is set to true (default is false) then the entire collection will be replaced. Otherwise individual items will be overwritten. --- ## Locale Collector ## Sample for Mutation Operator "Locale Collector" ```graphql mutation { updateTable( id: 7 input: { name_translated: { en: "Dinner table" de: "Esstisch" } } ) { success message output { name_en: name(language: "en") name_de: name(language: "de") } } } ``` --- ## Add a Custom Mutation Datatype For adding a new mutation data type two steps are necessary: - add an input type definition - provide a processor implementation Add a section similar to this one to your `services.yml` file. ```yaml opendxp.datahub.graphql.dataobjectmutationtypegenerator_datatype_mycustomdatatype: class: OpenDxp\Bundle\DataHubBundle\GraphQL\DataObjectMutationFieldConfigGenerator\MyCustomDatatype tags: - { name: opendxp.datahub.graphql.dataobjectmutationtypegenerator, id: typegenerator_dataobjectmutationdatatype_mycustomdatatype } ``` For reference, have a look at a look at the [`Geopoint datatype`](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/DataObjectMutationFieldConfigGenerator/Geopoint.php). You return a valid GraphQL input type (which is an `InputObjectType`) here and a `Processor` which processes the actual input data. For a rather simple example have a look at the [`Date`](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/DataObjectMutationFieldConfigGenerator/Date.php) implementation (which both accepts integer and string input values). --- ## Add a Custom Mutation Operator For adding a new mutation operator two steps are necessary: - add a type definition - add the operator implementation #### Type Definition Add a section similar to this one to your `services.yml` file. ```yaml opendxp.datahub.graphql.dataobjectmutationtypegenerator_operator_mycustommutationoperator: class: OpenDxp\Bundle\DataHubBundle\GraphQL\DataObjectMutationOperatorConfigGenerator\MyCustomMutationOperator tags: - { name: opendxp.datahub.graphql.dataobjectmutationtypegenerator, id: typegenerator_mutationoperator_mycustommutationoperator } ``` For reference have a look at: [`IfEmpty Operator`](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/DataObjectMutationOperatorConfigGenerator/IfEmpty.php). This will again define a processor (see the next subsection) and try to automatically determine the input type depending on its child element. #### Operator Implementation You have to provide both JavaScript code dealing with the UI configuration aspects specific to your operator and the server-side PHP implementation processing the input (the input processor according to your input schema). A JS sample can be found [here](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Resources/public/js/mutationoperator/IfEmpty.js). :::info Note that the namespace in your case would be `opendxp.plugin.datahub.mutationoperator.mycustommutationoperator`. ::: Make sure that your extension gets loaded. See [OpenDxp Bundles](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Extending_OpenDxp/Bundle_Developers_Guide/OpenDxp_Bundles/index.html) docs page for further details. Next thing is to provide the input processor on the server side. A sample can be found [here](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/GraphQL/DataObjectInputProcessor/IfEmptyOperator.php). It will get the child value and only overwrite the current value if it is empty. --- ## Add Custom Mutations You can extend the mutation schema and add your custom mutations in the following way. See [Events and Event Listeners](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Extending_OpenDxp/Event_API_and_Event_Manager.html) if you need more information on OpenDxp's event mechanism. ```php \OpenDxp::getEventDispatcher()->addListener(\OpenDxp\Bundle\DataHubBundle\Event\GraphQL\MutationEvents::PRE_BUILD, function (\OpenDxp\Bundle\DataHubBundle\Event\GraphQL\Model\MutationTypeEvent $event) { $config = $event->getConfig(); $opName = "performCustomMutation"; $inputType = new \GraphQL\Type\Definition\InputObjectType([ 'name' => "MyCustomInputTypeName", 'fields' => [ 'myCustomFieldName' => [ 'type' => \GraphQL\Type\Definition\Type::string() ] ] ]); $operation = [ 'type' => Type::string(), // the result type 'args' => [ 'id' => ['type' => Type::nonNull(\GraphQL\Type\Definition\Type::int())], 'input' => ['type' => $inputType], ], 'resolve' => function ($source, $args, $context, \GraphQL\Type\Definition\ResolveInfo $info) { // do something here $id = $args['id']; return "claiming that item " . $id . " has been updated to `" . $args['input']['myCustomFieldName'] . "`"; } ]; $config['fields'][$opName] = $operation; $event->setConfig($config); }); ``` ![iExplorer](../../img/graphql/add_mutation.png) --- ## If Empty Only sets the value if current one is empty. Add the operator to the list and drag & drop the desired field into the operator. ### Configuration ![ifempty_config.png](../../../img/graphql/ifempty_config.png) - **Label**: Field name to be used in the query. ### Example ![ifempty_example.png](../../../img/graphql/ifempty_example.png) Request: ```graphql mutation { updateCar( id:82 input:{ UpdateDescription:"Description if description is empty" } ) { success, output { description } } } ``` Response: ```json { "data": { "updateCar": { "success": true, "output": { "description": "Description if description is empty" } } } } ``` [] --- ## Locale Collector(Mutation) Allows editing all languages for a single field. ### Configuration ![locale_collector_config.png](../../../img/graphql/locale_collector_config.png) - **Label**: Name for the field to be used in the mutation. ### Example ![locale_collector_example.png](../../../img/graphql/locale_collector_example.png) Request: ```graphql mutation { updateCar( id:82 input:{ LocaleEditorName: { en:"Name_en", de:"Name_de", fr:"Name_fr" } } ) { success, output { name_en: name(language:"en"), name_de: name(language:"de"), name_fr: name(language:"fr") } } } ``` Response: ```json { "data": { "updateCar": { "success": true, "output": { "name_en": "Name_en", "name_de": "Name_de", "name_fr": "Name_fr" } } } } ``` --- ## Locale Switcher ![locale_switcher_config.png](../../../img/graphql/locale_switcher_config.png) Switches to different language other than the default language. Add the operator to the list and ### Configuration ![locale_switcher_example.png](../../../img/graphql/locale_switcher_example.png) - **Label**: Field name to be used in the query. - **Locale**: The locale you want to switch to. ### Example Request: ```graphql mutation { updateCar( id:82 input:{ name_ger:"Wert für name Feld" } ) { success, output { name_en:name(language:"en") name_de:name(language:"de") } } } ``` Response: ```json { "data": { "updateCar": { "success": true, "output": { "name_en": "Name_en", "name_de": "Wert für name Feld" } } } } ``` --- ## Alias Simply gives the child node a different name. If you are looking for a way to directly use aliases in a GraphQL query, please see [11_Using_Aliases.md](../../04_Query/11_Using_Aliases.md) . ### Configuration ![alias_config.png](../../../img/graphql/alias_config.png) - **Attribute**: The new name for the field to be used in the query. ### Example ![alias_example.png](../../../img/graphql/alias_example.png) Request: ```graphql { getCar(id: 82) { id, key, AliasForKey } } ``` Response: ```json { "data": { "getCar": { "id": "81", "key": "Cobra 427", "AliasForKey": "Cobra 427" } } } ``` --- ## Asset Thumbnail Returns the selected thumbnail URL. ### Configuration ![Thumbnail Config](../../../img/graphql/thumbnail_config.png) - **Attribute**: Name for the field to use in the query. - **Thumbnail**: Select the desired thumbnail from the list. ### Example ![thumbnail_example.png](../../../img/graphql/thumbnail_example.png) Request: ```graphql { getCar(id: 82) { id, contentThumbnail } } ``` Response: ```json { "data": { "getCar": { "id": "82", "contentThumbnail": "/Car%20Images/ac%20cars/68/image-thumb__68__content/automotive-car-classic-149813.44c4f656.jpg" } } } ``` [] --- ## Asset Thumbnail HTML Returns the selected thumbnail HTML tag. ### Configuration ![thumbnail_html_config.png](../../../img/graphql/thumbnail_html_config.png) - **Attribute**: Name for the field to use in the query. - **Thumbnail**: Select the desired thumbnail from the list. ### Example ![thumbnail_html_example.png](../../../img/graphql/thumbnail_html_example.png) Request: ```graphql { getCar(id: 82) { id, contentThumbnailHTML } } ``` Response: ```json { "data": { "getCar": { "id": "82", "contentThumbnailHTML": "\n\t\n\t\"\"\n\n" } } } ``` --- ## Concatenator Concatenates the values of the selected fields. ### Configuration ![concat_config.png](../../../img/graphql/concat_config.png) - **Label**: Name for the field to use in the query. - **Glue**: The string that will be used to concatenate the values. ### Example ![concat_example.png](../../../img/graphql/concat_example.png) Request: ```graphql { getCar(id: 82) { id, ConcatYearCountry } } ``` Response: ```json { "data": { "getCar": { "id": "82", "ConcatYearCountry": "1966-GB" } } } ``` --- ## Date Formatter Utilizes the PHP date formatter. ### Configuration ![date_formatter_config.png](../../../img/graphql/date_formatter_config.png) - **Label**: The name for the field to be used in the query . - **Date Format**: The format you want to use. For formatting options see [PHP Date Format](https://www.php.net/manual/en/function.date.php). ### Example ![date_formatter_example.png](../../../img/graphql/date_formatter_example.png) Request: ```graphql { getCar(id: 82) { id, modificationDate, FormattedModificationDate } } ``` Response: ```json { "data": { "getCar": { "id": "82", "modificationDate": 1732709167, "FormattedModificationDate": "Wednesday 27th of November 2024 12:06:07" } } } ``` --- ## Element Counter Counts the elements assigned to the selected field. Useful for counting the number of elements in a relation field. ### Configuration ![element_counter_config.png](../../../img/graphql/element_counter_config.png) - **Label**: Name for the field to use in the query. - **Count Empty**: If checked, the operator will also count empty fields. ### Example ![element_counter_example.png](../../../img/graphql/element_counter_example.png) Request: ```graphql { getCar(id: 82) { id, CategoriesCount } } ``` Response: ```json { "data": { "getCar": { "id": "82", "CategoriesCount": 2 } } } ``` --- ## Merge (deprecated) This operator is deprecated and will be removed in the next major release. --- ## Static Text Adds the configured static text to the query. ### Configuration ![static_text_config.png](../../../img/graphql/static_text_config.png) - **Text**: The text to add to the query. ### Example ![static_text_example.png](../../../img/graphql/static_text_example.png) Request: ```graphql { getCar(id: 82) { id, StaticTextForQuery } } ``` Result: ```json { "data": { "getCar": { "id": "81", "StaticTextForQuery": "StaticTextForQuery" } } } ``` --- ## Substring This operator extracts a substring from a string. ### Configuration ![substring_config.png](../../../img/graphql/substring_config.png) - **FieldName**: Name for the field to use in the query. - **Start**: The position of the first character to extract. - **Length**: The number of characters to extract. - **Ellipses**: If the string is longer than the specified length, an ellipsis is added at the end. ### Example ![substring_example.png](../../../img/graphql/substring_example.png) Request: ```graphql { getCar(id: 82) { id, description, ShortDescription } } ``` Response: ```json { "data": { "getCar": { "id": "82", "description": "

Description that clearly exceeds 10 characters in length

", "ShortDescription": "

Descript..." } } } ``` --- ## Translate Value Translates the values of the selected fields. For translation the default locale is used. Similar to OpenDxp's [Translate Value](https://docs.opendxp.io/docs/core-framework/User_Documentation/DataObjects/Grid_Configuration_Operators/Operators/TranslateValue.html). For a detailed example see [Website Translations](../../04_Query/11_Query_Samples/27_Sample_Translate_Values.md). ### Configuration ![translate_value_config.png](../../../img/graphql/translate_value_config.png) - **Label**: The label of the field. - **Prefix**: The prefix for the translation key. ### Example ![translate_value_example.png](../../../img/graphql/translate_value_example.png) :::info Note: Make sure to add the translation key to the translations in the OpenDxp backend, using the admin domain. ::: Request: ```graphql { getCar(id: 82) { id, TranslatedName } } ``` Response: ```json { "data": { "getCar": { "id": "82", "TranslatedName": "NameValuedAddedToTranslations" } } } ``` --- ## Trimmer Trims the value. ### Configuration ![trim_config.png](../../../img/graphql/trim_config.png) - **Label**: Name for the field to use in the query. - **Trim**: Where to trim, either `both`, `left`, `right` or `disabled`. ### Example ![trim_example.png](../../../img/graphql/trim_example.png) Request: ```graphql { getCar(id: 82) { id, name, TrimmedName } } ``` Response: ```json { "data": { "getCar": { "id": "82", "name": " Cobra 427 ", "TrimmedName": " Cobra 427" } } } ``` --- ## Operators Operators allow to modify and transform the data before it is delivered to the endpoint or stored in OpenDxp, depending on whether they are used in a query or a mutation. ![Overview](../../img/graphql/queryoperators_overview.png) Operators can be selected in the GraphQL configuration using the `Schema Definition` tab. In the `Query Schema` section use the `gear` icon to open the configuration dialog for a data object class you want to use in queries. In the `Mutation Schema` section use the `gear` icon to open the configuration dialog for a data object class you want to use in mutations. This will open the `Schema Fields` configuration dialog where you can select the fields you want to use in queries or mutations. In the tree on the left side you can select th operators you want to use by clicking on one of the 3 tabs: `Formatters`, `Others` or `Transformers`. Add an operator by double-clicking on it or by dragging it to the right side of the dialog. Depending on the operator an options dialog will open where you can configure the operator. After adding an operator you can drag & drop fields under the operator to apply the operator to them. Please see the contents of this chapter for more information on the available operators. --- ## Events(GraphQL) Datahub GraphQL events are based on the Symfony event dispatcher, and are triggered during execution of Query and Mutation requests. [Read more](https://docs.opendxp.io/docs/core-framework/Extending_OpenDxp/Event_API_and_Event_Manager) about events on OpenDxp documentation. All Datahub events are defined as a constant on component classes: - [Query](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Event/GraphQL/QueryEvents.php) - [Mutation](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Event/GraphQL/MutationEvents.php) - [Executor](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Event/GraphQL/ExecutorEvents.php) - [Listing](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Event/GraphQL/ListingEvents.php) - [Ouput cache](https://github.com/open-dxp/data-hub-bundle/blob/1.x/src/Event/GraphQL/OutputCacheEvents.php) ### Event Subscriber Examples With Symfony, you can listen to events using either [Event Listeners or Event Subscribers](https://symfony.com/doc/current/event_dispatcher.html). Event Subscribers are used in the examples below. Create a new class in `src/AppBundle/EventListener/GraphQlSubscriber.php` and use `autoconfigure: true` in your service configuration file (`app/config/services.yml` or `src/AppBundle/Resources/config/services.yml`) to let Symfony automatically recognize it as an Event Subscriber, either under `_defaults` or directly with the service: ```yml services: _defaults: # Defaults for this file autoconfigure: true # Let Symfony automatically configure Event Subscribers, Commands etc. # ... AppBundle\EventListener\: resource: '../../EventListener' ``` ##### Example 1: Query & Mutation execution ```php 'onPreExecute', //Pre execute on Query & Mutation ExecutorEvents::POST_EXECUTE => 'onPostExecute' //Post execute on Query & Mutation ]; } /** * @param ExecutorEvent $event */ public function onPreExecute(ExecutorEvent $event) { // do something with the query or schema $query = $event->getQuery(); $schema = $event->getSchema(); } /** * @param ExecutorResultEvent $event */ public function onPostExecute(ExecutorResultEvent $event) { // do something with output result $result = $event->getResult(); } } ``` ##### Example 2: Bypass workspace permissions with Query/Mutation build events ```php 'onMutationPreBuild', QueryEvents::PRE_BUILD => 'onQueryPreBuild' ]; } /** * @param MutationTypeEvent $event */ public function onMutationPreBuild(MutationTypeEvent $event) { $mutationType = $event->getMutationType(); $mutationType->setOmitPermissionCheck(true); //omit permission check for mutations } /** * @param QueryTypeEvent $event */ public function onQueryPreBuild(QueryTypeEvent $event) { $queryType = $event->getQueryType(); $queryType->setOmitPermissionCheck(true); //omit permission check for queries } } ``` ##### Example 3: Add custom arguments to existing types ```php 'onMutationPostBuild', QueryEvents::POST_BUILD => 'onQueryPostBuild' ]; } /** * @param MutationTypeEvent $event */ public function onMutationPostBuild(MutationTypeEvent $event) { $config = $event->getConfig(); //additional check for a field value $config['fields']['createProduct']['args']['foo'] = [ 'type' => Type::nonNull(Type::string()) ]; //additional checks for input fields $input = $config['fields']['createProduct']['args']['input']; $input->config['fields']['foo'] = [ 'type' => Type::nonNull(Type::string()) ]; $event->setConfig($config); } /** * @param QueryTypeEvent $event */ public function onQueryPostBuild(QueryTypeEvent $event) { $config = $event->getConfig(); $config['fields']['getProductListing']['args']['foo'] = [ 'type' => Type::boolean() ]; $event->setConfig($config); } } ``` ##### Example 4: Add custom query conditions to object listing - For simple filter conditions also see [Filtering](./04_Query/10_Filtering.md) ```php 'onListingPreLoad', ]; } /** * @param ListingEvent $event */ public function onListingPreLoad(ListingEvent $event) { $listing = $event->getListing(); if ($listing->getClassName() === 'Product') { $listing->setCondition(sprintf('(%s IN (SELECT %s FROM objects WHERE %s=\'object\') AND %s = \'variant\')', Service::getVersionDependentDatabaseColumnName('o_parentid'), Service::getVersionDependentDatabaseColumnName('o_id'), Service::getVersionDependentDatabaseColumnName('o_type'), Service::getVersionDependentDatabaseColumnName('o_type'))); } $event->setListing($listing); } } ``` ##### Example 5: Add custom conditions to enable/disable output (responses) cache per request - `OutputCacheEvents::PRE_LOAD`: is triggered before trying to load an entry from cache, if cache is enabled. You can disable the cache for this request by setting `$event->setUseCache(false)`. If you disable the cache, the entry won't be loaded nor saved - `OutputCacheEvents::PRE_SAVE`: if cache is enabled, it's triggered before saving an entry into the cache. You can use it to modify the response before it gets saved. Uncacheable headers, such as CORS Access-Control-Allow-Origin, are removed from the response before the PRE_SAVE event and re-added after the cached response is loaded. ```php 'onPreLoadCache', OutputCacheEvents::PRE_SAVE => 'onPreSaveCache' ]; } /** * @param OutputCachePreLoadEvent $event */ public function onPreLoadCache(OutputCachePreLoadEvent $event) { $uri = $event->getRequest()->getMethod(); if(str_contains($uri, "my-special-endpoint")) { $event->setUseCache(false); } } /** * @param OutputCachePreSaveEvent $event */ public function onPreSaveCache(OutputCachePreSaveEvent $event) { $uri = $event->getRequest()->getMethod(); if(str_contains($uri, "my-awesome-endpoint")) { $response = $event->getResponse(); // modify the response as you want it to be saved... $event->setResponse($response); } } } ``` --- ## GraphQL ## ![GraphQL Icon](../img/graphql/logo_small.png) GraphQL With [GraphQL](https://graphql.org/) endpoints, Datahub allows integrating OpenDxp to other systems and services via GraphQL and test them with the integrated [GraphiQL explorer](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) tool right away. ![Explorer](../img/graphql/iexplorer.png) ### Configuration Configuration takes place in the endpoint configuration and offers following possibilities: - [General Settings](./01_Configuration/01_General_Settings.md) - [Schema Definition](./01_Configuration/02_Schema_Settings.md) - [Security Settings](./01_Configuration/03_Security_Settings.md) - [Custom Permissions](./01_Configuration/04_Custom_Permissions.md) ### External Access The standard endpoint is ``` /opendxp-graphql-webservices/{configurationname}?apikey={yourApiKey} ``` So if your configuration name is blogdemo and your apikey 123456 then your endpoint would be ``` /opendxp-graphql-webservices/blogdemo?apikey=123456 ``` Here is a configuration how to [override the standard endpoint](./01_Configuration/15_Customize_Endpoint_URL.md) ### Queries Depending on the configuration, the endpoint provides several queries to fetch data from OpenDxp. As Datahub always creates a proper graphQL schema, also have a look at the generated schema to get details for the possible queries of a certain endpoint. On the following pages certain generic aspects are explained, and a couple of samples are listed: * For details on Document queries see [Document Query Documentation](./04_Query/01_Document_Queries.md). * For details on Asset queries see [Asset Query Documentation](./04_Query/04_Asset_Queries.md). * For details on DataObjects queries see [DataObject Query Documentation](./04_Query/05_DataObject_Queries.md). * For details on how to add custom queries see [Add Custom Queries Documentation](./04_Query/20_Add_Custom_Query.md). ### Mutations Depending on the configuration, the endpoint provides several mutations to update data in OpenDxp. As Datahub always creates a proper graphQL schema, also have a look at the generated schema to get details for the possible mutations of a certain endpoint. See following pages for a general overview of possible mutations: - For details on Document mutations see [Document Mutation Documentation](./07_Mutation/01_Document_Mutations.md) - For details on Asset mutations see [Asset Mutation Documentation](./07_Mutation/04_Asset_Mutations.md) - For details on DataObject mutations see [DataObject Mutation Documentation](./07_Mutation/20_DataObject_Mutations.md) - For details on how to add custom mutations see [Add Custom Mutations Documentation](./07_Mutation/27_Add_Custom_Mutations.md). ### Hands-On-Testing Using GraphiQL Explorer [GraphiQL explorer](https://github.com/graphql/graphiql/tree/main/packages/graphiql#readme) can be opened for an endpoint in an iframe within OpenDxp or as an additional browser tab. ![Open iExplorer](../img/graphql/open_explorer.png) ### Events It is possible to customize default behavior of graphQL endpoint with event listeners. For details see [Events Documentation](./10_Events.md). ### Output Cache It is possible to keep a cache of the responses delivered by the endpoint, using the same default cache backend configured for OpenDxp (Doctrine, Redis,...). This is specially useful to speed up the endpoint replies when it produces complex responses with many dependencies. The cache can be enabled and configured with a configuration entry like this in your `config.yml` file: ```yml #### DATAHUB OUTPUT CACHE opendxp_data_hub: graphql: output_cache_enabled: true # Enables/disables the output (responses) cache output_cache_lifetime: 20 # If enabled, for how many seconds each response will be cached ``` By default the cache is disabled but if it is enabled and you don't specify a value for `output_cache_lifetime`, its default value is set to 30 seconds. #### Disable Output Cache for a Single Request (Only in DEBUG MODE) Just add the parameter `?opendxp_outputfilters_disabled=true` to the URL. This works in a similar way as the [OpenDxp's Full Page Cache](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Development_Tools_and_Details/Cache/Full_Page_Cache.html). #### Customize the Cache Behaviour It is possible to customize some behavior of output cache with event listeners. For details see [Events Documentation](./10_Events.md). #### Note on Debugging With iGraplQL Playground Open the settings and change `request.credentials` to `include`. Otherwise the `XDEBUG_SESSION` cookie header will get removed by default. ![Settings](../img/graphql/debugging.png) --- ## Configuration & Deployment The configuration by default is saved in `var/config/data-hub/example.yaml`. Additionally, a workspace permission index is kept in the database for better query performance when checking for permissions. When deploying configurations following steps are necessary: - Deploy configuration file `/var/config/.../example.yaml` - e.g. check it into your VCS and deploy it with your deployment mechanisms. - Rebuild workspaces by running `datahub:configuration:rebuild-workspaces` Either call: ```bash datahub:configuration:rebuild-workspaces ``` to do that for all definitions, or: ```bash datahub:configuration:rebuild-workspaces --configs=assets,events ``` for specific definitions. :::warning Note: The command ```datahub:graphql:rebuild-definitions ``` is marked as deprecated and will be removed in a future release. ::: #### Configuration Storage The configuration user interface utilizes the `LocationAwareConfigRepository` for storing the configuration. In the symfony tree the storage location can be configured, possible values are - `symfony-config` - write configs as Symfony Config as YAML files to `/var/config/data_hub/.yaml` - `settings-store` - write configs to the SettingsStore - `disabled` - do not allow to edit/write configs at all > Important: When using symfony-config write target, configs are written to Symfony Config files (yaml), which are only getting revalidated in debug mode. So if you're changing configs in production you won't see any update, because these configs are read only. Details also see [OpenDxp Docs](https://docs.opendxp.io/docs/core-framework/Development_Documentation/Deployment/Configuration_Environments.html#page_Configuration-Storage-Locations-Fallbacks). ##### Example ```yaml opendxp_data_hub: config_location: data_hub: write_target: type: 'symfony-config' options: directory: '/var/www/html/var/config/data_hub' ``` Additionally, it is also possible to define the configuration directly in a symfony configuration file without using the configuration user interface. In this case, the configuration user interface is just read only. ##### Sample Configuration File ```yml opendxp_data_hub: configurations: : general: active: true type: '' name: '' description: '' group: ' sqlObjectCondition: '' modificationDate: path: '' createDate: ' schema: queryEntities: { } mutationEntities: { } specialEntities: document: read: false create: false update: false delete: false ... --- ## Changelog(Data-hub) ### 1.1.1 - [BUGFIX] GraphQL endpoints build their schema again when a class has a Block field [#32](https://github.com/open-dxp/data-hub-bundle/pull/32) - [CHORE] Check dependencies, code and commits for security issues ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.8 - [BUGFIX] Add _object_folder to relation and object property unions [#24](https://github.com/open-dxp/data-hub-bundle/pull/24) ### 1.0.7 - [BUGFIX] Make getDocument folder-safe (resolve document folders) [#22](https://github.com/open-dxp/data-hub-bundle/pull/22) - [BUGFIX] Register _object_folder in relation/object union getTypes() [#23](https://github.com/open-dxp/data-hub-bundle/pull/23) ### 1.0.6 - [BUGFIX] Fix undefined array key when a document image editable references a missing asset [#20](https://github.com/open-dxp/data-hub-bundle/pull/20) - [ENHANCEMENT] Improve RenderletType relation resolution and type field [#21](https://github.com/open-dxp/data-hub-bundle/pull/21) ### 1.0.5 - [BUGFIX] Fix undefined array key in document editables sort index for nested blocks [#19](https://github.com/open-dxp/data-hub-bundle/pull/19) - [BUGFIX] Fix misleading and misspelled property/metadata key descriptions [#18](https://github.com/open-dxp/data-hub-bundle/pull/18) - [BUGFIX] DocumentFolderType: use key instead of filename field [#17](https://github.com/open-dxp/data-hub-bundle/pull/17) ### 1.0.4 - [BUGFIX] Fix relations/properties pointing to document folders [#16](https://github.com/open-dxp/data-hub-bundle/pull/16) ### 1.0.3 - [BUGFIX] Fix relations to object folder [#14](https://github.com/open-dxp/data-hub-bundle/pull/14) - [ENHANCEMENT] Add php 8.5 support [#15](https://github.com/open-dxp/data-hub-bundle/pull/15) ### 1.0.2 - [CHORE] Update branding names [#11](https://github.com/open-dxp/data-hub-bundle/pull/11) - [CHORE] Remove outdated references to GitHub issues and comments. [#12](https://github.com/open-dxp/data-hub-bundle/pull/12) - [BUGFIX] AreablockDataType: Remove _editableType and _editableName fields [#8](https://github.com/open-dxp/data-hub-bundle/pull/8) - [BUGFIX] DocumentFolderType: Missing type and properties fields [#7](https://github.com/open-dxp/data-hub-bundle/pull/7) - [BUGFIX] Add missing Asset\Image focalPoints [#10](https://github.com/open-dxp/data-hub-bundle/pull/10) - [BUGFIX] Add missing DocumentElementType Renderlet [#9](https://github.com/open-dxp/data-hub-bundle/pull/9) ### 1.0.1 - [CHORE] Adjust Test Setup [#4](https://github.com/open-dxp/data-hub-bundle/pull/4) - [CHORE] Apply changes from upstream version 1.9.5 [#6](https://github.com/open-dxp/data-hub-bundle/pull/6) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix tests [#1](https://github.com/open-dxp/data-hub-bundle/pull/1) - [CHORE] Fix tests [#2](https://github.com/open-dxp/data-hub-bundle/pull/2) - [CHORE] Update references & docs [#3](https://github.com/open-dxp/data-hub-bundle/pull/3) --- ## Installation(Data-importer) ### Required Bundles This bundle depends on OpenDXP [Datahub bundle](https://github.com/open-dxp/data-hub-bundle). This needs to be installed first. ### Installation Process #### For OpenDXP >= 10.5 To install OpenDXP Data Importer for OpenDXP 10.5 or higher, follow the three steps below: 1. Install the required dependencies: ```bash composer require open-dxp/data-importer-bundle ``` 2. Make sure the bundle is enabled in the `config/bundles.php` file. The following lines should be added: ```php use OpenDxp\Bundle\DataImporterBundle\OpenDxpDataImporterBundle; // ... return [ // ... // make sure OpenDxpDataHubBundle is added before to that list // ... OpenDxpDataImporterBundle::class => ['all' => true], // ... ]; ``` 3. Install the bundle: ```bash bin/console opendxp:bundle:install OpenDxpDataImporterBundle ``` > Make sure the Datahub bundle's priority is higher than the Data Importer bundle's. > > This can be specified as a parameter during bundle enablement ### Bundle Configuration #### Import Execution The imports are executed asynchronously in the background. The processing can be done via executing commands on a regular basis or by utilizing symfony messenger. Either of the two needs to be configured. ##### Command Based For command based importing, following commands need to be executed on regular base. The actual interval depends on use cases and system environment. ```bash # Process import queue items that can be executed in parallel */5 * * * * php /home/project/www/bin/console datahub:data-importer:process-queue-parallel --processes=5 # Process import queue items that need to be executed sequentially */5 * * * * php /home/project/www/bin/console datahub:data-importer:process-queue-sequential ``` See [Import Execution Details](04_Import_Execution_Details.md) for more information about sequential and parallel execution. ##### Symfony Messenger Based For symfony messenger based importing, at least following configuration needs to be done in symfony configuration: ```yml opendxp_data_importer: messenger_queue_processing: activated: true ``` If activated, the processing is kicked off automatically as soon as an import is prepared. In addition to that, following settings are available. They all have meaningful default values though: - `worker_count_parallel`: Count of maximum parallel worker messages for parallel imports. - `worker_item_count`: Count of items imported per worker message. - `worker_count_lifetime`: Lifetime of tmp store entry for current worker count entry. After lifetime, the value will be cleared. Messages are dispatched via `opendxp_data_import` transport. So make sure, you have workers processing this transport when activating the messenger based queue processing. #### Cron Execution Import configuration can be setup to be executed on regular base by defining a cron definition. To make sure, the cron definitions are checked on regular base, following command needs to be executed on regular base. The actual interval depends on use cases and system environment; the shorter, the more accurate the import execution will take place. ```bash # Check cron configurations and execute necessary import definitions * * * * * php /home/project/www/bin/console datahub:data-importer:execute-cron ``` --- ## Data Sources Every data importer configuration needs a data source. Following data sources are available and can be configured. #### Asset ![Data Source Asset](../img/datasource_asset.png) Loads data from an asset stored within the OpenDXP instance. ###### Configuration Options: - **Path to asset** #### SFTP Loads data from a (remote) sftp location. ###### Configuration Options: - **Host** - **Port** - **Username** - **Password** - **Remote Path**: Absolute path on remote location. #### HTTP Loads data from a (remote) http location. ###### Configuration Options: - **Schema**: one of `http://` or `https://` which is prepened to the URL. - **Url**: Url to file without schema definition (which is added based on schema configuration due to security reasons). This implementation uses [php wrappers](https://www.php.net/manual/en/wrappers.http.php) internally, so encoding username and password is supported as follows: `user:password@example.com`. #### Push The `push` data source does not download the data from a remote location, it provides a http endpoint where data can be pushed to via a POST request. The data needs to be in the configured file format and provided as raw content of the POST request. The `push` data source internally uses `php://input` to read the content. The URL for the endpoint is: `http(s)://>/opendxp-datahub-import//push` ###### Configuration Options: - **API Key**: API Key that needs to be set as `authorization` header for every push request. - **Ignore not empty queue**: By default, imports are only started when import queue is empty (see also [Import Execution Details](../04_Import_Execution_Details.md)). Thus pushing data to the endpoint when import queue is not empty would result in an error. Activating this flag will ignore existing items in the queue and always adds items to the queue when data is pushed to the endpoint. #### SQL ![Data Source SQL](../img/datasource_sql.png) Loads data from a defined doctrine connection. The SQL Data Loader uses [DBAL](https://www.doctrine-project.org/projects/dbal.html) to allow data to be loaded from a SQL source. Connections to any database supported by DBAL will work provided they are configured correctly inside of `database.yaml`. (Database configuration can be placed in any valid Symfony config file, provided its in the correct format as can be seen in `database.yaml`). Example connection: ```yaml doctrine: dbal: connections: new_connection: host: db port: '3306' user: sample_user password: sample_password dbname: sample_dbname driver: any_supported_by_doctrine ``` For different drivers some additional configuration could be needed. ###### Configuration Options: - **Connection**: Connection from which data will be loaded - **SELECT**: Valid SQL `SELECT` - **FROM**: Valid SQL `FROM` - **WHERE**: Valid SQL `WHERE` - **GROUP BY**: Valid SQL `GROUP BY` Ensure to select **SQL** under File Format! --- ## File Formats The source data needs to be in an interpretable format for the importer. Following interpreters can be configured: #### CSV The source data is interpreted as CSV. ###### Configuration Options: - **Skip First Row**: If activated, first row will be used as column names and not interpreted as data row. - **Delimiter** - **Enclosure** - **Escape** Internally the adapter uses [`fgetcsv`](https://www.php.net/manual/en/function.fgetcsv.php) function of php. #### JSON The source data is interpreted as JSON. The adapter expects an array of json objects and reads all first level attributes as separate fields. If one field contains sub objects (like `technical_attributes`) in the example below, this object is interpreted as array in one field (and needs to be considered in the transformation pipeline). **Sample File**: ```json [ { "title_de": "Voluptas et est voluptas.", "title_en": "Animi ipsam rem et sed vel voluptas.", ... "technical_attributes": { "1-6": "value 1", "2-4": "value 2" } }, { "title_de": "Et alias nesciunt ea mollitia nihil mollitia corporis.", ... }, ] ``` Internally the adapter uses [`json_decode($content, true)`](https://www.php.net/manual/en/function.json-decode.php) function of php. #### XLSX (Excel) The source data is interpreted as XLSX Excel file. ###### Configuration Options: - **Skip First Row**: If activated, first row will be used as column names and not interpreted as data row. - **Sheet**: Name of data sheet to be imported. Internally the adapter uses [`phpspreadsheet`](https://phpspreadsheet.readthedocs.io/en/latest) to read the data. #### XML The source data is interpreted as XML. The adapter expects a list of data elements at the configued xpath and reads all first level elements of the data elements as separate fields. If one element contains sub elements (like `technical_attributes`) in the example below, this the sub elements are interpreted as array in one field (and needs to be considered in the transformation pipeline). ###### Configuration Options: - **XPath**: XPath to the elements to be imported. For the sample below it would be `/root/item`. - **Schema**: XSD Schema the import data should be validated against. If not defined, to validation takes place. **Sample File**: ```xml Et voluptas culpa et incidunt laborum repellat. Aliquam et voluptas nemo at excepturi. ... 1-6 Myrtle Kovacek 2-4 Ut. ... ``` Internally the adapter uses [Symfony `XmlUtils`](https://github.com/symfony/config/blob/master/Util/XmlUtils.php) to read and validate the data. #### Custom File Formats You can import any file format using custom adapters. --- ## Import Preview The import configuration allows to show a preview of the data which helps to setup the [mapping configuration](06_Mapping_Configuration/README.md) and validate the expected results. ![Import Preview](../img/import_preview.png) The preview interprets the file the same way as actual import data sources will be interpreted when executing the import and shows one record of the preview file at once. The preview does not import any data though. Any changes in file format settings result in a reloading of the uploaded preview file. Reloading the preview file or paging the records will also update the processing result preview of the [mapping configuration](06_Mapping_Configuration/README.md). There are two options for loading the preview file: - Upload an extra preview file. - Copy the preview file from the configured data source (not possible with push data source). For both options, preview files are saved per user and import configuration in OpenDXPs `tmp` directory and should only be a small extract of the actual import files - due to loading performance and used storage space. --- ## Resolver Settings Resolver settings are responsible to define to which OpenDXP data imported data should be imported to and consists of following parts: ![Resolver Settings](../img/resolver_settings.png) #### Class Define the OpenDXP data object class of the imported data. #### Element Loading Define a strategy the importer should use for looking for existing OpenDXP data objects in order to update them instead of creating new data objects. Following strategies are available: ##### Loading Strategy: `No Loading` Does not look for any existing OpenDXP data objects. Import always creates new data objects. ##### Loading Strategy: `Id` Look for data objects based on their id. - **Data Source Index**: Field of import that contains the id to look for. ##### Loading Strategy: `Path` Look for data objects based on their full path. - **Data Source Index**: Field of import that contains the path to look for. ##### Loading Strategy: `Attribute` Look for data objects based on a specific attribute (e.g. Remote Id, EAN, ...). - **Data Source Index**: Field of import that contains the attribute value to look for. - **Attribute Name**: Attribute of data object to look for. #### Element Creation Define location of new created data objects. ##### Location Strategy: `Static Path` Always put new elements to a fixed specific folder. - **Path**: Folder where to put new elements to. ##### Location Strategy: `Find Parent` Find parent based on a strategy. - **Find Strategy**: Strategy find to parent - Loading Strategy `Id`: Load based on id. - Loading Strategy `Path`: Load based on full path. - Loading Strategy `Attribute`: Load based on data attribute with additional settings: - Class: Data object class to look for (can be different one that the imported data object class) - Attribute Name: Attribute of data object to look for. - **Data Source Index**: Field of import that contains the value to look for. - **Fallback Path**: Folder to use if parent cannot be found. #### Element Location Update Define location updates of data objects. The importer applies the location update strategy to all imported data objects - no matter if they are updated or created. For details on the strategies see Element Creation above. In addition, there is a `No Change` strategy that does not change the location of elements at all. #### Element Publishing Define a strategy to set the published state of data object during import. Following strategies are available: - **Always Publish**: Always publishes new created or updated data objects. - **Attribute Based**: Set publish state based on a field of the import data. - **No Change, Publish New**: Do not change existing data objects and set new data objects to `published`. - **No Change, Unpublish New**: Do not change existing data objects and set new data objects to `unpublished`. --- ## Processing Settings There are a couple of processing settings that allow fine-tuning the import process. #### Execution Type There are two types of processing - sequential and parallel - which are configured in the import configuration. For details see [Import Execution Details](../04_Import_Execution_Details.md). #### Archive File Import Define if the importer should archive the imported file for later traceability. When activated, the importer will create an application logger entry with the imported file as file object attached. Be aware of needed disk space for archiving the data and that the importer creates a log entry of every single data row in application logger anyway. For details also see [Import Process and Logging](../05_Import_Progress_and_Logging.md). #### Delta Check > This option requires an id field in the import data. With active delta check, the importer checks if imported data has changed since last import and imports data only if updates are available. This might speed-up import because only updated data object will be processed and saved. The delta check is based on hashes and compares the import data only. It does not consider any other changes of the data object if self, that might occur in the meantime between two imports. Be aware that calculating and saving hashes for delta checking needs additional resources. So use this option wisely. #### Cleanup > This option requires an id field in the import data. The importer can cleanup in OpenDXP existing data objects if they are not part of the current import data anymore. There are two cleanup strategies available: - Unpublish: Unpublish data object to be cleaned up. - Delete: Delete data object to be cleaned up. Only activate this option, if the imports are always full-imports. Otherwise there might be data loss. For details see also [Import Execution Details](../04_Import_Execution_Details.md). --- ## Transformation Pipeline The transformation pipeline takes the data read from source data based on the `Source Attributes` setting and transforms it to a necessary target format with one or multiple operators. ![Import Preview](../../img/transformation_pipeline.png) The transformation result panels shows information about the current resulting type of the transformation and - if a preview file is uploaded - also a preview based on the currently active data record of the preview panel. The result type is also important for the [Data Target](./03_Data_Target/README.md) setting as it defines available options there. #### Operators Operators transform the input data to a desired output format. Every operator expects certain input formats and delivers certain an output format. There are two groups of operators - Standard Operators: Do some real processing and transformation with the input data. - Factory Operators: Prepare data for a certain necessary result type, e.g. convert a date to a `Carbon\Date` so it can be assigned to a date field etc. Their name is usually prefixed with `As`. ##### List of available Operators - **As Array**: Converts data to an array, if not already. - **As Boolean**: Converts data to a boolean. - **As Date**: Converts data to a date, format definition necessary. - **As Gallery**: Packs a single asset, or an asset array to a gallery. - **As Image Advanced**: Packs a single asset to an image advanced. - **As Input Quantity Value**: Converts an array to a quantity value object for input quanitity value, expects first item in array to be value, second item in array to be unit id. - **As Input Quantity Value Array**: Same like `As Input Quantity Value`, but for arrays of values. Expects an array with sub-arrays where first item to be value and second item to be unit id each and results in an array of quantity value objects. - **As Numeric**: Converts data to a numeric with type casting. - `Return null if empty` option: | Input | Output | | ------- | ---------- | | 1234 | 1234 | | String | --EMPTY-- | | | --EMPTY-- | | 0 | 0 | - **As Quantity Value**: Converts an array to a quantity value object for quanitity value, expects first item in array to be value, second item in array to be unit id. - **As Quantity Value Array**: Same like `As Quantity Value`, but for arrays of values. Expects an array with sub-arrays where first item to be value and second item to be unit id each and results in an array of quantity value objects. - **As Geopoint**: Expects an array, where the first item reflects the value for the latitude attribute and the second item reflects the value for the longitude attribute. - **As Geobounds**: Expects an array, where the first and second item reflect the values for the northeastern latitude and longitude, third and fourth item reflect the values for the southwestern latitude and longitude respectively. - **As Geopolygon**: Expects an array with a variable amount of items. Whereas first and second item reflect latitude and longitude for the first point, third and fourth item for the second point and so on. - **As Geopolyline**: Same as `As Geopolygon`. - **As Color**: Converts an array(R,G,B,A) or a hex-string to a color object. - **As Countries**: Converts an array of countries into an array of country codes - **Combine**: Combines an array to a string with using configuerd `glue`. - **Explode**: Explodes string to array using configured `delimiter`. If input is an array, explode is done on every array item recursively. Depending if `Do not flatten sub arrays` is set, the operator results in one flat array with all items, or in an array with sub arrays. - **Flatten Array**: Converts one array with potential sub arrays into one flat array with all items and sub items in one level. - **HTML Decode**: Applies `html_entity_decode` to input data. - **Import Asset**: Expects a URL as input, downloads data via `file_get_contents` and stores it as new asset in configured target folder. File name is extracted from URL via `basename`. If asset with same name already exists, either it is reused (when `Use Existing Asset` activated), or a new asset with suffix in file name is generated. - **Load Asset**: Loads existing asset based on path or id - **Load DataObject**: Loads existing data object based on id, path or specific attribute. With specific attribute it is possible to find the object with a partial match of the attribute value (e.g. data value `%foo%` would find an object with attribute value `barfoobar`) - **Reduce Array KeyValue Pairs**: Reduces a flat array `['k1', 'v1', 'k2', 'v2']` to key-value pair array `['k1' => 'v1', 'k2' => 'v2']`. - **Trim**: Removes leading and/or tailing white spaces from string. - **Static Text**: Adds a static text to the value - either prepends or appends it. - **Conditional Conversion**: String values are converted to other string values (e.g. '0' to '1' or 'csv-value' to 'object-value'). Multiple conversions can be configured by separating the values with pipe symbol ('|') (e.g. '0|1|2' to 'some|other|values'). An asterisk can be used as a wildcard (e.g. '0|\*' to 'no value|default' where '0' will be converted to 'no value' and all other values to 'default'). ##### What Operators are NOT supposed to do: - **Complex statistical calculations**: you possibly get an idea like that you can explode string to array and then calculate some average value, but it is wrong place to do it. Please keep the import peformance light. - **Assign data to data object fields**: One import is updating fields of one Data Object. If you need to update another one then please create one more import. --- ## Classification Store Batch Details The `Classification Store Batch` data target allows assigning multiple classification store attributes with one mapping. There are a couple of aspects important to know about. #### Transformation Result Format The `Classification Store Batch` data target requires an array with `-` as keys, and values to be assigned as array values. This format has to be prepared by the transformation pipeline in advance. The simpliest way to archive that is using a JSON data source like ```json [ { "remote-id": 1, "datastore_input": { "1-1": "some value object 1", "1-2": "some other value object 1" } }, { "remote-id": 2, "datastore_input": { "1-1": "some value" } } ] ``` and then just use the `As Array` operator to import the data. ![Transformation Pipeline](../../../img/data_target_classification_store_batch_simple.png) As an alternative, it is also possible to encode the data into one data field (e.g. for CSVs) and use more operators of the transformation pipiline to archive the required format. An example data could be `1-6#value 1||2-4#value 2`. The corresponding transformation pipeline would then be something like the following ![Transformation Pipeline](../../../img/data_target_classification_store_batch_decoding.png) #### Assign Complex Data Values Assigning more complex values (like `date` or `quantityValue`) to the classification store requires some more operators to be added to the transformation pipeline, as the values need to be transformed to a `date` or `quantityValue`. This is possible, with one restriction: One transformation pipeline can result in one complex value type only. It is not possible to mix values in one mapping with one transformation pipeline. When importing different complex data types to a classification store, they need to be splitted by type. An import file could look as follows: ```json [ { "remote-id": 1, "datastore_input": { "1-1": "some value object 1", "1-2": "some other value object 1" }, "datastore_date": { "1-4": "2021-07-22" }, "datastore_unit": { "1-3": "234 km" } }, { "remote-id": 2, "datastore_input": { "1-1": "some value" }, "datastore_date": { "1-4": "2021-07-21" }, "datastore_unit": { "1-3": "54 km" } } ] ``` The mapping needs to contain a mapping entry for each `datastore_*` which all assign the data to the same classification store field. Mappings for `date` and `quantityValue` attributes can look as follows (please notice that in that context, `As Quantity Value Array` is used). ![Transformation Pipeline](../../../img/data_target_classification_store_batch_date.png) ![Transformation Pipeline](../../../img/data_target_classification_store_batch_quantityValue.png) --- ## Data Target Data target definition assigns the result of the transformation pipeline to a data object field. The available data object fields for assignment depend on the transformation result of the [transformation pipeline](../02_Transformation_Pipeline.md). Three different data target types are available: #### Direct Assign data directly to fields defined directly in the data object class, object bricks or localized fields. The naming schema for Object brick fields is `..`. ![Data Target Direct](../../../img/data_target_direct.png) > The availability of target fields depends on the settings and the result type of the transformation pipeline. #### Classification Store Assign data to specific keys in a classification store. ![Data Target Classification Store](../../../img/data_target_classification_store.png) > The availability of target fields depends on the settings and the result type of the transformation pipeline. #### Classification Store Batch Assign multiple classification store attributes with one mapping. For this to work, the transformation result has to be an array with `-` as keys, and values as array values. ![Data Target Classification Store](../../../img/data_target_classification_store_batch.png) For more details and examples see [Classification Store Batch Details](./05_Classification_Store_Batch_Details.md). --- ## Mapping Configuration The mapping configuration defines what data fields from the import data should be imported where and how to the OpenDXP data object. The mapping configuration consists of multiple mapping entries. Each mapping entry provides settings for: - **Label**: Defines a name for the mapping entry. The name is used as title of the mapping entry only and has no further functionality. - **Source Attributes**: Define one or multiple fields from the import data as source for the mapping entry. Multiple fields are passed as an array to transformation pipeline and data target. The field list is based on the preview file uploaded, but also other fields can be defined by just writing the data index or field name. - **Transformation Pipeline**: The transformation pipeline transforms the data read from the source attribute(s) with operators. For details see [Transformation Pipeline](./02_Transformation_Pipeline.md). - **Data Target**: Data target definition assigns the result of the transformation pipeline to a data object field. For details see [Data Target](./03_Data_Target/README.md). --- ## Execution Configuration Depending on the configuration there are different options to start an actual import. When data source is `push`, the import process starts every time data is pushed to the corresponding endpoint. There is no further configuration possible or needed. For all the other data sources, OpenDXP needs a trigger to start the import process. Following triggers are available. #### Manual Execution Clicking on the `Manual Execution Start` button in the configuration editor manually starts the import. ![Manual Execution Start](../img/execution_manual.png) #### Cron-based Execution Besides the `Manual Execution Start` button there is also the possibility to configure a cron definition based on which the import starts on a regular base, e.g. every 10 Minutes, once a day, etc. ![Cron Definition](../img/execution_cron.png) See for example [Crontab Guru](https://crontab.guru/) for possibilities and a generator for generating cron definitions. > Make sure `datahub:data-importer:execute-cron` command is setup properly during installation. #### Command-based Execution It is also possible to imports with executing the `datahub:data-importer:prepare-import` command on the commandline. For further details on import execution also see [Import Execution Details](../04_Import_Execution_Details.md). --- ## Configuration(Configuration) This section gives your details about all the configuration options of an import. Also, have a look at [Import Execution Details](../04_Import_Execution_Details.md) to understand how imports are actually executed based on the import configuration. ### Configuration Chapters - [Data Sources](./01_Data_Sources.md) - [File Formats](./02_File_Formats.md) - [Import Preview](./03_Import_Preview.md) - [Resolver Settings](./04_Resolver_Settings.md) - [Processing Settings](./05_Processing_Settings.md) - [Mapping Configuration](./06_Mapping_Configuration/README.md) - [Execution Configuration](./07_Execution_Configuration.md) --- ## Update Notes ### 1.1.0 * [ENHANCEMENT] The installer creates the table of the import queue. Before, the queue created it on its first use * [BUGFIX] The operator `StaticText` appends its text to the value `0` as well. It treated `0` as an empty value * [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` * [CHORE] Require `open-dxp/opendxp` ^1.5 ### Migration from `pimcore/data-importer-bundle` to `open-dxp/data-importer-bundle` * Renamed composer package to `open-dxp/data-importer-bundle` * Renamed top-level PHP namespace to `OpenDxp\Bundle\DataImporterBundle` * Renamed top-level config node to `opendxp_data_importer` --- ## Import Execution Details Every import execution consists of two major parts 1) Preparation 2) Processing #### 1) Preparation Import preparation loads import source from configured data source, interprets the file based on the file format settings and splits import source into single data rows. These data rows are added to a queue to be processed during import processing. Preparation starts when 'import is starte', that means ... - when clicking manual execution in `Execution` tab of import configuration UI. - based on cron definition for import when `datahub:data-importer:execute-cron` command is executed. Every command execution calls preparation of all import configuration, that are or were due since the last command execution. - when `datahub:data-importer:prepare-import` is executed for a certain import configuration. - when data is pushed to the corresponding endpoint via http when `push` data source is configured. For starting imports see also [Execution Configuration](./03_Configuration/07_Execution_Configuration.md). Steps to be executed while preparation are: - Loading data from data source. - Interpret source data, spilt into data rows and create queue items. - If activated: check if existing elements in OpenDXP need to be cleaned up and create corresponding cleanup queue items. Preparation is executed only when the queue for corresponding import configuration is empty to prevent race conditions during import. #### 2) Processing There are two types of processing - sequential and parallel - which are configured in the import configuration. Sequential imports process the queue items one by one in the order they were added. This might be necessary when data elements depend on each other, e.g. when building up hierarchies etc. Parallel imports process the queue items in a parallelized way. This speed things up, but queue items will not be processed in their exact order. For executing processing of sequential and parallel queue items, two commands (`datahub:data-importer:process-queue-sequential` and `datahub:data-importer:process-queue-parallel`) are available or processing can be done via the symfony messenger. The actual processing is the same for both types and consists of following steps for import jobs: - Look for existing data element based on loading strategy or create new data element. - Update location of data element based on location update strategy. - Update published state of element based on publish strategy. - Process mappings and transformation pipelines for each mapping. - Assign transformation result to data element based on data target definition. - Assign userModification to data element if possible. Cleanup jobs are simpler and consist of following steps: - Look for existing data element based on loading strategy. - Cleanup element (unpublish or delete) based on cleanup strategy. To learn about all different configuration options and strategies in detail, see the [Configuration Docs](./03_Configuration/README.md). --- ## Import Progress and Logging ### Import Progress The execution tab of the import configuration shows current status and progress information of an import. It shows, if there are queue items currently processed, the progress of the current processing, and it also allows to cancel the current import run (and remove all queue items). ### Logging The importer logs overview information into OpenDXP application logger and detailed debugging information into standard OpenDXP/symfony loggers. The Import Logs tab of the importer configuration shows a prefiltered list of the application logger containing only entries belonging to the current import configuration. The application logger contains ... - information about started imports. - information about each imported element including the original imported data as linked file object. - archived original import files if activated. - information about any problems and errors happened. --- ## Extend via Custom Strategies The bundle architecture easily allows extension and customization of many parts of the importing process. Following strategies and configuration options can be extended all following the same schema: - Data Sources - File Formats - Resolver Loading Strategies - Element Location Strategies - Element Publishing Strategies - Cleanup Strategies - Transformation Pipeline Operators - Data Targets #### Extending Schema Extending one of the listed strategies and configuration options needs following steps. Also, have a look at the current implementations to see how things are working. ##### 1) PHP Implementation PHP implementations always need to implement an interface (e.g. `DataLoaderInterface` for data sources). Sometimes there is also an abstract base class, that already implements certain functionality. Try to use them if possible (e.g. `AbstractInterpreter` for FileFormats). It is of course also possible to extend existing implementations. ##### 2) Registering implementation as symfony service The php implementation needs to be registered as symfony service and tagged accordingly. Tag `name` defines the extension point (e.g. `opendxp.datahub.data_importer.loader` for data sources) and `type` defines the actual type of the extension. It must be unique and is also the link to values in the configuration file and the JavaScript implementation. ```yml OpenDxp\Bundle\DataImporterBundle\DataSource\Loader\HttpLoader: tags: - { name: "opendxp.datahub.data_importer.loader", type: "http" } ``` ##### 3) JavaScript Implementation Create a JavaScript class which meets following requirements: - Located in a certain namespace depending on the extension point (e.g. `opendxp.plugin.opendxpDataImporterBundle.configuration.components.loader.*` for data sources). - Extend the `opendxp.plugin.opendxpDataImporterBundle.configuration.components.abstractOptionType` class. - Define a `type` attribute that matches the `type` of the service definition, e.g. `type: 'http'` - Implement a function `buildSettingsForm` that creates and returns a form with all necessary setting field for the exension. --- ## Events(Extending) Another option to customize import behavior is listening for events. The bundle fires following events during the - `OpenDxp\Bundle\DataImporterBundle\Event\DataObject\PreSaveEvent`: Fired just before an imported data object will be saved - `OpenDxp\Bundle\DataImporterBundle\Event\DataObject\PostSaveEvent`: Fired just after an imported data object is saved More events to come when needed (just provide PRs ;-) . --- ## Extending(Extending) The bundle architecture provides several extension possibilities for developers to customize the behaviour. Beside standard symfony extension and customization possibilities, there are two more specific options for extending: - [Extend via Custom Strategies](./01_Extend_Custom_Strategies.md) - [Events](./03_Events.md) --- ## Troubleshooting / FAQ #### 1) Status in the Execution isn´t progressing Please be aware that you either need to activate the symfony messenger based or the command based processing for the queue. See [Import Execution Details](04_Import_Execution_Details.md) for details. ![Execution Status](./img/faq_execution_status.png) #### 2) "ERROR: The command is already running." while running the process queue command Sometimes it can happen that one of the worker processes terminates unexpectedly. If you try to run the process queue command again, you may get a "The command is already running." error message. If that is the case, please check the "lock_keys" table. The key column contains the (SHA256) hashed representation of the command (e.g. datahub:data-importer:process-queue-sequential). Delete the corresponding key and try to run the command again. --- ## Changelog(Data-importer) ### 1.1.1 - [SECURITY] [OPENDXP-SA-2026-018] Every action of the import configuration checks the data hub permission. A preview with a configuration from the request needs the update permission for the stored configuration - [CHORE] Check dependencies, code and commits for security issues ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [CHORE] Update branding names [#3](https://github.com/open-dxp/data-importer-bundle/pull/3) - [CHORE] Use requird attribute instead of annotation [#6](https://github.com/open-dxp/data-importer-bundle/pull/6) - [ENHANCEMENT] Add php 8.5 support [#5](https://github.com/open-dxp/data-importer-bundle/pull/5) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix workflows [#1](https://github.com/open-dxp/data-importer-bundle/pull/1) - [CHORE] Update cs-fixer config [#2](https://github.com/open-dxp/data-importer-bundle/pull/2) --- ## Data Importer Bundle *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP DataImporter Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** This extension adds a comprehensive import functionality to OpenDXP Datahub. It allows importing data from external sources and adjusting it to OpenDXP Data Objects based on a configured mapping without writing any code. ### Features in a Nutshell - Multiple imports configuration directly in Datahub. - Data import from various data sources. - Supported File Formats: `csv`, `xlsx`, `json`, `xml`. - Strategies configuration for: - loading existing elements for updating data. - defining location for newly imported data. - publishing data. - cleanup of existing data. - Mappings definition for adjusting data to OpenDXP Data Objects with: - simple transformations. - preview of imported data. - Imports execution directly in OpenDXP Datahub or on a regular base via cron definitions. - Import status updates and extensive logging information. ### Documentation Overview - [Installation](./doc/01_Installation.md) - [Configuration](./doc/03_Configuration/README.md) - [Import Execution Details](./doc/04_Import_Execution_Details.md) - [Import Progress and Logging](./doc/05_Import_Progress_and_Logging.md) - [Extending](./doc/06_Extending/README.md) - [Troubleshooting/FAQ](./doc/06_Troubleshooting_FAQ.md) ### Further Information On other OpenDXP Datahub adapters and export solutions: - [Datahub (GraphQL API)](https://docs.opendxp.io/docs/core-bundles/data-hub/Installation_and_Upgrade/) *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore data-importer (685c7c1 / v1.10.2)](https://github.com/pimcore/data-importer/tree/685c7c1e29b2c59c9883036fcc964dd5fa9bc12a), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Architecture Overview The following architecture overview shows available framework components. The component configuration takes place in the `opendxp_ecommerce_framework` configuration node and a factory is responsible for resolving of the implementations. For each component a custom implementation can be configured and used. ![bigpicture](img/ecommerce-architecture.png) ## Separation of Concerns We try to separate different functionality and encapsulate them as good as possible in the different components. Following list should state the basic ideas and represent a guideline for future extensions: ### Index Service The Index Service is responsible for all aspects concerning indexing products and providing an API to access product data from the index. These aspects contain among other things: * Defining which attributes should be indexed. * Implementations for different search backends (e.g. mysql, elasticsearch, fact finder, findologic). * *Product Lists* as the API to access the product data stored in the search index. *Product Lists* can be used by controllers to display product listings. ### Filter Service The Filter Service is responsible for all aspects concerning filtering products and setting up a filtered navigation. It is tightly coupled with the *Product Lists* of the Index Service, provides the developer a simple API for building a layered navigation and takes care of query generation, counting results and stuff. ### Availability System The *Availability System* is responsible for all aspects concerning product availability. Here the logic for calculating availabilities, calling external availability services, etc. is encapsulated. Each product has an *Availability System* assigned and when it comes to getting the availability of a product, this should be delegated to the *Availability System* of the product. ### Price System and Taxes Like *Availability Systems*, there are *Price Systems* which are responsible for all aspects of getting product prices. Here the logic of calculating the product prices should be encapsulated. Each product has a *Price System* and when it comes to getting the price of a product, this should be delegated to the *Price System* of the product. Also *Tax Management* is located in this component. ### Pricing Manager In addition to the *Price System*, there is the Pricing Manager which is responsible for all aspects concerning modification of prices for marketing purposes. Therefore pricing rules (e.g. certain products, certain time frames, ...) build conditions which need to be valid that certain pricing actions (e.g. product price discount, free shipping, ...) are executed. ### Voucher System The Voucher System is responsible for all aspects concerning vouchers for customers. These aspects contain among other things: * Voucher Services * Voucher Tokens * Voucher Statistics * Modification of product prices based on vouchers which is done with the help of the Pricing Manager. ### Cart Manager The Cart Manager is responsible for all aspects concerning carts. These aspects contain among other things: * Different cart implementations * CRUD-Operations on carts * Price calculations for carts * Price modifications for carts (like shipping costs, etc.) ### Checkout Manager The Checkout Manager is responsible for all aspects concerning checkout process and an one-stop API for getting through the checkout process. The Checkout Manager always works with a cart and at certain points in the checkout process it delegates to other components to convert the cart to an order object (Order Manager), start payment operations (Commit Order Processor and Payment Manager) and commits the order (Commit Order Processor). #### Commit Order Processor The Commit Order Processor is part of the Checkout Manager namespace and is responsible for all aspects concerning committing and order. These aspects contain among other things: * Handle payment response * commit order payment * commit order and send order to other backend systems (e.g. erp system) In contrast to the Checkout Manager, the Commit Order Processor does not work with carts anymore and can be initialized without a cart. Therefore it also can be used to commit orders in combination with server side payment notifications when no cart is available anymore. ### Payment Manager The Payment Manager is responsible for all aspects concerning payment. The main aspect is the implementation of different Payment Providers to integrate them into the framework. ### Order Manager The Order Manager is responsible for all aspects of working with orders except committing them (which is the responsibility of the Commit Order Processor). These aspects contain among other things: * Creating orders based on carts * Order Storage * Loading orders * Loading order lists and filter them (Order List) * Working with orders after order commit (Order Agent) --- ## Migrating to OpenDXP(Installation) ### Migrating from `pimcore/ecommerce-framework-bundle` to `open-dxp/ecommerce-framework-bundle` * Moved Bundle to `OpenDxp\Bundle\EcommerceFrameworkBundle\` namespace * Renamed top-level config node to `opendxp_ecommerce_framework` --- ## Installation and First Configuration This section describes the installation of the E-Commerce Framework and the first steps of configuration. ### Installation #### Minimum Requirements * OpenDXP >= 1.5 #### Install Install bundle via composer: ```bash composer require open-dxp/ecommerce-framework-bundle ``` Enable bundle via console or extensions manager: ```bash php bin/console opendxp:bundle:install OpenDxpEcommerceFrameworkBundle ``` Check if the bundle has been installed: ```bash php bin/console opendxp:bundle:list +---------------------------------+---------+-----------+----+-----+-----+ | Bundle | Enabled | Installed | I? | UI? | UP? | +---------------------------------+---------+-----------+----+-----+-----+ | OpenDxpEcommerceFrameworkBundle | ✔ | ✔ | ❌ | ✔ | ❌ | +---------------------------------+---------+-----------+----+-----+-----+ ``` The installer does following tasks: - Install several field collections. - Install several object classes. - Create additional tables for carts, pricing rules, vouchers, etc. - Add additional permissions. - Install the Application Logger, Personalization and Google Marketing bundles if they are not installed yet. A field collection, class, table or permission that already exists is skipped. #### Upgrade After updating the bundle, run its migrations: ```bash php bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\EcommerceFrameworkBundle\Migrations' ``` After this installation routine, additional configurations have to be made - most important Product and ProductCategory. Please see [Configuration](../04_Configuration/README.md) for further information on available options. ### Configure Product and Product Category Class The E-Commerce Framework installation does not create classes for products and product categories. That is because the framework does not limit you on specific classes or class structures. Literally every class can act as a product or product category class, and it is also possible to have several product classes (if necessary). The only requirement is, that the classes have to be 'prepared' for being products or product categories. #### Product There are two ways of preparing a OpenDxp class for product-usage in the E-Commerce Framework 1. The OpenDxp class needs to extend the abstract class `\OpenDxp\Bundle\EcommerceFrameworkBundle\Model\AbstractProduct` * This is useful, when both product index and checkout functionality are based on the E-Commerce Framework. 2. Make sure that the OpenDxp class implements either `\OpenDxp\Bundle\EcommerceFrameworkBundle\Model\IndexableInterface` or `\OpenDxp\Bundle\EcommerceFrameworkBundle\Model\CheckoutableInterface` - or both, depending on the use case it is used for. * This is useful, when e.g. only checkout functionality is based on the E-Commerce Framework, but not the product presentation. * The interfaces define methods that are needed for the two use cases and need to be implemented. > For the abstract class use the parent class functionality of OpenDxp. For implementing the interfaces use either the parent class functionality or the overriding models functionality of OpenDxp (see also [Overriding Models](https://github.com/open-dxp/opendxp/tree/1.x/doc/20_Extending_OpenDxp/03_Overriding_Models.md)). > If using the abstract class, also have a look at its [implementation](https://github.com/open-dxp/ecommerce-framework-bundle/tree/1.x/src/Model/AbstractProduct.php). You might need to override a few methods that cannot be implemented by the abstract class and throw an exception depending on the use case you are using it. #### Product Category When a product category class is used, this class needs to extend the abstract class `\OpenDxp\Bundle\EcommerceFrameworkBundle\Model\AbstractCategory`. > For product categories only one OpenDxp class should be used. For products, several OpenDxp classes can be used. Possibly the index update scripts need to be adapted. ### Configuring OpenDxp Ecommerce Framework The E-Commerce Framework is split up into multiple components which can be configured individually. For further reading please see: - [Configuration](../04_Configuration/README.md) describes configuration features valid for the whole framework configuration - [OpenDxpEcommerceFrameworkBundle Configuration Reference](../04_Configuration/01_OpenDxpEcommerceFrameworkBundle_Configuration_Reference.md) contains a reference of the whole configuration tree Please see the following sections for a description of each component and a configuration reference describing the configuration entries relevant to the component: - [Cart Manager](../11_Cart_Manager.md) - [Price Systems](../09_Working_with_Prices/README.md) - [Availability Systems](../10_Working_with_Availabilities.md) - [Checkout Manager and Checkout Steps](../13_Checkout_Manager/README.md) - [Payment Providers](../15_Payment/README.md) - [Index Service and which attributes should be in the Product Index](../05_Index_Service/README.md) - [Pricing Manager](../09_Working_with_Prices/05_Pricing_Rules.md) - ... For detailed information see comments within the configuration file. Depending on your use case, you might not need all components configured in the configuration file. > During development, you will return to the configuration and adjust the settings multiple times. --- ## OpenDxpEcommerceFrameworkBundle Configuration Reference The following is the generated reference for the `opendxp_ecommerce_framework` configuration tree. This reference can be generated by issuing the following command: $ bin/console config:dump-reference opendxp_ecommerce_framework > **IMPORTANT** This is just a reference for the configuration tree, you need to adjust it to replace the required configurations by setting up the respective module. ```yaml # Default configuration for extension with alias: "opendxp_ecommerce_framework" opendxp_ecommerce_framework: # Default scale used for Decimal objects decimal_scale: 4 # Configuration of OpenDxp backend menu entries opendxp: menu: # Enabling/Disabling Pricing Rules menu entry. User specific settings can be done via permissions. pricing_rules: enabled: true # Configuring order list menu - enabling/disabling and defining route of order list to inject custom implementations of order backend. order_list: enabled: true route: opendxp_ecommerce_backend_admin-order_list path: null # Configuration of e-commerce framework factory factory: # Service Id of factory implementation factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\Factory # If true the factory will not fall back to the default tenant if a tenant is passed but not existing strict_tenants: false # Configuration of environment environment: environment_id: OpenDxp\Bundle\EcommerceFrameworkBundle\SessionEnvironment options: [] # Settings for cart manager cart_manager: # Configuration per tenant. If a _defaults key is set, it will be merged into every tenant. It needs to be set in every file. A tenant named "default" is mandatory. tenants: # Examples: _defaults: cart: factory_id: CartFactory default: cart: factory_options: cart_class_name: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\Cart price_calculator: modificators: shipping: class: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartPriceModificator\Shipping options: charge: 5.90 noShipping: price_calculator: factory_id: PriceCalculatorFactory modificators: [] # Prototype name: # Service id of cart service cart_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\MultiCartManager # Configuration for carts cart: # Service id of cart factory and configuration array factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartFactory factory_options: # Defaults: cart_class_name: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\Cart guest_cart_class_name: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\SessionCart price_calculator: factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartPriceCalculatorFactory factory_options: # 'class' defines the class name of the price calculator, which the factory instantiates. # If you wish to replace or extend the price calculation routine shipped with the e-commerce # framework provide your custom class name here. class: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartPriceCalculator # List price modificators for cart, e.g. for shipping-cost, special discounts, etc. Key is name of modificator. modificators: # Prototype name: class: ~ # Required options: [] # Configuration of Order Manager order_manager: # Configuration per tenant. If a _defaults key is set, it will be merged into every tenant. A tenant named "default" is mandatory. tenants: # Prototype name: # Service id for order manager implementation order_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\V7\OrderManager # Options for order manager options: # OpenDxp object class for orders order_class: \OpenDxp\Model\DataObject\OnlineShopOrder # OpenDxp object class for order items order_item_class: \OpenDxp\Model\DataObject\OnlineShopOrderItem # Class for order listing list_class: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\Listing # Class for order item listing list_item_class: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\Listing\Item # Default parent folder for new orders # parent_order_folder: /order/%%Y/%%m/%%d # deprecated and discouraged order_parent_path: /order/*Y*/*M*/*D* order_agent: # Service id for order agent factory factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\AgentFactory factory_options: [] # Configuration of Pricing Manager pricing_manager: # Condition mapping from name to used class conditions: # Prototype name: ~ # Action mapping from name to used class actions: # Prototype name: ~ # Configuration per tenant. If a _defaults key is set, it will be merged into every tenant. A tenant named "default" is mandatory. tenants: default: ~ # Prototype name: enabled: true # Service id of pricing manager pricing_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\PricingManager # Options for pricing manager pricing_manager_options: rule_class: OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\Rule price_info_class: OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\PriceInfo environment_class: OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\Environment # Configuration of price systems - key is name of price system. price_systems: # Prototype name: id: ~ # Required # Configuration of availability systems - key is name of price system. availability_systems: # Prototype name: id: ~ # Required # Configuration of checkout manager checkout_manager: # Configuration per tenant. If a _defaults key is set, it will be merged into every tenant. A tenant named "default" is mandatory. tenants: # Prototype name: factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\CheckoutManagerFactory factory_options: [] # Define payment provider which should be used for payment. Payment providers are defined in payment_manager section. payment: provider: null # Define used commit order processor commit_order_processor: id: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CommitOrderProcessor options: [] # Define different checkout steps which need to be committed before commit of order is possible steps: # Prototype name: class: ~ # Required options: [] # Configuration of payment manager and payment providers payment_manager: payment_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\PaymentManager # Configuration of payment providers, key is name of provider. providers: # Prototype name: name: ~ # Service id of payment provider implementation provider_id: ~ # Required # Currently active profile profile: ~ # Required # Available profiles with options profiles: # Prototype name: # Prototype name: ~ # Configuration of index service index_service: index_service_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\IndexService default_tenant: default # Configure assortment tenants - at least one tenant has to be configured. If a _defaults key is set, it will be merged into every tenant. tenants: # Prototype name: enabled: true # Service id of config implementation config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\DefaultMysql config_options: [] # Worker id of worker implementation. Can be omitted, then default worker id of configured config is used. worker_id: ~ # Placeholder values in this tenant attributes definition (locale: "%%locale%%") will be replaced by the given placeholder value (eg. "de_AT") placeholders: '%%locale%%': 'de_AT' # Add columns for general fulltext search index of product list - they must be part of the column configuration below search_attributes: [] # Attributes definition for product index - key is name of attribute attributes: # Prototype name: name: ~ # Required # Defines object attribute field name, can be omitted if the same like name of index attribute field_name: null # Type of index attribute (database column or elasticsearch data type) type: null # Locale for localized fields, can be omitted if not necessary locale: null # Defines filter group for filter definition in filter service filter_group: null options: [] # Service id of getter for this field getter_id: null getter_options: [] # Service id of interpreter for this field interpreter_id: null interpreter_options: [] # Hides field in field list selection data type of filter service - default to false hide_in_fieldlist_datatype: false # Configuration of filter service filter_service: # Configuration per tenant. If a _defaults key is set, it will be merged into every tenant. tenants: # Prototype name: enabled: true service_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterService # Assign backend implementations and views to filter type field collections filter_types: # Prototype name: # Service id for filter type implementation filter_type_id: ~ # Required # Default template for filter, can be overwritten in filter definition template: ~ # Required options: [] # Configuration of voucher service voucher_service: # Service id of voucher service implementation voucher_service_id: OpenDxp\Bundle\EcommerceFrameworkBundle\VoucherService\DefaultService voucher_service_options: # Reservations older than x MINUTES get removed by maintenance task reservation_minutes_threshold: 5 # Statistics older than x DAYS get removed by maintenance task statistics_days_threshold: 30 # Configuration of token managers token_managers: # Service id of token manager factory factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\VoucherService\TokenManager\TokenManagerFactory # Mapping for token manager implementations mapping: # Prototype name: ~ # Configuration of offer tool offer_tool: # Service id for offer tool service service_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OfferTool\DefaultService order_storage: # OpenDxp object class for offers offer_class: OpenDxp\Model\DataObject\OfferToolOffer # OpenDxp object class for offer items offer_item_class: OpenDxp\Model\DataObject\OfferToolOfferItem # default path for new offers offer_parent_path: /offertool/offers/*Y*/*M* #parent_folder_path: /offertool/offers/%%Y/%%m # deprecated and discouraged, use offer_parent_path instead # Configuration of Tracking Manager tracking_manager: # Service id of tracking manager tracking_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\TrackingManager # Enable/Disable trackers and configure them trackers: # Prototype enhanced_ecommerce: # Service id for tracker id: OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\Tracker\Analytics\EnhancedEcommerce enabled: false # Service id for item builder for tracker item_builder_id: OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\TrackingItemBuilder # List of assortment and checkout tenants where this tracker should be activated for. tenants: # Add list of assortment tenants where the tracker should be activated for. Empty array means activated for all tenants. assortment: [] # Add list of checkout tenants where the tracker should be activated for. Empty array means activated for all tenants. checkout: [] ``` --- ## Configuration(3) The E-Commerce Framework is implemented as semantic bundle configuration which means that you can configure the framework in any of the loaded config files (e.g. `/config/config.yaml` or `*Bundle/Resources/config/opendxp/config.yaml`) by adding configuration to the `opendxp_ecommerce_framework` node. The configuration is built upon the [Symfony Config Component](https://symfony.com/doc/current/components/config.html) and defines a well-known configuration tree which is validated against a defined configuration structure. While configuring the framework you'll get instant feedback on configuration errors. As OpenDxp defines a standard configuration for the E-Commerce Framework, your custom configuration will be merged into the standard configuration. You can dump the final (merged, validated and normalized) configuration at any time with the following command: $ bin/console debug:config opendxp_ecommerce_framework A reference of available configuration entries can be found on [OpenDxpEcommerceFrameworkBundle Configuration Reference](./01_OpenDxpEcommerceFrameworkBundle_Configuration_Reference.md). As the E-Commerce Framework makes heavy use of Symfony service definitions and you'll need to reference IDs of custom services in the configuration it's advised that you are comfortable to work with [Symfony's Service Container](https://symfony.com/doc/current/service_container.html#creating-configuring-services-in-the-container]). ### Tenant support and `_defaults` sections As certain components of the E-Commerce Framework support different tenants, OpenDxp adds a way to specify settings which are common to all tenants in a special tenant named `_defaults`. If such a tenant exists, its values will be merged into all other tenants and the `_defaults` tenant will be removed afterwards. The logic described below applies to all components supporting tenants. As example, a simple `cart_manager` configuration section which defines a `default` and a `noShipping` tenant: ```yaml opendxp_ecommerce_framework: cart_manager: tenants: # _defaults will be automatically merged into every tenant and removed afterwards # the result will be a default and a noShipping _defaults: cart: factory_id: CartFactoryId price_calculator: factory_id: PriceCalculatorFactoryId factory_options: foo: bar default: price_calculator: factory_options: baz: 1234 noShipping: price_calculator: factory_options: baz: 4321 ``` In addition to the `_defaults` tenant, you can define additional tenants starting with `_defaults` to make use of [YAML inheritance](https://learnxinyminutes.com/docs/yaml/). ```yaml opendxp_ecommerce_framework: cart_manager: tenants: _defaults_foo: price_calculator: factory_options: &defaults_foo_options # define an anchor class: MyCommonCalculatorClass default: price_calculator: factory_options: <<: *defaults_foo_options # import anchor anotherOne: price_calculator: factory_options: <<: *defaults_foo_options # import anchor ``` Of course you can still use the PHP config file format by importing a PHP config file from your `config.yaml` to be completely free how to merge common configuration entries. ### Service IDs and tenant specifics When configuring tenant specific services, there are multiple configuration entries demanding a service ID as configuration value. This means, the system expects the configured value to be available as service definition on the container. You can read through the service definitions defined in [OpenDxpEcommerceFrameworkBundle](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Resources/config) to get an insight of default e-commerce services. As an example let's take a look at a price system configuration: ```yaml # when loading the "default" price system, use a service named "App\Ecommerce\PriceSystem\CustomPriceSystem" opendxp_ecommerce_framework: price_systems: default: # price system defined and configured as container service id: App\Ecommerce\PriceSystem\CustomPriceSystem ``` The configuration above expects something like this configured as service: ```yaml services: App\Ecommerce\PriceSystem\CustomPriceSystem: arguments: - 'foo' ``` The "default" price system is just an alias to your existing service and when loading that price system, your service will be directly loaded. Getting the "default" price system from the ecommerce framework factory will result in the same instance as getting `App\Ecommerce\PriceSystem\CustomPriceSystem` directly from the container. #### Service IDs in tenant context Now let's take a look at another example handling tenants: ```yaml opendxp_ecommerce_framework: order_manager: tenants: default: order_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\OrderManager options: # parent_order_folder: /orders/default/%%Y/%%m/%%d # deprecated and discouraged order_parent_path: /orders/default/*Y*/*M*/*D* b2b: order_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\OrderManager options: # parent_order_folder: /orders/b2b/%%Y/%%m/%%d # deprecated and discouraged order_parent_path: /orders/b2b/*Y*/*M*/*D* ``` As you can see we define 2 tenants `default` and `b2b` with the same order manager ID but with different options for each tenant. In this case it's not possible to just alias the default or the b2b order manager to the given service ID as we need multiple order manager instances based on this service definition. In this case the framework takes the configured service ID as *template* to configure 2 independent child services by utilizing the configured service id as [parent service](https://symfony.com/doc/current/service_container/parent_services.html). This means, that when you request the `OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\OrderManager` service from the container, it would be neither the default nor the b2b tenant. In fact, getting that service directly wouldn't work anyways as it is missing dependencies. If you take a look at the [service definition](https://github.com/open-dxp/ecommerce-framework-bundle/tree/1.x/src/Resources/config/order_manager.yaml) you can see that the definition is missing the `OrderAgentFactoryInterface` argument which will be resolved and set for each tenant specific order manager. In short, when configuring multiple tenant specific service to the same service id the framework will: 1) create a new child definition from the configured service 2) set tenant specific arguments (as the options above) to the tenant specific child service 3) register the child service under a another ID which can be resolved by the factory To keep your services clean and give the service container more optimization (and performance) possibilities you should define your parent services as `private` (see order manager definition in the linked config above) as this will result in the parent definition being removed from the compiled container. This child definition pattern applies to nearly all service IDs configured inside tenants with the exception of reusable services (e.g. getters and interpreters in the product index configuration) which do not have an internal state and therefore can be reused throughout multiple tenants. --- ## Assortment Tenant Configuration The E-Commerce Framework provides a two level Assortment Tenant system for the Product Index: 1. **Assortment Tenant**: The first level of tenants are heavy-weight tenants. They allow multiple shop instances within one system. The shop instances are completely independent from each other and can contain complete different products, index attributes and even use different product index implementations. 2. **Assortment Subtenant**: The second level of tenants are light-weight tenants, which exist within a shop instance. Light-weight tenants use the same Product Index with the same attributes as their parent shop, but can contain a subset of the products. So they are meant to be used for implementing different product assortments within one shop. One system can have multiple tenants (heavy- and light-weight). But too many tenants can have bad effects on the performance of saving products, since all *Product Indices* need to be updated on every save. By default the system always uses one heavy-weight tenant (which is `DefaultMysql`), but the default tenant can be disabled. ### Assortment Tenants For setting up an Assortment Tenant, following steps are necessary: - **Implementation of a Tenant Config:** The Tenant Config class is the central configuration of an assortment tenant, defines which products are available for the tenant and provides the connection to the used *Product Index* implementation. It needs to implement [`OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\ConfigInterface`](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/IndexService/Config/ConfigInterface.php). For detailed information see in-source documentation of the interface. Following implementations are provided by the framework and may be extended: - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\DefaultMysql`: Provides a simple mysql implementation of the product index. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\ConfigOptimizedMysql`: Provides an optimized mysql implementation of the product index. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\ElasticSearch`: Provides a default [elasticsearch](https://www.elastic.co/) implementation of the product index. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\DefaultFindologic`: Provides a default [findologic](https://www.findologic.com/) implementation of the product index. - **Configuring Assortment Tenants within configuration:** Each tenant has to be configured within the `index_service` configuration by defining the tenant config class and index attributes. Depending on the *Product Index* implementation, additional configuration may be necessary. - **Declare the service:** You need to declare the service as well so the class can be used. On your service configuration or for instance at the top of the ecommerce configuration file: ```yaml services: MyBundle\Service\MySubtenantConfig: calls: - [setAttributeFactory, ['@OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\AttributeFactory']] ``` #### Setting current Assortment Tenant for Frontend The [E-Commerce Framework Environment](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/EnvironmentInterface.php#L22-L22) provides following methods to set the current Assortment Tenant when working with *Product Lists* in Code: ```php getEnvironment(); $environment->setCurrentAssortmentTenant("elasticsearch"); //getting suitable product list $productlist = $factory->getIndexService()->getProductListForCurrentTenant(); //doing stuff with product list ``` ### Assortment Subtenants Subtenants are light-weight tenants, which share the same Product Index with the same attributes as their parent assortment tenant. #### Implementing an Assortment Subtenant for MySQL The mapping which product is assigned to with subtenant is done with an additional mapping table. The necessary joins and conditions are implemented within additional methods within [`OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\MysqlConfigInterface`](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/IndexService/Config/MysqlConfigInterface.php): ```php /** * return table name of product index tenant relations for subtenants * * @return string */ public function getTenantRelationTablename(); /** * return join statement in case of subtenants * * @return string */ public function getJoins(); /** * returns additional condition in case of subtenants * * @return string */ public function getCondition(); ``` In order to populate the additional mapping data, also following methods have to be implemented: ```php /** * in case of subtenants returns a data structure containing all sub tenants * * @param IndexableInterface $object * @param int|null $subObjectId * * @return mixed $subTenantData */ public function prepareSubTenantEntries(IndexableInterface $object, $subObjectId = null); /** * populates index for tenant relations based on given data * * @param mixed $objectId * @param mixed $subTenantData * @param mixed $subObjectId * * @return void */ public function updateSubTenantEntries($objectId, $subTenantData, $subObjectId = null); ``` For an complete example have a look at the [sample implementation](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/IndexService/Config/DefaultMysqlSubTenantConfig.php). #### Implementing an Assortment Subtenant for Elasticsearch In order to populate the additional mapping data, the following method has to be implemented: ```php /** * in case of subtenants returns a data structure containing all sub tenants * * @param IndexableInterface $object * @param int|null $subObjectId * * @return array $subTenantData */ public function prepareSubTenantEntries(IndexableInterface $object, $subObjectId = null); ``` For an complete example have a look at the [sample implementation](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/IndexService/Config/DefaultElasticSearchSubTenantConfig.php). --- > Note: This is currently only implemented for MySQL and elasticsearch based product index implementations. --- ## Data Architecture and Indexing Process Depending on the *Product Index* implementation, there are two different *Product Index* data architectures and ways for indexing: Simple Mysql Architecture and Optimized Architecture. For indexing itself the provided OpenDxp console commands can be used. ### Simple Mysql Architecture - OpenDxp object data is transferred directly to the Product Index. - After every update of a OpenDxp object, the changes are directly written into the Product Index. - Only used for `\OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\DefaultMysql` > Updates of dependent objects (like child objects, variants that inherit data, related objects) are not transferred > into the index automatically. ![productindex-simple](../../img/productindex-simple.png) #### Console Commands for Simple Mysql Architecture - For manually updating the whole index use following command: ```bash php bin/console ecommerce:indexservice:bootstrap --update-index ``` - If you need to create or update the index structures you can use: ```bash php bin/console ecommerce:indexservice:bootstrap --create-or-update-index-structure ``` - By default, OpenDxp assumes that the product class is `OpenDxp\Model\DataObject\Product`. If you have a different product class name, please use the `--object-list-class` param and provide the listing class name that should be used. > For further details (e.g. only updating certain product types, apply list conditions) see `--help` section of the >`ecommerce:indexservice:bootstrap` command. ### Optimized Architecture - In the optimized architecture, object data is transferred **not** directly to the *Product Index*. - In this case a so called store table is between the OpenDxp objects and the *Product Index*. This store table enables to ... - ... update the *Product Index* only if index relevant data has changed. Therefore the load on the index itself is reduced and unnecessary write operations are prevented. - ... update the *Product Index* asynchronously and therefore update also dependent elements (children, variants, ...) of an updated OpenDxp object without impact on save performance. - ... rebuilding the whole *Product Index* out of the store table much faster since no direct interaction with OpenDxp objects is needed. - After every update of a OpenDxp object, the changes are written into the store table and all child objects of the updated object are added to the so called preparation queue (see later). As a consequence a periodic full update should not be necessary any more. - Used for optimized mysql, elasticsearch, ... ![productindex-optimized](../../img/productindex-optimized.png) #### Console Commands for Optimized Architecture For updating data in index following commands are available. - For process the preparation queue and update OpenDxp objects to the index store table, use following command. **This command should be executed periodically (e.g. all 10 minutes).** ```bash php bin/console ecommerce:indexservice:process-preparation-queue ``` - To update the Product Index based on changes stored in the store table use the following command. **This command should be executed periodically (e.g. all 10 minutes).** ```bash php bin/console ecommerce:indexservice:process-update-queue ``` - For manually update all OpenDxp objects in the index store use following command. As stated before, this should only be necessary for an initial fill-up of the index. After that, at least Product Index Store and OpenDxp objects should always be in sync. It is important to execute `ecommerce:indexservice:process-preparation-queue` and `ecommerce:indexservice:process-update-queue` periodically though. ```bash php bin/console ecommerce:indexservice:bootstrap --update-index ``` > By default, OpenDxp assumes that the product class is `OpenDxp\Model\DataObject\Product`. If you have a > different product class name, please use the `--object-list-class` param and provide the listing class name > that should be used. - Invalidate either the preparation queue or the index-update queue. This is usually **only needed during development** when the store table is out of sync. Reset the preparation queue for instance when your product model returns updated data for a field. ```bash php bin/console ecommerce:indexservice:reset-queue preparation --tenant=MyTenant php bin/console ecommerce:indexservice:reset-queue update-index --tenant=MyTenant ``` - If you need to create or update the index structures you can still use: ```bash php bin/console ecommerce:indexservice:bootstrap --create-or-update-index-structure ``` > For further details see `--help` section of the commands. #### Paralelization of Indexing All indexing commands include the [parallelization trait of webmozart](https://github.com/webmozarts/console-parallelization). Thus indexing can be parallelized very easily by adding the `--processes=X` option to the command. Be aware that depending on the command too many parallel processes might cause deadlocks on database. --- ## Configuration Configuration Following aspects need to be considered in index configuration: ### General Configuration Options In the `config_options` area general elasticsearch settings can be made - like hosts, index settings, etc. ###### `client_config` - `logging`: (deprecated, for Elasticsearch 7 only) `true`/`false` to activate logging of elasticsearch client - `indexName`: index name to be used, if not provided tenant name is used as index name ###### `index_settings` Index settings that are used when creating a new index. They are passed 1:1 as settings param to the body of the create index command. Details see also [elasticsearch Docs](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_index_management_operations.html). ##### `es_client_name` (for Elasticsearch 8 only) Elasticsearch 8 client configuration takes place via [OpenDxp Elasticsearch Client Bundle](https://github.com/open-dxp/elasticsearch-client) and has two parts. 1) Configuring an elasticsearch client in separate configuration ```yaml # Configure an elasticsearch client opendxp_elasticsearch_client: es_clients: default: hosts: ['elastic:9200'] username: 'elastic' password: 'somethingsecret' logger_channel: 'opendxp.elasticsearch' ``` 2) Define the client name to be used by an elasticsearch tenant. This will be done via the `es_client_name` configuration in the `config_options`. ###### `synonym_providers` Specify synonym providers for synonym filters defined in filter section of index settings. For details see [Synonyms](./02_Synonyms.md). ##### Sample Config ```yml opendxp_ecommerce_framework: index_service: tenants: MyEsTenant: worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\ElasticSearch\DefaultElasticSearch8 config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\ElasticSearch config_options: client_config: logging: false indexName: 'ecommerce-demo-elasticsearch' # elasticsearch client name, for Elasticsearch 8 only es_client_name: default index_settings: number_of_shards: 5 number_of_replicas: 0 max_ngram_diff: 30 analysis: analyzer: my_ngram_analyzer: tokenizer: my_ngram_tokenizer allow_list_analyzer: tokenizer: standard filter: - allow_list_filter tokenizer: my_ngram_tokenizer: type: ngram min_gram: 2 max_gram: 15 token_chars: [letter, digit] filter: allow_list_filter: type: keep keep_words: - was - WAS ``` ### Data Types for attributes The type of the data attributes needs to be set to elasticsearch data types.. ```yml opendxp_ecommerce_framework: index_service: tenants: MyEsTenant: attributes: name: locale: '%%locale%%' type: keyword ``` In addition to the `type` configuration, you also can provide custom mappings for a field. If provided, these mapping configurations are used for creating the mapping of the elasticsearch index. You can also skip the `type` and `mapping`, then ES will try to create dynamic mapping. ```yml opendxp_ecommerce_framework: index_service: tenants: MyEsTenant: attributes: name: locale: '%%locale%%' type: text options: mapping: type: text store: true index: not_analyzed fields: analyzed: type: text analyzer: german analyzed_ngram: type: text analyzer: my_ngram_analyzer ``` --- ## 02_Synonyms ### Synonyms With elasticsearch so called synonym filters can be configured to further optimize search behavior. For details see [Synonym Token Filter and following pages](https://www.elastic.co/guide/en/elasticsearch/reference/7.12/analysis-synonym-tokenfilter.html) at elasticsearch documentation. OpenDxp provides an out-of-the box integration to provide synonyms for the synonym filters of elasticsearch. ##### Synonym Providers Synonym providers are symfony services that implement the `SynonymProviderInterface`, load synonyms from a specific source and provide it for using them in elasticsearch synonym filters. Sources can be simple files, OpenDxp assets, OpenDxp data objects, database tables or what ever source is needed. OpenDxp ships with a simple `FileSynonymProvider` that can be used right away. The synonym source is a file (e.g. a OpenDxp asset) that follows the [Solr file format](https://www.elastic.co/guide/en/elasticsearch/reference/7.12/analysis-synonym-tokenfilter.html#_solr_synonyms). Besides the service configuration itself, the synonym providers need to be configured in index service configuration as follows. ```yml opendxp_ecommerce_framework: index_service: tenants: : enabled: true worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\ElasticSearch\DefaultElasticSearch8 config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\ElasticSearch config_options: synonym_providers: app_synonym_filter: # service ID of synonym provider to use provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\SynonymProvider\FileSynonymProvider # additional options for synonym provider (are applied to a child-service instance of given synonym provider options: synonymFile: '%kernel.project_dir%/public/var/assets/system/synonyms.txt' ``` ##### Matching Synonym Providers to Synonym Filters Matching between synonym providers and synonym filters in index settings takes place via name. In the sample below there the synonym provider `app_synonym_filter` provides the synonyms for the filter `app_synonym_filter`. The filter definition in the index settings can hold just an empty array (as some definition is required). During index building, index resetting or reloading of synonyms, the synonyms are loaded from synonyms provider and injected to the synonyms array of the corresponding synonyms filter. ```yml opendxp_ecommerce_framework: index_service: tenants: : enabled: true worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\ElasticSearch\DefaultElasticSearch8 config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\ElasticSearch config_options: synonym_providers: app_synonym_filter: # service ID of synonym provider to use provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\SynonymProvider\FileSynonymProvider # additional options for synonym provider (are applied to a child-service instance of given synonym provider options: synonymFile: '%kernel.project_dir%/public/var/assets/system/synonyms.txt' index_settings: analysis: filter: app_synonym_filter: # mapping between synonym_provider and filter based on name type: synonym # or synonym_graph or any other ES type synonyms: [] # provide an empy array here, for ES6 [], for ES5[""] ``` > Don't forget to also add the synonyms filter to an analysers filter array where needed - as described in [elasticsearch docs](https://www.elastic.co/guide/en/elasticsearch/reference/7.12/analysis-synonym-tokenfilter.html). ##### Updating Synonyms There are three ways of updating the synonyms in the elasticsearch index. For all applies that the synonyms are loaded from synonyms provider and injected to the synonyms array of the corresponding synonyms filter by OpenDxp. ###### Index Creation During index creation the synonyms are loaded from synonym providers and applied to index. ###### Reindex During reindex the synonyms are loaded from synonym providers and applied to index when new index is created. > This is the recommended way to update synonyms during runtime at a production system as there is no service downtime. ###### Elasticsearch sync command With the command `bin/console ecommerce:indexservice:elasticsearch-sync update-synonyms` synonyms can be updated in the current index. For that, the index has to be closed and reopened which means a short downtime of the index. --- ## Special Aspects for Elasticsearch Basically Elasticsearch worker works as described in the [optimized architecture](../README.md). Currently, Elasticsearch 8 is supported. ### Installation #### Elasticsearch 8 To work properly OpenDxp requires the Elasticsearch client, install them with: `composer require open-dxp/elasticsearch-client`. ### Index Configuration Elasticsearch provides a couple of additional configuration options for the index to utilize elasticsearch features. See [Configuration Details](01_Configuration_Details.md) for more information. ### Reindexing Mode It is possible that elasticsearch cannot update the mapping, e.g. if data types of attributes change on the fly. For this case, a reindex is necessary. If it is necessary, a native ES reindex is executed automatically during `bin/console ecommerce:indexservice:bootstrap --create-or-update-index-structure`. While reindex is executed, no updates are written to the ES index. The changes remain in store table and are transferred to index during next execution of `bin/console ecommerce:indexservice:process-update-queue` after reindex is finished. All queries that take place during reindex go to the old index. As soon the reindex is finished, the current index is switched to the newly created index and the old index is deleted. As a result, during reindex the results delivered by Product Lists can contain old data. To manually start a reindex, following command can be used: `bin/console ecommerce:indexservice:search-index-sync reindex`. :::caution The existing command `bin/console ecommerce:indexservice:search-elasticsearch-sync reindex` is deprecated and will be removed in 2.0.0. ::: ### Indexing of Classification Store Attributes With elasticsearch it is possible to index all attributes of [Classification Store](https://github.com/open-dxp/opendxp/tree/1.x/doc/05_Objects/01_Object_Classes/01_Data_Types/15_Classification_Store.md) data without defining an attribute for each single classification store key. For details see [Filter Classification Store](../../../07_Filter_Service/03_Elastic_Search/01_Filter_Classification_Store.md) in Filter Service documentation. ### Synonyms OpenDxp provides an out-of-the box integration for synonyms in elasticsearch. See [Synonyms](./02_Synonyms.md) for details. --- ## Special Aspects for Findologic Exporter Basically findologic worker works as described in the [optimized architecture](README.md). But there is an additional speciality with the export: Executing `php bin/console ecommerce:indexservice:process-update-queue` does not write the data directly to Findologic, but into an extra table `\OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\DefaultFindologic::EXPORT_TABLE_NAME` (default is `ecommerceframework_productindex_export_findologic`). Findologic then can use the endpoint `/ecommerceframework/findologic-export`, which delivers all data directly based on the export table. Valid parameters for this endpoint are: - `start`: Pagination start. - `count`: Count of delivered entries. - `shopKey`: Shop key to identify the shop. - `id`: Filter for Product-ID - `type`: Filter for type --- ## Configuration Configuration(Open_Search) Following aspects need to be considered in index configuration: ### General Configuration Options In the `config_options` area general OpenSearch settings can be made - like hosts, index settings, etc. ###### `client_config` - `indexName`: index name to be used, if not provided tenant name is used as index name ###### `index_settings` Index settings that are used when creating a new index. They are passed 1:1 as settings param to the body of the create index command. Details see also [OpenSearch Docs](https://opensearch.org/docs/latest/api-reference/index-apis/index/). ##### `opensearch_client_name` OpenSearch client configuration takes place via [OpenDxp OpenSearch Client Bundle](https://github.com/open-dxp/opensearch-client) and has two parts. 1) Configuring an OpenSearch client in separate configuration ```yaml # Configure an OpenSearch client opendxp_open_search_client: clients: default: hosts: [ 'opensearch:9200' ] username: 'admin' password: 'somethingsecret' logger_channel: 'opendxp.opensearch' ``` 2) Define the client name to be used by an OpenSearch tenant. This will be done via the `opensearch_client_name` configuration in the `config_options`. ###### `synonym_providers` Specify synonym providers for synonym filters defined in filter section of index settings. For details see [Synonyms](./02_Synonyms.md). ##### Sample Config ```yml opendxp_ecommerce_framework: index_service: tenants: MyOpenSearchTenant: worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\OpenSearch\DefaultOpensearch config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\OpenSearch config_options: client_config: indexName: 'ecommerce-demo-opensearch' opensearch_client_name: default index_settings: number_of_shards: 5 number_of_replicas: 0 max_ngram_diff: 30 analysis: analyzer: my_ngram_analyzer: tokenizer: my_ngram_tokenizer allow_list_analyzer: tokenizer: standard filter: - allow_list_filter tokenizer: my_ngram_tokenizer: type: ngram min_gram: 2 max_gram: 15 token_chars: [letter, digit] filter: allow_list_filter: type: keep keep_words: - was - WAS ``` ### Data Types for attributes The type of the data attributes needs to be set to OpenSearch data types.. ```yml opendxp_ecommerce_framework: index_service: tenants: MyOpenSearchTenant: attributes: name: locale: '%%locale%%' type: keyword ``` In addition to the `type` configuration, you also can provide custom mappings for a field. If provided, these mapping configurations are used for creating the mapping of the OpenSearch index. You can also skip the `type` and `mapping`, then OpenSearch will try to create dynamic mapping. ```yml opendxp_ecommerce_framework: index_service: tenants: MyOpenSearchTenant: attributes: name: locale: '%%locale%%' type: text options: mapping: type: text store: true index: not_analyzed fields: analyzed: type: text analyzer: german analyzed_ngram: type: text analyzer: my_ngram_analyzer ``` --- ## 02_Synonyms(Open_Search) ### Synonyms With OpenSearch so called synonym filters can be configured to further optimize search behavior. For details see [Synonym Token Filter and following pages](https://opensearch.org/docs/latest/analyzers/token-filters/index/) at OpenSearch documentation. OpenDxp provides an out-of-the box integration to provide synonyms for the synonym filters of OpenSearch. ##### Synonym Providers Synonym providers are symfony services that implement the `SynonymProviderInterface`, load synonyms from a specific source and provide it for using them in OpenSearch synonym filters. Sources can be simple files, OpenDxp assets, OpenDxp data objects, database tables or what ever source is needed. OpenDxp ships with a simple `FileSynonymProvider` that can be used right away. Besides the service configuration itself, the synonym providers need to be configured in index service configuration as follows. ```yml opendxp_ecommerce_framework: index_service: tenants: MyOpenSearchTenant: enabled: true worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\OpenSearch\DefaultOpensearch config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\OpenSearch config_options: synonym_providers: app_synonym_filter: # service ID of synonym provider to use provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\SynonymProvider\FileSynonymProvider # additional options for synonym provider (are applied to a child-service instance of given synonym provider options: synonymFile: '%kernel.project_dir%/public/var/assets/system/synonyms.txt' ``` ##### Matching Synonym Providers to Synonym Filters Matching between synonym providers and synonym filters in index settings takes place via name. In the sample below there the synonym provider `app_synonym_filter` provides the synonyms for the filter `app_synonym_filter`. The filter definition in the index settings can hold just an empty array (as some definition is required). During index building, index resetting or reloading of synonyms, the synonyms are loaded from synonyms provider and injected to the synonyms array of the corresponding synonyms filter. ```yml opendxp_ecommerce_framework: index_service: tenants: MyOpenSearchTenant: enabled: true worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\OpenSearch\DefaultOpensearch config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\OpenSearch config_options: synonym_providers: app_synonym_filter: # service ID of synonym provider to use provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\SynonymProvider\FileSynonymProvider # additional options for synonym provider (are applied to a child-service instance of given synonym provider options: synonymFile: '%kernel.project_dir%/public/var/assets/system/synonyms.txt' index_settings: analysis: filter: app_synonym_filter: # mapping between synonym_provider and filter based on name type: synonym # or synonym_graph or any other ES type synonyms: [] # provide an empy array here, for ES6 [], for ES5[""] ``` > Don't forget to also add the synonyms filter to an analysers filter array where needed - as described in [OpenSearch docs](https://opensearch.org/docs/latest/analyzers/token-filters/index/). ##### Updating Synonyms There are three ways of updating the synonyms in the OpenSearch index. For all applies that the synonyms are loaded from synonyms provider and injected to the synonyms array of the corresponding synonyms filter by OpenDxp. ###### Index Creation During index creation the synonyms are loaded from synonym providers and applied to index. ###### Reindex During reindex the synonyms are loaded from synonym providers and applied to index when new index is created. > This is the recommended way to update synonyms during runtime at a production system as there is no service downtime. ###### Search Index sync command With the command `bin/console ecommerce:indexservice:search-index-sync update-synonyms` synonyms can be updated in the current index. For that, the index has to be closed and reopened which means a short downtime of the index. --- ## Special Aspects for OpenSearch Basically OpenSearch worker works as described in the [optimized architecture](../README.md). ### Installation #### OpenSearch To work properly OpenDxp requires the OpenSearch client, install them with: `composer require open-dxp/opensearch-client`. ### Index Configuration OpenSearch provides a couple of additional configuration options for the index to utilize OpenSearch features. See [Configuration Details](01_Configuration_Details.md) for more information. ### Reindexing Mode It is possible that OpenSearch cannot update the mapping, e.g. if data types of attributes change on the fly. For this case, a reindex is necessary. If it is necessary, a native ES reindex is executed automatically during `bin/console ecommerce:indexservice:bootstrap --create-or-update-index-structure`. While reindex is executed, no updates are written to the OpenSearch index. The changes remain in store table and are transferred to index during next execution of `bin/console ecommerce:indexservice:process-update-queue` after reindex is finished. All queries that take place during reindex go to the old index. As soon the reindex is finished, the current index is switched to the newly created index and the old index is deleted. As a result, during reindex the results delivered by Product Lists can contain old data. To manually start a reindex, following command can be used: `bin/console ecommerce:indexservice:search-index-sync reindex`. ### Indexing of Classification Store Attributes With OpenSearch it is possible to index all attributes of [Classification Store](https://github.com/open-dxp/opendxp/tree/1.x/doc/05_Objects/01_Object_Classes/01_Data_Types/15_Classification_Store.md) data without defining an attribute for each single classification store key. For details see [Filter Classification Store](../../../07_Filter_Service/03_Elastic_Search/01_Filter_Classification_Store.md) in Filter Service documentation. ### Synonyms OpenDxp provides an out-of-the box integration for synonyms in OpenSearch. See [Synonyms](./02_Synonyms.md) for details. --- ## Product Index Configuration The configuration of the *Product Index* defines the content of the *Product Index* (which attributes are extracted how and stored where) and takes place in the `opendxp_ecommerce_framework` configuration within the section `index_service`. The product index can define multiple tenants (see [Assortment Tenant Configuration](./03_Assortment_Tenant_Configuration.md)) which can be configured individually. Each tenant defines a set of attributes to index/search and a configuration and worker class responsible for storing and managing the index. ```yaml opendxp_ecommerce_framework: index_service: # product index defines multiple tenants which can be disabled individually # a tenant can define placeholders which will be replaced tenants: _defaults: attributes: name: type: varchar(255) filter_group: string locale: '%%locale%%' default: enabled: false # service ID of the desired configuration config_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Config\DefaultMysql # optional set of options passed to the config service - available options vary by config # implementation config_options: foo: bar # optional - id of the worker handling the index. worker and config must be matching as a worker # is only able to accept a certain config implementation (e.g. an elasticsearch worker can only operate # on an elasticsearch config). as long as you don't implement a custom worker you can omit the wotker_id # as the system is able to automatically resolve the worker for a given config worker_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Worker\DefaultMysql # placeholders will be replaced with the value defined here # you can use placeholders to define multiple tenant configuration # via _defaults which set the locale based on a placeholder # # in this example, the "default" tenant will have the attributes name # and seoname and use "de_AT" as locale for the "name" attribute # # please make sure to use double %% or another char as {} to denote placeholders # as "%locale%" would be replaced by the "%locale%" container parameter instead # of the placeholder placeholders: '%%locale%%': de_AT # add columns for general fulltext search index of productlist # they must be part of the attributes configuration below search_attributes: - name - seoname # defines search index attributes and how they're gathered # as the _defaults entry already defines a name attribute, we'll end # up with name and seoname here attributes: seoname: type: varchar(255) filter_group: string INT: attributes: name_en: &name_en locale: '%%locale%%' filter_group: string placeholders: '%%locale%%': en BE: attributes: name_fr: <<: *name_en # placeholders will be replaced with the value defined here # attribute level placeholders will be processed before tenant level placeholders # # in this example, the "BE" (belgium) tenant will have the attributes "name_fr", "name_de" # and "name_nl" referencing the same attribute config as tenant "INT" (international) # with attribute "name_en", but using use "fr", "de" and "nl" as locale placeholders: '%%locale%%': fr name_de: <<: *name_en placeholders: '%%locale%%': de name_nl: <<: *name_en placeholders: '%%locale%%': nl example_tenant: attributes: rucksacksLoad: type: 'double' filter_group: double # a getter is a specific service responsible for getting the value from an object # this must be defined as service - as we use the class name as service id you can # just use the fully qualified class name. you can use your own getters if you define # them as service first getter_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\DefaultBrickGetter # options passed to the getter. available options vary by getter implementation - see # getter for available options getter_options: brickfield: specificAttributes bricktype: rucksackSpecs fieldname: load # an interpreter can further transform the value retrieved by the getter. same logic applies as # for getters - interpreter must be defined as service interpreter_id: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\Numeric # interpreter can define options which are passed to the interpreter when interpreting the value interpreter_options: {} ``` #### `search_attributes` Defines attributes which should be considered in fulltext-search. All attributes must be defined within the `attributes`-section. #### `attributes` Defines for all attributes if and how they should be indexed. Each attribute is referenced with an unique name (e.g. `seoname` or `rucksacksLoad` in the example above) which is the name of the attribute in the product index. The following configuration options are available: - `type` (mandatory for mysql): Datatype for column in Product Index. - `field_name` (optional): Field name in product object, needed if it is different than `name` in index. Defaults to `name` - `locale` (optional): Used locale for data retrieving if field is in a localized field. - `getter_id` (optional): Service ID of a special getter implementation for getting attribute value. Per default, the method `get()` of the product object is called. If this is not suitable, an alternative getter class can be defined which is responsible for getting the value. This can be used for calculations, getting complex values (field collections, object bricks), etc. Getter implementations need to implement `\OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\GetterInterface` interface and be defined as service. Best practice is to use the fully qualified class name as service ID and to reference the class name in the configuration. - `getter_options` (optional): options passed to the getter when resolving a value. Available options vary by getter implementation. - `interpreter_id` (optional): By default all data is stored without any transformation in the Product Index. With an interpreter, this data can be transformed and manipulated before storing. This can be used for only saving IDs of assets, normalization of data, special treatment of relations, etc. Interpreter implementations need to implement `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\InterpreterInterface` interface. The same service ID best practices as for getters apply to interpreters. - `interpreter_options` (optional): options passed to the interpreter. Available options vary by interpreter implementation. - `hide_in_fieldlist_datatype` (optional): Hides column in FieldList drop down (see [FilterService](../../07_Filter_Service/README.md) for more information). - `filter_group` (optional): Defines filter group for the FieldList drop down (see [FilterService](../../07_Filter_Service/README.md) for more information). ##### Relations in *Product Index* Relations are stored in a special way in *Product Index* and also need to be filtered in a different way in the [Product List](../07_Product_List.md). In order to store relations correctly in the Product Index, relation attributes must have an interpreter defined which implements the interface `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\RelationInterpreterInterface`. ##### Selection of available Getters: - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\DefaultBrickGetter`: Gets data from an Object Brick. Needed configuration: - `brickfield`: Field name of Object Brick, e.g. `bricks`. - `bricktype`: Type of Object Brick, e.g. `TentBrick`. - `fieldname`: Field name of attribute in Object Brick, e.g. `height`. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\DefaultBrickGetterSequence`: Same as `DefaultBrickGetter`, but can use more than one source definition and stores first found value in *Product Index*. The options go under `source`, either as one source or as a list of sources: ```yaml getter_options: source: - brickfield: specificAttributes bricktype: rucksackSpecs fieldname: load - brickfield: specificAttributes bricktype: tentSpecs fieldname: load ``` - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\DefaultBrickGetterSequenceToMultiselect`: Like `DefaultBrickGetterSequence`, but stores all found values as a multi select in the *Product Index*. The options go under `source` as well. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\TagsGetter`: Gets [Tags](https://github.com/open-dxp/opendxp/blob/1.x/doc/18_Tools_and_Features/09_Tags.md) of product object and returns them as array. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Getter\DefaultClassificationAttributeGetter`: Gets attribute value from classification store. Possible options: - `key_id` - id of the classification store attribute - `group_id` - id of the group related to the id | key can occur multiple times in classification store field through multiple groups - `fieldname` - name of the field upon which the classification store is saved on the specific object (defaults to attributes) ##### Selection of available Interpreters: - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\AssetId`: Stores only asset id into *Product Index*. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\DefaultObjects`: Default interpreter to store object relations as relations into the *Product Index*. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\DefaultRelations`: Same as `DefaultObjects` but also for other relations to Assets and Documents. Also can deal with `ObjectMetadata`. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\DefaultStructuredTable`: Interpreter for structured table data type. Expects following configuration options: - `row` - `column` - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\IdList`: Returns id list of given values as CSV list. If configuration option `multiSelectEncoded` is set, it returns id list encoded as multi select (relevant for filtering in Product List). - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\Numeric`: Returns `floatval` of given value. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\QuantityValue`: Interprets quantity value data types, by default by serializing it to string, when config option `onlyValue` set to `true`, it returns only value - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\ObjectId`: Returns id of given object. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\ObjectIdSum`: Calculates sum if ids of given objects. Could be used for similarity calculation. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\ObjectValue`: Get value from an related object. Expects following configuration options: - `['target']['fieldname']`: Field name of value to get. Is used for getter generation which is called on given object. - `['target']['locale']` (optional): Locale passed as first parameter to the getter. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\Round`: Rounds given value to integer. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\Soundex`: Returns soundex of given value. Could be used for similarity calculation. - `OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\DefaultClassificationStore`: Stores all classification store attributes of a data object to the index. Only usable in combination with elasticsearch. See [Filter Classification Store](../../07_Filter_Service/03_Elastic_Search/01_Filter_Classification_Store.md) for details. > Depending on the *Product Index* implementation, the *Product Index* configuration can be slightly different. > See sample configurations for specific *Product Iindex* implementations. --- ## Product List ### Working with Product Lists The API for getting (and filtering, ...) products out of the *Product Index* are so called Product Lists. They all implement the interface `\OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ProductListInterface` and need to be Product Index implementation specific. Detailed method documentation is available in [in-source documentation](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/IndexService/ProductList/ProductListInterface.php). For how to get a Product List instance suitable for the current Product Index implementation and filter for products see following code sample: ```php getIndexService()->getProductListForCurrentTenant(); $list->addCondition("name = 'testproduct'", 'name'); $list->addRelationCondition('category', "dest IN (1024,1025,1026)"); $list->setOrder("ASC"); $list->setOrderKey('name'); $list->load(); ``` All filtered attributes need to be in the *Product Index*. The Product List implements all iterator and paginator interfaces and can be used in foreach loops and in combination with `Knp\Paginator`. > For logging standard Symfony logging is used. E-Commerce Framework Product Indices log into special channels like > `opendxp_ecommerce_indexupdater`, `opendxp_ecommerce_sql`, `opendxp_ecommerce_es` > and `opendxp_ecommerce_findologic`. --- ## Mockup Objects in Product List Results Normally the result of Product Lists contain OpenDxp product objects. When retrieving lists with many entries this can result in performance issues during rendering product listings - especially on high traffic applications when OpenDxp product objects are very complex, heavily use content inheritance and have lots of relations. To address this issue, Product Lists can return so called Mockup objects instead of the original OpenDxp product objects. The idea is that these Mockup objects are a lightweight a selection of the product data, therefore are much smaller and load faster. By default the optimized product index implementations of the E-Commerce Framework support Mockup objects in a transparent way and you can take advantage from the faster loading times. This means that the corresponding product lists return Mockup objects which contain all data that is stored into the product index. If a getter is called on the Mockup object (e.g. `$product->getName()`), it first tries to get the requested data from the index data. If the data is not available, the call is delegated to the original OpenDxp object. Then the call is delegated, following log message is written to OpenDxp log files - if system is in debug mode as `WARN`, otherwise as `INFO`. ``` "Method $method not in Mockup implemented, delegating to object with id {$this->id}." ``` So, the only thing you need to take care about: make sure that all the data that is printed in product listing is available in the product index. ### Using Custom Mockup Object Implementation Of course, it might be necessary to use custom Mockup implementations. To do you, overwrite the `createMockupObject($objectId, $data, $relations)` method in your `Config` implementation. For an example see [`MyOptimizedMysql`](https://github.com/open-dxp/demo/blob/1.x/src/Ecommerce/IndexService/Tenant/Config/MyOptimizedMysql.php#L37) in the Demo. --- ## Index Service The Index Service (in combination with the Filter Service) provides functionality for indexing, listing, filtering and searching products. In the heart of this component is the *Product Index* - an optimized storage of product data for all kinds of queries. Depending on the implementation, the *Product Index* is stored in a special mysql table, in elasticsearch or any other search provider (currently implemented are [fact finder](http://www.fact-finder.de/) and [findologic](https://www.findologic.com/)). These implementations can be configured in [Assortment Tenants](./01_Product_Index_Configuration/03_Assortment_Tenant_Configuration.md). The default tenant always uses `DefaultMysql` as implementation. The separate *Product Index* has several advantages: - It is completely independent from the OpenDxp object structure, only contains needed information and can pre-calculate complex data. - It can be optimized without any side effects on OpenDxp for requirements considering filtering, listing and searching products. - It supports assortment tenants and therefore allows optimized indices for multiple assortments within one system. Based on the *Product Index* the [*Product List*](./07_Product_List.md) provides a one stop API for accessing data and listing products. See the following topics for details: - [Configuration of the *product index*](./01_Product_Index_Configuration/README.md) - [Assortment Tenant configuration](./01_Product_Index_Configuration/03_Assortment_Tenant_Configuration.md) - [Data architecture and indexing process](./01_Product_Index_Configuration/05_Data_Architecture_and_Indexing_Process.md) - [Working with Product Lists](07_Product_List.md) - [Mockup Objects in Product List Results](09_Mockup_Objects.md) --- ## Filter Classification Store With elasticsearch it is possible to index all attributes of [Classification Store](https://github.com/open-dxp/opendxp/blob/1.x/doc/05_Objects/01_Object_Classes/01_Data_Types/15_Classification_Store.md) data without defining an attribute for each single classification store key. To do so, follow these steps #### 1) Index Definition OpenDxp ships with a special interpreter to load all classification store attributes to the index. To use this interpreter add following attribute configuration into your index definition: ```yml some_field_name: fieldname: 'my_classification_store_field_name' interpreter: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\DefaultClassificationStore filtergroup: classificationstore options: mapping: type: 'object' properties: keys: type: 'long' values: type: 'object' ``` This results in a data structure in your index similar to this: ```json "some_field_name" : { "values" : { "1" : [ "one value" ], "2" : [ "another value" ], "3" : [ "123", "99" ], "5" : [ "AT", "DZ" ], "4" : [ "" ] }, "keys" : [ 1, 2, 3, 5, 4 ] ``` This contains all the classification store IDs as well as all the data. #### 2) Filter Type To interpret the indexed data correctly, a special filter type is needed. As this filter type works only in combination with elasticsearch, it is not activated by default. Following steps are necessary to activate it: - make sure the field collection `FilteSelectClsStoreAttributes` is installed and is allowed in the filter list of the filter definition class. - add following filter type mapping (see [here](../README.md) for details): ```yml FilteSelectClsStoreAttributes: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\SelectClassificationStoreAttributes template: 'product/filters/nested_attributes.html.twig' ``` #### 3) Template The template for the filter has to render not only one filter, but the whole list of possible filters for the classification store attributes. For a sample template see our [demo](https://github.com/open-dxp/demo/blob/1.x/templates/product/filters/nested_attributes.html.twig). --- ## Filter for nested documents In some cases it is necessary to store an array of objects, but in a way so that they can be queried independently of each other, i.e. if you want to store an array of additional data from field collections. The data in your index may look as follows: ```json { "_source": { "attributes": { "my_attributes": [ { "id": "12345", "name": "Höhe", "value": "15 mm" }, { "id": "12346", "name": "Länge", "value": "7 mm" }, { "id": "12347", "name": "Breite", "value": "30 mm" } ] } } } ``` To utilize the `nested` document functionality the mapping type of the field `my_attributes` must be defined as `nested`, to let elasticsearch know about the sub-documents: ```yaml attributes: filtergroup: string type: 'nested' options: mapping: type: 'nested' interpreter_id: App\Ecommerce\IndexService\Interpreter\MyAttributes interpreter_options: locale: '%%locale%%' ``` Now you can create a filter for the nested document field, which has to be defined in a nested manner as well: ```php class SelectMyAttribute extends \OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\AbstractFilterType { public function prepareGroupByValues(AbstractFilterDefinitionType $filterDefinition, ProductListInterface $productList): void { /** @var AbstractElasticSearch $productList */ $nestedPath = "attributes.my_attributes"; // first group by id $subAggregationField = $nestedPath . ".id"; // then group by value $subSubAggregationField = $nestedPath . ".value.keyword"; $productList->prepareGroupByValuesWithConfig($this->getField($filterDefinition), true, false, [ "nested" => [ "path" => $nestedPath ], "aggs" => [ $subAggregationField => [ "terms" => [ "size" => 200, "field" => $subAggregationField ], "aggs" => [ $subSubAggregationField => [ "terms" => [ "size" => 200, "field" => $subSubAggregationField ] ] ] ] ] ]); } public function addCondition(AbstractFilterDefinitionType $filterDefinition, ProductListInterface $productList, array $currentFilter, array $params, bool $isPrecondition = false): void { $nestedPath = "attributes.my_attributes"; // @todo: get $myAttributeValue and $myAttributeId from request params $condition = [ "nested" => [ "path" => $nestedPath, "query" => [ "bool" => [ $mode => [ [ "term" => [ $nestedPath . ".value.keyword" => $myAttributeValue ] ], [ "term" => [ $nestedPath."id" => $myAttributeId ] ] ] ] ] ] ]; $productList->addCondition($condition, $this->getField($filterDefinition)); } public function getFilterValues(AbstractFilterDefinitionType $filterDefinition, ProductListInterface $productList, array $currentFilter): array { $field = $this->getField($filterDefinition); $this->prepareGroupByValues($filterDefinition, $productList); $values = $productList->getGroupByValues($field, true, !$filterDefinition->getUseAndCondition()); return [ 'label' => $filterDefinition->getLabel(), 'values' => $values, 'metaData' => $filterDefinition->getMetaData(), 'hasValue' => $this->hasValue, ]; } } ``` #### Further information Read more about - [_nested documents_ ](https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html) - [_nested queries_](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html) - [_nested aggregations_](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html) in the official elasticsearch documentation. --- ## Filter Service with Elasticsearch ### Definition of Filter Types When using elasticsearch as Product Index, different FilterTypes must be configured for the corresponding tenant. These filter types create the elasticsearch specific conditions for each filter. Here is an example for the configuration: ```yml opendxp_ecommerce_framework: filter_service: tenants: ElasticSearch: filter_types: FilterNumberRange: # Service id for filter type implementation filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\NumberRange # Default template for filter, can be overwritten in filter definition template: ':Shop/filters:range.html.php' FilterNumberRangeSelection: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\NumberRangeSelection template: ':Shop/filters:numberrange.html.php' FilterSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\Select template: ':Shop/filters:select.html.php' FilterSelectFromMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\SelectFromMultiSelect template: ':Shop/filters:select.html.php' FilterMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\MultiSelect template: ':Shop/filters:multiselect.html.php' FilterMultiSelectFromMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\MultiSelectFromMultiSelect template: ':Shop/filters:multiselect.html.php' FilterMultiRelation: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\MultiSelectRelation template: ':Shop/filters:multiselect-relation.html.php' FilterCategory: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\SelectCategory template: ':Shop/filters:select_category.html.php' FilterRelation: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\ElasticSearch\SelectRelation template: ':Shop/filters:object_relation.html.php' ``` ### Filtering for Classification Store Attributes With the document structure of elasticsearch it is easily possible to index and filter for classification store attributes without defining them all als separate attributes in the index definition. See [Filter Classification Store](01_Filter_Classification_Store.md) for details. ### Filtering for Nested Documents in General For information how to take leverage of the nested documents feature for elasticsearch and make even more sophisticated search queries, have a look at [Filter Nested Documents](02_Filter_Nested_Documents.md). --- ## Filter Classification Store(Open_Search) With OpenSearch it is possible to index all attributes of [Classification Store](https://github.com/open-dxp/opendxp/blob/1.x/doc/05_Objects/01_Object_Classes/01_Data_Types/15_Classification_Store.md) data without defining an attribute for each single classification store key. To do so, follow these steps #### 1) Index Definition OpenDxp ships with a special interpreter to load all classification store attributes to the index. To use this interpreter add following attribute configuration into your index definition: ```yml some_field_name: fieldname: 'my_classification_store_field_name' interpreter: OpenDxp\Bundle\EcommerceFrameworkBundle\IndexService\Interpreter\DefaultClassificationStore filtergroup: classificationstore options: mapping: type: 'object' properties: keys: type: 'long' values: type: 'object' ``` This results in a data structure in your index similar to this: ```json "some_field_name" : { "values" : { "1" : [ "one value" ], "2" : [ "another value" ], "3" : [ "123", "99" ], "5" : [ "AT", "DZ" ], "4" : [ "" ] }, "keys" : [ 1, 2, 3, 5, 4 ] ``` This contains all the classification store IDs as well as all the data. #### 2) Filter Type To interpret the indexed data correctly, a special filter type is needed. As this filter type works only in combination with OpenSearch, it is not activated by default. Following steps are necessary to activate it: - make sure the field collection `FilteSelectClsStoreAttributes` is installed and is allowed in the filter list of the filter definition class. - add following filter type mapping (see [here](../README.md) for details): ```yml FilteSelectClsStoreAttributes: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\SearchIndex\SelectClassificationStoreAttributes template: 'product/filters/nested_attributes.html.twig' ``` #### 3) Template The template for the filter has to render not only one filter, but the whole list of possible filters for the classification store attributes. For a sample template see our [demo](https://github.com/open-dxp/demo/blob/1.x/templates/product/filters/nested_attributes.html.twig). --- ## Filter for nested documents(Open_Search) In some cases it is necessary to store an array of objects, but in a way so that they can be queried independently of each other, i.e. if you want to store an array of additional data from field collections. The data in your index may look as follows: ```json { "_source": { "attributes": { "my_attributes": [ { "id": "12345", "name": "Höhe", "value": "15 mm" }, { "id": "12346", "name": "Länge", "value": "7 mm" }, { "id": "12347", "name": "Breite", "value": "30 mm" } ] } } } ``` To utilize the `nested` document functionality the mapping type of the field `my_attributes` must be defined as `nested`, to let OpenSearch know about the sub-documents: ```yaml attributes: filtergroup: string type: 'nested' options: mapping: type: 'nested' interpreter_id: App\Ecommerce\IndexService\Interpreter\MyAttributes interpreter_options: locale: '%%locale%%' ``` Now you can create a filter for the nested document field, which has to be defined in a nested manner as well: ```php class SelectMyAttribute extends \OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\AbstractFilterType { public function prepareGroupByValues(AbstractFilterDefinitionType $filterDefinition, ProductListInterface $productList): void { /** @var AbstractOpenSearch $productList */ $nestedPath = "attributes.my_attributes"; // first group by id $subAggregationField = $nestedPath . ".id"; // then group by value $subSubAggregationField = $nestedPath . ".value.keyword"; $productList->prepareGroupByValuesWithConfig($this->getField($filterDefinition), true, false, [ "nested" => [ "path" => $nestedPath ], "aggs" => [ $subAggregationField => [ "terms" => [ "size" => 200, "field" => $subAggregationField ], "aggs" => [ $subSubAggregationField => [ "terms" => [ "size" => 200, "field" => $subSubAggregationField ] ] ] ] ] ]); } public function addCondition(AbstractFilterDefinitionType $filterDefinition, ProductListInterface $productList, array $currentFilter, array $params, bool $isPrecondition = false): void { $nestedPath = "attributes.my_attributes"; // @todo: get $myAttributeValue and $myAttributeId from request params $condition = [ "nested" => [ "path" => $nestedPath, "query" => [ "bool" => [ $mode => [ [ "term" => [ $nestedPath . ".value.keyword" => $myAttributeValue ] ], [ "term" => [ $nestedPath."id" => $myAttributeId ] ] ] ] ] ] ]; $productList->addCondition($condition, $this->getField($filterDefinition)); } public function getFilterValues(AbstractFilterDefinitionType $filterDefinition, ProductListInterface $productList, array $currentFilter): array { $field = $this->getField($filterDefinition); $this->prepareGroupByValues($filterDefinition, $productList); $values = $productList->getGroupByValues($field, true, !$filterDefinition->getUseAndCondition()); return [ 'label' => $filterDefinition->getLabel(), 'values' => $values, 'metaData' => $filterDefinition->getMetaData(), 'hasValue' => $this->hasValue, ]; } } ``` --- ## Filter Service with OpenSearch ### Definition of Filter Types When using OpenSearch as Product Index, different FilterTypes must be configured for the corresponding tenant. These filter types create the OpenSearch specific conditions for each filter. Here is an example for the configuration: ```yml opendxp_ecommerce_framework: filter_service: tenants: MyOpenSearchTenant: filter_types: FilterNumberRange: # Service id for filter type implementation filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\NumberRange # Default template for filter, can be overwritten in filter definition template: ':Shop/filters:range.html.php' FilterNumberRangeSelection: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\NumberRangeSelection template: ':Shop/filters:numberrange.html.php' FilterSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\Select template: ':Shop/filters:select.html.php' FilterSelectFromMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\SelectFromMultiSelect template: ':Shop/filters:select.html.php' FilterMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\MultiSelect template: ':Shop/filters:multiselect.html.php' FilterMultiSelectFromMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\MultiSelectFromMultiSelect template: ':Shop/filters:multiselect.html.php' FilterMultiRelation: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\MultiSelectRelation template: ':Shop/filters:multiselect-relation.html.php' FilterCategory: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\SelectCategory template: ':Shop/filters:select_category.html.php' FilterRelation: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SearchIndex\SelectRelation template: ':Shop/filters:object_relation.html.php' ``` ### Filtering for Classification Store Attributes With the document structure of OpenSearch it is easily possible to index and filter for classification store attributes without defining them all als separate attributes in the index definition. See [Filter Classification Store](01_Filter_Classification_Store.md) for details. ### Filtering for Nested Documents in General For information how to take leverage of the nested documents feature for OpenSearch and make even more sophisticated search queries, have a look at [Filter Nested Documents](02_Filter_Nested_Documents.md). --- ## Filter Service ### Basic Idea of the *Filter Service* The *Filter Service* supports the developers in setting up E-Commerce product listings with filters and layered navigation known from classic shop systems. Therefore it provides functionality to ... - ... configure available filters and to set up the product listings in the frontend. - ... generating the necessary filter conditions for the Product Index based on the filter type and user input. - ... printing out the configured filter with possible filter values etc. to the frontend. To provide this functionality, a few components are necessary. The *Filter Service* links all these components together and provides the developer a clean API for creating product listings in the frontend. ### 1 - Setting up Filter Types Each product listing has different filters like drop downs, multi selects, input fields, number ranges, etc. Each of these Filter Types require - special configuration - special presentation in the view - special filter conditions for the Product Index The Filter Types are responsible for these three tasks and can be used for composing filter definition objects (see next chapter). The backend implementation of Filter Types takes place in php classes which extend the abstract class `\OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\AbstractFilterType` and are responsible for creating the correct filter conditions based on the Product Index implementation and rendering the filter output to the frontend. Therefore `\OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\AbstractFilterType` expects the two methods `getFilterValues()` and `addCondition()` to be implemented. Each Filter Type needs to be defined as service and registered on the `opendxp_ecommerce_framework.filter_service` configuration. The framework already defines a number of core filter types in [filter_service_filter_types.yaml](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Resources/config/filter_service_filter_types.yaml). > FilterTypes are dependent of the used index backend. You need to use different FilterTypes when using MySQL, ElasticSearch or OpenSearch etc. > OpenDxp ships with FilterTypes implementations for all supported index backends. For details see for example > [Elasticsearch Config](03_Elastic_Search/README.md). > [OpenSearch Config](05_Open_Search/README.md). ```yaml opendxp_ecommerce_framework: filter_service: tenants: default: # assign backend implementations and views to filter type field collections filter_types: # filter type for the FilterNumberRange field collection FilterNumberRange: # service id for filter type implementation filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\NumberRange # default template for filter, can be overwritten in filter definition template: ':Shop/filters:range.html.php' FilterNumberRangeSelection: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\NumberRangeSelection template: ':Shop/filters:numberrange.html.php' FilterSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\Select template: ':Shop/filters:select.html.php' FilterSelectFromMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SelectFromMultiSelect template: ':Shop/filters:select.html.php' FilterMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\MultiSelect template: ':Shop/filters:multiselect.html.php' FilterMultiSelectFromMultiSelect: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\MultiSelectFromMultiSelect template: ':Shop/filters:multiselect.html.php' FilterMultiRelation: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\MultiSelectRelation template: ':Shop/filters:multiselect-relation.html.php' FilterCategory: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SelectCategory template: ':Shop/filters:select_category.html.php' FilterRelation: filter_type_id: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\SelectRelation template: ':Shop/filters:object_relation.html.php' ``` Optionally, you can configure a custom filter service which relies on a custom helper implementation. The helper is a tool for the OpenDxp backend controller to get possible group by values for a certain field (used by object data type IndexFieldSelection, e.g. in filter definitions). First, create your filter service definition: ```yaml services: app.custom_filter_service: class: OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterService arguments: - '@OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\FilterGroupHelper' ``` You can now use the service definition in the `filter_service` config: ```yaml opendxp_ecommerce_framework: filter_service: tenants: default: service_id: app.custom_filter_service filter_types: # ... ``` **Configuration elements are:** - `FilterCategory`: The key of the array represents the field collection type (= name of field collection) for configuration in filter definition objects (see next chapter). - `class`: Backend implementation of the filter type. - `script`: Default view script of the filter type, can be overwritten in the filter definition objects. You can find some script filter examples in the Demo [here](https://github.com/open-dxp/demo/tree/1.x/templates/product/filters). - `Helper`: Is a helper implementation that gets available values for pre select settings in the filter definition objects based on the [filter group](../05_Index_Service/01_Product_Index_Configuration/README.md) setting in the index attributes definition. ### 2 - Setting up FilterDefinition Objects The configuration of available filters and the set up of product listings in the frontend takes place in FilterDefinition OpenDxp objects. Configuration options are beside others: - General settings like `page size` etc. - `PreConditions` for pre filtering of products, e.g. only products of a certain category. These preconditions cannot be changed by the user in the frontend. - `Filters` that are visible in the frontend. ![FilterDefinition](../img/filter-definitions.jpg) The configuration of preconditions and filters is done by field collection entries, whereby the field collection types are mapped to Filter Types and their backend implementations in the `opendxp_ecommerce_framework.filter_service` config section (see previous chapter). The Filter Definition class can be extended and modified to custom needs of the system. Filter Definition objects can be assigned to category objects to build up automatic category pages or to area bricks in OpenDxp documents to set up manual landing pages etc. Both is demonstrated at our [Demo](https://demo.opendxp.io) and also available as [source code](https://github.com/open-dxp/demo). In case that a filter contains relational objects (`FilterMultiRelation`, `FilterRelation`, etc.), the `getName()` method of the object is used to render the text in pre-select lists and filters. Implement the `getNameForFilterDefinition()` method in your data objects to show customized (HTML) texts, including icons. ### 3 - Putting it all together Once Filter Types and Filter Definitions are set up, it is quite easy to put it all together and use the *Filter Service* in controller actions. #### Controller For setting up the *Filter Service* (including Product List with `Knp\Paginator`) within the controller use following sample: ```php query->all(), $request->attributes->all()); $indexService = $ecommerceFactory->getIndexService(); $productListing = $indexService->getProductListForCurrentTenant(); $templateParams['productListing'] = $productListing; //get filter definition from document, category or global settings $filterDefinition = //TODO ...get from somewhere; // create and init filter service $filterService = $ecommerceFactory->getFilterService(); (new \OpenDxp\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper)->setupProductList($filterDefinition, $productListing, $params, $filterService, true, true); $templateParams['filterService'] = $filterService; $templateParams['filterDefinition'] = $filterDefinition; // inject and use Knp Paginator service: PaginatorInterface $paginator $paginator = $paginator->paginate( $productListing, $request->get('page', 1), 18 ); $templateParams['results'] = $paginator; $templateParams['paginationVariables'] = $paginator->getPaginationData(); return $this->render('Path/template.html.twig', $templateParams); ``` For a sample of a controller see our demo [here](https://github.com/open-dxp/demo/blob/1.x/src/Controller/ProductController.php#L118). #### View For putting all filters to the frontend use following sample. It is important that this sample is inside a form in order to get the parameter of changed filters delivered back to the controller. ```twig {% if(filterDefinition.filters|length > 0) %} {% for filter in filterDefinition.filters %} {% set filterMarkup = filterService.filterFrontend(filter, productListing, currentFilter) %} {{ filterMarkup | raw }} {% endfor %} {% endif %} ``` --- ## Price Systems In terms of pricing, the E-Commerce Framework has the concept of Price Systems. These Price Systems are responsible for retrieving or calculating prices and returning so called `PriceInfo` objects which contain the calculated prices. Each product can have its own Price System. So very complex pricing structures and different price sources can be integrated into the system quite easily. In terms of product availabilities and stocks, the very similar concept of Availability Systems is used. ### Configuration of Price Systems A price system is a class implementing `OpenDxp\Bundle\EcommerceFrameworkBundle\PriceSystem\PriceSystemInterface` which is defined as service and registered with a name in the `opendxp_ecommerce_framework.price_systems` configuration tree. The framework already ships with a number of [concrete implementations](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/PriceSystem) which you can use as starting point. There are 3 places where the configuration of Price Systems takes place: - **Product class**: Each product has to implement the method `getPriceSystemName()` which returns the name of its Price System. - **Service definition**: Each price system must be registered as service - **Configuration**: The `price_systems` section maps price system names to service IDs The product class returns the name of a price system: ```php The simplest price system is [`OpenDxp\Bundle\EcommerceFrameworkBundle\PriceSystem\AttributePriceSystem`](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/PriceSystem/AttributePriceSystem.php) > which reads the price from an attribute of the product object. For implementing custom price systems have a look at method comments > of [`\OpenDxp\Bundle\EcommerceFrameworkBundle\PriceSystem\PriceSystemInterface`](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/PriceSystem/PriceSystemInterface.php) > and the implementations of the existing price systems. ### Getting and Printing Prices Once the Price Systems are set up correctly, working with prices should be quite easy. Each product has the method `getOSPrice()` which returns a `\OpenDxp\Bundle\EcommerceFrameworkBundle\PriceSystem\PriceInterface` object with the price of the product. Internally the product gets its Price System and starts the price calculation to get the price. When the price system returns a custom `PriceInfo` object (e.g. with additional stock prices, customer specific prices etc.), this `PriceInfo` can be retrieved by calling `getOSPriceInfo()` method of the product object. A sample for printing the price on a product detail page is: ```twig

{{ product.OSPrice }}

``` --- ## Tax Management Within the Price Systems there is a Tax Management component to deal with all sorts of taxes. So it is possible to calculate and print out taxes as needed. The Tax Management is quite transparent and should not affect the system very deeply. As a result - if not necessary (e.g. because you have a B2B system, etc.) - you don't need to deal with taxes in E-Commerce Framework at all. Also, if you have your very own tax implementation, this should be perfectly possible and you should need to not deal with the Tax Management in the E-Commerce Framework at all. Just use all the default values and every thing should be fine. ### Components of Tax Management If you need to deal with taxes following components are important to know of: #### Tax Configuration with `OnlineShopTaxClass` The configuration of taxes is done with `OnlineShopTaxClass` OpenDxp objects within in the OpenDxp Backend UI. The actual tax calculation is always based on the configuration of such a tax class. So, tax configurations for different countries and product groups can be established. The tax calculation is always based on one tax class, a combination of tax classes is not possible. The configuration concludes a TaxEntryCombinationMode (`combine` and `one after another`) and one or more tax entries with a name and a tax rate in percent. ![tax classes](../img/tax-class.png) The selection of the correct tax class (for a certain country and a certain product group) is done by the Price System (see next section). #### Tax Class Selection with Price Systems The Price System decides for each product and environment which tax class to take for tax calculation. Therefore following two methods need to be implemented: - `getTaxClassForProduct`: Should return tax class for given product. The default implementation returns a generic tax class based on the Website Settings or - if not set - an empty tax class. - `getTaxClassForPriceModification`: See later for more information. The logic behind the tax class selection can be of any complexity. It can be based on a simple Website Setting (for one tax class fits all), or based on a complex matrix with product group, sending country, delivering country and several other aspects. #### Tax Calculation with `TaxCalculationService` The actual tax calculation is done in the `TaxCalculationService::updateTaxes(PriceInterface $price, $calculationMode = self::CALCULATION_FROM_NET)` method. It updates taxes in given price object by using its tax entries, tax combination mode and net or gross amount based on the given `$calculationMode`. The calculation is done by the framework in two places: - By Price Systems when creating the `PriceInfo` objects - By `PriceInterface` objects when `setAmount`, `setGrossAmount` or `setNetAmount` is called and `$recalc` is set to true. #### The `PriceInterface` object Every price in the E-Commerce Framework comes down to an `PriceInterface` object. Therefore also all calculated taxes and all necessary information for calculating taxes is stored in `PriceInterface` objects. Following methods are important: - `getTaxEntries()`, `setTaxEntries($taxEntries)`: Sets and gets tax entries for price. Each price can have one or more tax entries based on the tax laws. Each of these tax entries contain percent rate and calculated amount. The order of the tax entries is important. - `getTaxEntryCombinationMode()`, `setTaxEntryCombinationMode($taxEntryCombinationMode)`: Sets and gets the tax entry combination mode which defines how tax calculation is done based on the tax entries: - `TaxEntry::CALCULATION_MODE_COMBINE`: Sum up all tax rates and calculate tax amount afterwards. - `TaxEntry::CALCULATION_MODE_ONE_AFTER_ANOTHER`: For each tax rate calculate tax amount, add it to total price and then calculate tax amount for next tax rate based on new total sum. - `TaxEntry::CALCULATION_MODE_FIXED`: Amounts and percent rates are fixed and cannot be (re)calculated based on information within the `PriceInterface` object. This mode is needed for `subTotal` and `grandTotal` in `CartPriceCalculator`. - `getGrossAmount()`, `setGrossAmount($grossAmount, $recalc = false)`: Sets and gets gross amount of price. If `$recalc` is set to `true`, corresponding net price is calculated based on tax entries and tax entry combination mode. - `getNetAmount()`, `setNetAmount($netAmount, $recalc = false)`: Sets and gets net amount of price. If `$recalc` is set to `true`, corresponding gross price is calculated based on tax entries and tax entry combination mode. - `getAmount()`, `setAmount($amount, $priceMode = self::PRICE_MODE_GROSS, $recalc = false)`: Gets the gross amount by default and sets the gross or net amount based on the params. ### Special Aspects #### Tax Calculation in Pricing Rules E-Commerce Framework Pricing Rules always modify the gross price of the product and recalculate the net price based on the tax entries of the product price. So specified discount amounts on product level need to be configured as gross discounts. Since cart discounts are implemented as `CartPriceModificators` the next point is important for them. It might be necessary to extend the default implementation of the cart discounts for the correct selection of the tax class for discounts. The default implementation uses the `getTaxClassForPriceModification` method of the Price System called `default` for tax class selection. #### Tax Calculation in `CartPriceModificators` The `CartPriceModificators` themselves can decide if the modification should be done as net or gross amount since the interface `ModificatedPriceInterface` extends `PriceInterface` and therefore all tax related information as explained above. The method `getTaxClassForPriceModification` in Price Systems can be used to delegate the tax class selection to Price Systems. ### Putting the Pieces Together For setting up the tax management, following steps are necessary. #### 1) Defining Tax Classes Create and configure all the `OnlineShopTaxClass` objects within OpenDxp. #### 2) Configuring Price System Setup the correct price systems and implement their methods `getTaxClassForProduct` and `getTaxClassForPriceModification`. It might also be necessary to have a look at the `CartPriceModificator` for cart discounts and make sure that it selects the correct tax class. #### 3) Printing Taxes To print taxes into the frontend use following samples: ##### Product Detail Page ```twig {% set price = product.OSPrise %} {{ price }}

{{ 'shop.detail.included_tax'|trans }}'

    {% for entry in price.taxEntries %}
  • {{ entry.entry.name }}: {{ entry.percent }}% ({{ price.currency.toCurrency(entry.amount) }})
  • {% endfor %}
``` ##### Cart ```twig {% set grandTotal = cart.priceCalculator.grandTotal %} {% if grandTotal.taxEntries %} {{ 'cart.taxes'|trans }} {% for taxEntry in grandTotal.taxEntries %} {{ taxEntry.entry.name }}: {{ taxEntry.percent }}% ({{ grandTotal.currency.toCurrency(taxEntry.amount) }})
{% endfor %} {% endif %} ``` ##### Order Confirmation Mail ```twig {% if order.taxInfo %} {{ 'cart.taxes'|trans }} {% for taxEntry in order.taxInfo %} {{ taxEntry[0] }}: {{ taxEntry[1] }} ({{ currency.toCurrency(taxEntry[2])) }})
{% endfor %} {% endif %} ``` #### 4) Taxes in `OnlineShopOrders` Make sure that all tax related attributes are available in `OnlineShopOrder` and `OnlineShopOrderItem`. Then the E-Commerce Framework populates all needed values automatically and therefore stores the tax information in the order objects. --- ## Pricing Rules Pricing Rules are supported by the E-Commerce Framework out of the box. The pricing rules themselves can be configured in the OpenDxp Backend UI by putting conditions and actions together. Once active, all rules are checked and applied automatically by the system - including reducing product prices, adding price modificators to reduce cart totals, removing shipping costs and adding gift items to the cart. To print the applied rules in the frontend, the developer needs to add some lines of code. Depending on the location, following scripts can be used. ##### Product Detail Page ```twig {% set priceInfo = product.OSPriceInfo %} {% if priceInfo.rules %}

{{ 'shop.detail.your_benefit'|trans }}

    getRules() as $rule ) { ?> {% for rule in priceInfo.rules %} getActions() as $action) { ?> {% for action in rule.actions %} {% if action is instanceof('OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\Action\ProductDiscount') %} {% if action.amount > 0 %}
  • {{ rule.label }} {{ 'shop.detail.your_benefit.discount.amount'|trans([action.amount]) }}
  • {% elseif action.percent > 0 %}
  • {{ rule.label }} {{ 'shop.detail.your_benefit.discount.percent'|trans([action.percent]) }}
  • {% endif %} {% elseif action is instanceof('OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\Action\GiftInterface') %}
  • {{ 'shop.detail.your_benefit.discount.gift'|trans }}, {{ action.product.name }}
  • {% elseif action is instanceof('OpenDxp\Bundle\EcommerceFrameworkBundle\PricingManager\Action\FreeShipping') %}
  • {{ 'shop.detail.your_benefit.discount.freeshipping'|trans }}
  • {% endfor %} {% endfor %}
{% endif %} ``` ##### Cart Product List - Printing Gift Items ```twig {% for item in car.giftItems %} {% set linkDetail = item.product.shopDetailLink %} {{ item.product.OSName }} {{ item.count }} {% endfor %} ``` > All other price modifications on cart level are included as cart price modificators. > See [Cart manager](../11_Cart_Manager.md) for more details and how to print them. --- ## Vouchers(Working_with_Prices) Like Pricing Rules, also vouchers are supported out of the box by the framework. To use vouchers, following steps are necessary: 1) Create an `OnlineShopVoucherSeries` object. 2) Create tokens based on the `OnlineShopVoucherSeries`. 3) Create a Pricing Rule for the `OnlineShopVoucherSeries` and define the benefit of the voucher. 4) Allow the user to add a token to his cart. 5) Display voucher information to user. ##### Create an `OnlineShopVoucherSeries` object A voucher series contains basic information of the voucher and settings for creating the voucher tokens. It is represented by `OnlineShopVoucherSeries` objects. The corresponding class is added to the system during installation of the E-Commerce Framework. ![Creating Voucher Series](../img/voucher-series.png) Currently there are two types of vouchers supported - Single and Pattern. - Single: One single token is defined that can be used multiple times. - Pattern: Tokens are generated based on a certain pattern definition. ![Voucher Series Settings Pattern](../img/voucher-series-pattern.png) ##### Create tokens based on the `OnlineShopVoucherSeries` In the OpenDxp Backend UI, each `OnlineShopVoucherSeries` object has an additional tab for managing the voucher tokens. Depending on the token type there are different functions for managing the tokens and some statistics concerning the voucher. - Simple: 'Activate' the token and specify how often it may be used. ![Create Tokens Simple](../img/voucher-series-single-2.jpg) - Pattern: Create tokens based on the defined pattern, export created tokens as csv and get an overview of created tokens and their usages. ![Create Tokens Pattern](../img/voucher-series-pattern-2.png) ##### Create a Pricing Rule for the `OnlineShopVoucherSeries` Once a voucher series is defined and tokens are created, a pricing rule has to define the benefits of the voucher. To do so, a special condition allows to specify the voucher series the pricing rule should be valid for. As action all available actions for pricing rules can be used. The voucher token condition also can contain an error message, that can be shown if voucher token is added to cart, but not all other conditions of the pricing rule are met. ![Pricing Rule](../img/voucher-series-rule.jpg) ##### Allow the User to Add a Token to his Cart A voucher token is always applied to a cart. To do so, use following snippet. ```php get('voucher-code', ''))) { try { $success = $cart->addVoucherToken($token); if ($success) { $this->addFlash('success', $translator->trans('cart.voucher-code-added')); } else { $this->addFlash('danger', $translator->trans('cart.voucher-code-cound-not-be-added')); } } catch (VoucherServiceException $e) { $this->addFlash('danger', $translator->trans('cart.error-voucher-code-' . $e->getCode())); } } ``` ###### Error Codes of Exceptions thrown | Code | Description | | ---- | ------------------------------------------------------------------ | | 1 | Token already in use. | | 2 | Token already reserved. | | 3 | Token reservation not possible. | | 4 | No token for this code exists. | | 5 | Criteria oncePerCart: Token of same series already in cart. | | 6 | Criteria onlyTokenPerCart: Tokens in cart and tried to add token of type "only". | | 7 | Criteria onlyTokenPerCart: Token of type "only" already in cart. | | 8 | No more usages for a single token. | | 8 | Token code not found in cart. | ##### Display Voucher Information Since benefits for vouchers are defined via pricing rules, no special actions are needed to display them. They are just displayed the same way as all other Pricing Rules. Another consequence of defining the benefits of vouchers via pricing rules is, that additional criteria (like date range etc.) can be defined to be required to get the benefits. To get all necessary detail information about vouchers, use `getPricingManagerTokenInformationDetails` of the cart or the voucher service. This method returns an array of `PricingManagerTokenInformation` for each added token with following information: - Voucher Token - Token Object - List of applied pricing rules that require the given voucher token. - List of not applied pricing rules that would take the given voucher token into account but are not applied because some other conditions are not met. - List of error messages that are defined in voucher token conditions of all pricing rules that would take the given voucher token into account but are not applied because some other conditions are not met. - Flag that indicates if no pricing rules are defined for the given voucher token at all. See an sample snippet to display the voucher information to the customer: ```twig
{% if (cart.pricingManagerTokenInformationDetails | length > 0) %}
    {% for codeInfo in cart.pricingManagerTokenInformationDetails %}
  • {{ codeInfo.tokenCode }}
    {% if (codeInfo.errorMessages | length) > 0 %} {{ codeInfo.errorMessages | join(', ') }} {% endif %} {% if (codeInfo.noValidRule) %} {{ 'cart.voucher-no-rule' | trans }} {% endif %}
  • {% endfor %}
{% endif %}
``` --- ## Calculate with Prices As floating point numbers (`float`, `double`) are not able to represent numbers exactly (see [here](http://floating-point-gui.de/) if you want to know details), and exact numbers are a strict demand to e-commerce applications the E-Commerce Framrwork uses [`Decimal`](https://github.com/open-dxp/ecommerce-framework-bundle/tree/1.x/src/Type/Decimal.php) value objects instead of floats to represent prices. These value objects internally store the represented value as integer by defining a fixed amount of supported digits (so-called `scale`) after the comma and by multiplying the actual value with the given scale on construction. The scale is set to 4 by default, but can be changed globally in the `opendxp_ecommerce_framework.decimal_scale` config entry. An example: Given a scale of 4, a `Decimal` will internally represent a number of `123.45` as `1234500` by calculating `123.45 * 10^4 = 1234500`. To calculate with these values, the `Decimal` class exposes methods like `add()`, `sub()`, `mul()`, `div()` and others to run calculations without having to deal with the internal scale representation. For details see the [Decimal class definition](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Type/Decimal.php) and the corresponding [test](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/tests/Ecommerce/Type/DecimalTest.php) which contains a lot of usage examples and describes the `Decimal` behaviour quite well. > **Important**: The `Decimal` is designed as *immutable* value object. Every operation yields a *new* instance of a `Decimal` representing the new value. Please be aware that this needs to be considered when calculating with `Decimal`s and/or when extending the `Decimal` class with custom functionality. On the DB side, all E-Commerce Framework class definitions supporting price values were updated to store prices as [`DECIMAL`](https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html) data type. This means, when fetching a price value from an ecommerce-object (e.g. an order), it will be a string instead of a `float`. This string can directly be passed to the `Decimal` value object's `create()` method. A usage example: ```php add($b); var_dump($c->asString()); // 30.0000 as the default string representation contains all digits depending on the scale // regarding immutability: $a->add($b); // $a is still 10 and will never be changed - the add() method returns a new object ($c in the example above) $a->equals(Decimal::create(30)); // false $a->equals(Decimal::create(10)); // true ``` In most cases, you should be able to build a `Decimal` object by using the static `create()` method which is able to build a `Decimal` from strings, integers and floating point numbers. If needed, you can also make use of a number of `from*` methods directly exposing costruction logic for a specific type (e.g. `fromDecimal(Decimal $decimal)`). ### Rounding logic The `Decimal` object will try to avoid rounding and calculating with floats if possible. If you pass a string to the `create()` method, it will try to convert the numeric string to an integer with string operations before falling back to converting it into a float which is rounded. Examples (given a scale of 4): * `Decimal::create('123')` will just add 4 chars of `0` to the string and cast it to an integer (no floats involved) - results in `1230000` * `Decimal::create('123.45')` will move the dot to the right by 2 places and add 2 chars of `0` - results in `1234500` However, if the given value exceeds the maximum scale or is a float value, the `create()` method needs to fall back to float calculations and rounding to generate the integer representation: * `Decimal::create('123.1234567')` with a string value will fall back to float calculations as the amount of digits after the comma exceed the scale of `4`. The value is first multiplied with `10^4`, resulting in PHP casting the string to float. The float `1231234.567` is then passed to PHP's `round()` function with a `precision` parameter of `0` and a default rounding mode of `PHP_ROUND_HALF_UP`, resulting in an integer representation of `1231235` (note the rounding on the last digit). * `Decimal::create(123.1234567)` with a float value will have the same behaviour as above (skipping the string conversion). You can influence how rounding is applied by specifying the `$roundingMode` parameter on the `create()` method: ``` asString()); // 123.5555 var_dump(Decimal::create('123.55555', 4, PHP_ROUND_HALF_UP)->asString()); // 123.5556 ``` Please be aware that as rounding is applied only when exceeding the scale, the following can happen: ``` 1.9999 var_dump(Decimal::create('1.9999')->asString()); // rounding is applied -> 2.0000 var_dump(Decimal::create('1.99999')->asString()); ``` This is important to know as it could lead to unexpected calculation results. The `DECIMAL` mysql data type has the same behaviour - if you calculate with `Decimal`s at a higher scale you still need to update your class definitions to match that scale as otherwise the same rounding logic will be applied by the database. However, while doing calculations (e.g. tax or discount calculations, reports), you're free to calculate at a higher scale by passing the `scale` parameter to the `create()` method and just setting the resulting value to the scale represented on the DB. Example: ```php toPercentage(15); // create a representation with a lower scale - at this point rounding logic will be applied $result = $b->withScale(4); // an order object $order->setTotalPrice($result->asString()); $order->save(); ``` ### Extending the Decimal class You're free to add custom calculation logic to the Decimal class, but please make sure every operation returns a new instance holding the calculated value. An object can never change its internal state (value and scale) after construction! ### Caveats/aspects good to know * In order to have sufficient number of digits in integer datatype, your system should run on 64 bit infrastructure. On 32 bit systems, you would be able to handle prices up to 214,748.3647 only (since max int value with 32 bit is 2,147,483,647). The `Decimal` implementation contains logic to throw an exception on an integer overflow in case the used numbers are too large/small. --- ## Working with Prices Prices are an essential part of every E-Commerce solution. In order to be able to implement complex and very custom pricing schemes, the E-Commerce Framework has the concept of [Pricing Systems](./01_Price_Systems_and_getting_Prices.md). These Pricing Systems encapsulate all the logic of retrieving and calculating prices. The [Tax Management Component](./03_Tax_Management.md) adds functionality for dealing with taxes and should be flexible enough to implement all kinds of tax structures. With [Pricing Rules](./05_Pricing_Rules.md) and [Vouchers](./07_Vouchers.md) marketing actions can be implemented. For details on how to calculate with prices, see [Calculate with Prices](./09_Calculate_with_Prices.md). --- ## Working with Availabilities For availabilities there is a similar concepts like the [PriceSystems](./09_Working_with_Prices/01_Price_Systems_and_getting_Prices.md) for prices - which is called *Availability Systems*. The Availability Systems are responsible for retrieving or calculating availabilities of a product and returning a so called `AvailabilityInfo` object which contains all the availability information. Each product can have its own Availability System. ### Configuration of Availability Systems An availability system is a class implementing `OpenDxp\Bundle\EcommerceFrameworkBundle\AvailabilitySystem\AvailabilitySystemInterface` which is defined as service and registered with a name in the `opendxp_ecommerce_framework.availability_systems` configuration tree. Currently, the framework ships only with a [sample implementation](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/AvailabilitySystem/AvailabilitySystem.php#L21) which you can use as starting point. There are 3 places where the configuration of Availability Systems takes place: - **Product class**: Each product has to implement the method `getAvailabilitySystemName()` which returns the name of its Availability System. - **Service definition**: Each Availability System must be registered as service - **Configuration**: The `availability_systems` section maps Availability System names to service IDs The product class returns the name of an Availability System: ```php getCartManager(); $cartId = $manager->createCart(array('name' => $cartName)); $cart = $manager->getCart( $cartId ); ``` ##### Adding and removing products ```php getCartManager(); $cart = $manager->getCartByName($cartName); $id = $cart->addItem( $product, $amount ); $cart->save(); $cart->removeItem( $id ); $cart->save(); //alternative way $cartItemId = $manager->addToCart( $product, $amount, $cart->getId() ); //save is done automatically $manager->removeFromCart($cartItemId, $cartId); //save is done automatically ``` ##### List products of cart ```php getCartManager(); $cart = $manager->getCartByName($cartName); if (count($cart->getItems()) > 0) { foreach ($cart->getItems() as $item) { $product = $item->getProduct(); //item key $cartItemId = $item->getItemKey(); //item amount $amount = $item->getCount(); //price info and price $priceInfo = $item->getPriceInfo(); $price = $item->getPrice(); } } ``` ### Price Calculation in Carts Each cart has a `CartPriceCalculator` (configuration see below) which is responsible for calculating total sums of the cart. The `CartPriceCalculator` sums up all product prices to a sub total, adds (or subtracts) so called price modificators like shipping costs, cart discounts, etc. and then calculates a grand total. See sample below for how to get the different sums: ```php getPriceCalculator()->getSubTotal(); // iterates through all price modifications foreach ($cart->getPriceCalculator()->getPriceModifications() as $name => $modification) { // $name is the label of a modification // $modification is an implementation of \OpenDxp\Bundle\EcommerceFrameworkBundle\PriceSystem\ModificatedPriceInterface } // delivers sum including all price modifications $grandTotal = $cart->getPriceCalculator()->getGrandTotal(); ``` ### Configuration of Cart Manager The configuration takes place in the `opendxp_ecommerce_framework.cart_manager` configuration section which is [tenant aware](./04_Configuration/README.md). ```yaml opendxp_ecommerce_framework: cart_manager: tenants: # defaults for all cart managers _defaults: # define service manager id of cart service - following value is default and can be omitted cart_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\MultiCartManager # configuration for carts - the following values are set by default and can be omitted cart: # service ID of a cart factory which creates individual carts at runtime factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartFactory # options passed to cart factory, e.g. the cart class (available options vary by factory implementation) factory_options: cart_class_name: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\Cart guest_cart_class_name: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\SessionCart default: price_calculator: # list price modificators for cart, e.g. for shipping-cost, special discounts, ... # key is name of modificator modificators: shipping: class: OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartPriceModificator\Shipping # configuration options for price modificator options: charge: "5.90" # additional checkout tenant for cart manager # - active tenant is set at \OpenDxp\Bundle\EcommerceFrameworkBundle\EnvironmentInterface::setCurrentCheckoutTenant() noShipping: ~ # inherits from _defaults ``` Following elements are configured: * **Cart manager service ID**: The cart manager is the basic entry point for working with carts. It is responsible for all interactions with different carts and provides functionality as creating carts, adding/removing products and also creates the corresponding price calculator. * **Cart factory service ID**: builds carts when needed and can be configured with cart class name and further options varying by factory implementation * **Price calculator factory service ID + options and modificators**: The price calculator is a framework for calculation and modification (shipping costs, discounts, ...) of prices on cart level. Each modification is implemented in a [`CartPriceModificatorInterface` class](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/CartManager/CartPriceModificator/CartPriceModificatorInterface.php). See [Shipping](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/CartManager/CartPriceModificator/Shipping.php) or [Discount](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/CartManager/CartPriceModificator/Discount.php) for examples. ### Available Cart Implementations Following cart implementations are shipped with OpenDxp core and can be configured in the `factory_options` section of the cart manager configuration: * **Session-Cart** (class name `OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\SessionCart`): This cart implementation stores all cart information in the **session** of the user. If the session is cleared, also the carts are deleted. Use this implementation when no user login is available and storing carts in the database has no benefit. * **Database-Cart** (class name `OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\Cart`): This cart implementation stores all cart information in the **database**. In this case, it is important that the currently logged in user is set to the [E-Commerce Framework Environment](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/EnvironmentInterface.php) with the code snippet in the box below. Use this implementation when user logins are available and the carts should be persisted beyond session lifetime. > Note: if you are using the database cart, don't forget to set the currently logged in user to the environment like > follows: `Factory::getInstance()->getEnvironment()->setCurrentUserId(YOUR_USER_ID)` ### Checkout Tenants for Carts The E-Commerce Framework has the concept of so called Checkout Tenants which allow different cart manager and checkout manager configurations based on a currently active checkout tenant. The current checkout tenant is set in the framework environment as follows: ```php getEnvironment(); $environment->setCurrentCheckoutTenant('default'); $environment->save(); $environment->setCurrentCheckoutTenant('noShipping'); $environment->save(); ``` Once set, the cart manager uses all specific settings of the currently active checkout tenant which are configured in the configuration (identified by tenant name). See also [Demo](https://github.com/open-dxp/demo/blob/1.x/config/ecommerce/base-ecommerce.yaml#L197) for some examples. ### Adding Custom Properties to Cart Items Following steps are necessary to add additional custom properties to cart items: 1) Extend `OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartItem` implementation and add your custom properties including getters/setters. 2) Extend `Cart::getCartItemClassName` implementation and make sure your custom `CartItem` implementation gets returned. 3) Provide the custom properties as key-value pairs in `$params` parameter in the following methods: 1) `OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\AbstractCart::addItem` 2) `OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\AbstractCart::updateItem` 3) `OpenDxp\Bundle\EcommerceFrameworkBundle\CartManager\CartManagerInterface::addToCart` --- ## Basic Configuration The configuration takes place in the `opendxp_ecommerce_framework.checkout_manager` configuration section and is [tenant aware](../04_Configuration/README.md). ```yaml opendxp_ecommerce_config: checkout_manager: tenants: _defaults: # the following two values are default values an can be omitted # service ID of a checkout manager factory which builds cart specific checkout managers factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\CheckoutManagerFactory # options passed to the factory - available options vary by implementation factory_options: class: \OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CheckoutManager handle_pending_payments_strategy: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\HandlePendingPayments\CancelPaymentOrRecreateOrderStrategy # commit order processor commit_order_processor: # order processor service ID id: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CommitOrderProcessor # options passed to the commit order processor - available options vary by implementation options: confirmation_mail: /en/emails/order-confirmation # define different checkout steps which need to be committed before commit of order is possible steps: deliveryaddress: class: \OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\DeliveryAddress # example step from the Ecommerce demo, which extends AbstractStep confirm: class: \App\Ecommerce\Checkout\Confirm default: # define payment provider which should be used for payment. # payment providers are defined in payment_manager section. payment: provider: qpay paypal: payment: provider: paypal ``` Following elements are configured: * **Service ID and options of the checkout manager factory**: The Checkout Manager is a central player of the checkout process. It checks the state of single checkout steps, is responsible for the payment integration and also calls the commit order processor in the end. As the a checkout manager is specific to a cart instance, checkout manager factory takes care of creating checkout managers on demand. * Optional configuration option `handle_pending_payments_strategy` defines strategy how to handle pending payments. See [Integrating Payment](./07_Integrating_Payment.md) for details. * [**Checkout steps and their implementation**](./03_Checkout_Steps.md): Each checkout step (e.g. Delivery address, delivery date, ...) needs a concrete checkout step implementation. The implementation is responsible for storing and validating the necessary data, is project dependent and has to be implemented for each project. * [**Service ID and options of the commit order processor**](./05_Committing_Orders.md): When finalization of the order is done by the commit order processor. This is the places, where custom ERP integrations and other project dependent order finishing stuff should be placed. * **Additional stuff like**: * Mail configuration * [Payment Implementation](./07_Integrating_Payment.md) * [Checkout Tenants](./09_Checkout_Tenants.md) --- ## Checkout Steps For each checkout step (e.g. delivery address, delivery date, ...) there has to be a concrete checkout step implementation. This implementation is responsible for storage and loading of necessary checkout data for each step. It needs to extend `\OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\AbstractStep` and implement `\OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\CheckoutStepInterface`. Following methods have to be implemented: * `commit($data)`: Is called when step is finished and data needs to be saved. * `getData()`: Returns saved data for this step. * `getName()`: Returns name of the step. ### Configuration of Checkout Steps: See [configuration](./01_Basic_Configuration.md) for checkout step configuration. ### Sample Implementation of a Checkout Step: ```php cart->setCheckoutData(self::PRIVATE_NAMESPACE, json_encode($data)); return true; } /** * returns saved data of step */ public function getData(): mixed { $data = json_decode($this->cart->getCheckoutData(self::PRIVATE_NAMESPACE)); return $data; } } ``` ### Working with Steps: ```php getCheckoutManager($cart); $step = $manager->getCheckoutStep("deliveryaddress"); $address = new stdClass(); //fill address $manager->commitStep($step, $address); $step = $manager->getCheckoutStep("deliverydate"); $manager->commitStep($step, $data); $cart->save(); ``` --- ## Committing Orders After all checkout steps are completed, the order can be committed. If no payment is involved, this is done as follows. If payment is involved, have a look at the [Payment Integration docs](./07_Integrating_Payment.md). ```php getCheckoutManager($cart); $order = $manager->commitOrder(); ``` While committing the order, the checkout manager delegates it to the specified commit order processor implementation, which needs to implement `\OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\CommitOrderProcessorInterface`. This is the place where all functionality for committing the order (e.g. sending orders to erp systems, sending order confirmation mails, ...) is located. The default implementation `\OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CommitOrderProcessor` provides basic functionality like creating a OpenDxp order object and sending an order confirmation mail. Order creation itself is delegated to the `\OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\OrderManagerInterface`. ### Typically needed Custom Extensions In simple use cases a project specific implementation needs * ...to extend `\OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\V7\OrderManager` and overwrite the method `applyCustomCheckoutDataToOrder` to add additional custom fields to the order object and * ...to extend `\OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CommitOrderProcessor` and overwrite the method `processOrder` where website specific functionality is integrated (sending orders to erp systems, ...). See following examples for details. #### Order Manager If additional information needs to be stored into the order, the OrderManager has to be extended. For more Information concerning the [OrderManager](../17_Order_Manager/README.md) see the [documentation](../17_Order_Manager/README.md). A simple implementation of `App\Ecommerce\Order\OrderManager` could look like: ```php getCheckoutManager($cart); $deliveryAddress = $checkout->getCheckoutStep('deliveryaddress') ? $checkout->getCheckoutStep('deliveryaddress')->getData() : null; $confirm = $checkout->getCheckoutStep('confirm') ? $checkout->getCheckoutStep('confirm')->getData() : null; if($deliveryAddress) { //inserting delivery and billing address from checkout step delivery $order->setCustomerFirstname( $deliveryAddress->firstname ); $order->setCustomerLastname( $deliveryAddress->lastname ); $order->setCustomerCompany( $deliveryAddress->company ); $order->setCustomerStreet( $deliveryAddress->address ); $order->setCustomerZip( $deliveryAddress->zip ); $order->setCustomerCity( $deliveryAddress->city ); $order->setCustomerCountry( $deliveryAddress->country ); $order->setCustomerEmail( $deliveryAddress->email ); $order->setDeliveryFirstname( $deliveryAddress->firstname ); $order->setDeliveryLastname( $deliveryAddress->lastname ); $order->setDeliveryCompany( $deliveryAddress->company ); $order->setDeliveryStreet( $deliveryAddress->address ); $order->setDeliveryZip( $deliveryAddress->zip ); $order->setDeliveryCity( $deliveryAddress->city ); $order->setDeliveryCountry( $deliveryAddress->country ); } else if($confirm) { //in quick checkout - only get email-adress from confirm step $order->setCustomerEmail( $confirm ); } return $order; } } ``` #### Commit Order Processor A simple implementation of `\App\Checkout\Processor` could look like: ```php sendOrder($order); $order->setOrderNumber($erpOrderNumber); } catch(Exception $e) { Logger::error($e->getMessage()); throw $e; } } } ``` If needed, further methods can be overwritten. E.g. `sendConfirmationMail` if special e-mails should be sent to specific persons. After commit order was successful, the user can be directed to a success-page. --- ## Payment Integration To integrate payment into the checkout process, instead of calling `$manager->commitOrder();` like described in [Committing Orders](./05_Committing_Orders.md), a few more steps are necessary. ### Initialize Payment in Controller After all checkout steps are completed, the payment can be started. This is done as follows: ```php /** * @Route("/checkout-init-payment", name="shop-checkout-init-payment") */ public function initPaymentAction(Request $request, Factory $factory) { // ... do some stuff, and get $cart /** @var CheckoutManagerInterface $checkoutManager */ $checkoutManager = $factory->getCheckoutManager($cart); //optional - init payment and get OpenDxp internal payment ID (e.g. if needed for config of payment provider) $paymentInformation = $checkoutManager->initOrderPayment(); $config = new DatatransRequest([ //all options needed for payment provider - you also can use setters of the corresponding object ]); // start payment $startPaymentResponse = $checkoutManager->startOrderPaymentWithPaymentProvider($config); // depending on response type handle start payment response - e.g. render form, render snippet, etc. $paymentForm = $startPaymentResponse->getForm(); return $this->render('payment/init_payment.html.twig', [ 'form' => $paymentForm->getForm()->createView() ]); } ``` ### Build payment view Once the payment is started, the created payment form needs to be integrated into the view script. Depending on the payment provider, also other data structures can be created: ```twig

{{ 'Starting Payment' }}

{{ form(form) }} ``` For more samples see [our demo](https://github.com/open-dxp/demo/blob/1.x/templates/payment/payment_frame.html.twig) ### Handle Payment Response When the user finishes the payment, the given response (either via redirect or via server side call) has to be handled as follows. If payment handling was successful, the order needs to be committed. A client side handling could look like as follows: ```php /** * @Route("/checkout-payment-response", name="shop-checkout-payment-response") */ public function paymentResponseAction(Request $request, Factory $factory, RequestStack $requestStack) { // ... do some stuff, and get $cart $checkoutManager = $factory->getCheckoutManager($cart); $params = []; // ... get all necessary parameters for payment provider, e.g. by array_merge($request->query->all(), $request->request->all()); try { $order = $checkoutManager->handlePaymentResponseAndCommitOrderPayment($params); // optional to clear payment // if this call is necessary depends on payment provider and configuration. // its possible to execute this later (e.g. when shipment is done) // $payment = $checkoutManager->getPayment(); // $paymentStatus = $payment->executeDebit(); // $orderAgent = Factory::getInstance()->getOrderManager()->createOrderAgent($order); // $orderAgent->updatePayment($paymentStatus); $session = $requestStack->getSession(); $session->set("last_order_id", $order->getId()); $goto = $this->generateUrl('shop-checkout-completed'); } catch (\Exception $e) { $this->addFlash('danger', $e->getMessage()); $goto = $this->generateUrl('shop-checkout-address'); } return $this->render('payment/payment_response.html.twig', ['goto' => $goto]); } ``` A server side handling could look as follows: ```php query->all(), $request->request->all()); $environment = $factory->getEnvironment(); //if checkout tenant is set via param, use that one for this request if($params['checkouttenant']) { $environment->setCurrentCheckoutTenant($params['checkouttenant'], false); } $commitOrderProcessor = $factory->getCommitOrderProcessor(); $paymentProvider = $factory->getPaymentManager()->getProvider("unzer"); if($committedOrder = $commitOrderProcessor->committedOrderWithSamePaymentExists($params, $paymentProvider)) { Logger::info("Order with same payment is already committed, doing nothing. OrderId is " . $committedOrder->getId()); } else { $order = $commitOrderProcessor->handlePaymentResponseAndCommitOrderPayment( $params, $paymentProvider ); Logger::info("Finished server side call. OrderId is " . $order->getId()); } exit("success"); } ``` ### Dealing with Pending Payments Depending on the shops user journey, it might be possible, that a user starts multiple payments. Typical use cases for that can be: * User starts payment → user goes back to shop and changes cart → user starts checkout and payment with modified cart again * User has multiple tabs open → user starts payment in first tab → user starts another payment in second tab → user finishes first payment → user finishes second payment The ecommerce application needs a strategy how to deal with that. Tthe checkout manager can be configured with one of the following strategies how to handle pending payments when a new payment is started (with `handle_pending_payments_strategy` factory option): * **RecreateOrder**: Create new order every time a payment is started and leave old orders untouched. ```yml factory_options: class: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CheckoutManager handle_pending_payments_strategy: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\HandlePendingPayments\AlwaysRecreateOrderStrategy ``` * **CancelPaymentOrRecreateOrder** (default value): Cancel payments if possible and cart has not changed, create new order when cart has changed. ```yml factory_options: class: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CheckoutManager handle_pending_payments_strategy: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\HandlePendingPayments\CancelPaymentOrRecreateOrderStrategy ``` * **ThrowException**: Throw exceptions to make handling of these cases in controller possible. ```yml factory_options: class: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\CheckoutManager handle_pending_payments_strategy: OpenDxp\Bundle\EcommerceFrameworkBundle\CheckoutManager\V7\HandlePendingPayments\ThrowExceptionStrategy ``` Above mentioned use cases will now result in following behavior: * User starts payment → user goes back to shop and changes cart → user starts checkout and payment with modified cart again: * Cart can be changed despite pending payments. * When user restarts payment, new order is created for new payment (with new cart content): * If user finishes the first payment, first order is finished → all post order processes are done based on first order. * If user finishes second payment, second order is finished. * If user finishes both payments, user has two orders. * User has multiple tabs open → user starts payment in first tab → user starts another payment in second tab → user finishes first payment → user finishes second payment: * Depending on configured CancelPaymentOrRecreateOrderStrategy when user starts second payment following things can happen: * RecreateOrder: Another order is created and user has two orders when he finishes both payments. * CancelPaymentOrRecreateOrder: First payment would be cancelled, user only has one order. When user finishes both payments, both payment information entries will be in one order. * ThrowException: When starting second payment an exception will be thrown and controller needs to decide what to do. It is possible to implement custom strategies as they are just services implementing `HandlePendingPaymentsStrategyInterface`. For more details see [Payment Docs ](../15_Payment/README.md) section. --- ## Checkout Manager Details Following documentation page provide a few more insights on Checkout Manager Architecture. #### Architecture Details ![Architecture V7](../img/PaymentWorkflowV7.svg) * Stars mark places, where events are thrown. For details see [EventManager docs](https://github.com/open-dxp/opendxp/tree/1.x/doc/20_Extending_OpenDxp/11_Event_API_and_Event_Manager.md). --- ## Checkout Tenants for Checkout The E-Commerce Framework has the concept of Checkout Tenants which allow different cart manager and checkout manager configurations based on a currently active checkout tenant. The current checkout tenant is set in the framework environment as follows. Once set, the checkout manager uses all specific settings of the currently active checkout tenant. So different checkout steps, different payment providers etc. can be implemented within one shop. ```php getEnvironment(); $environment->setCurrentCheckoutTenant('default'); $environment->save(); $environment->setCurrentCheckoutTenant('noShipping'); $environment->save(); ``` > When using server-by-server payment confirmation communication, make sure that the correct tenant is set during the > response handling! --- ## Checkout Manager(Checkout_Manager) The Checkout Manager is responsible for all aspects concerning checkout process and an one-stop API for getting through the checkout process. But: The checkout manager is not an out-of-the-box checkout process! It is a tool and a set of components the developer can use to create a use case specific checkout process. > Starting with OpenDxp 1.0 an optimized checkout manager architecture was introduced. This is parallel to the old > architecture, which is deprecated now and will be removed in OpenDxp 2.0. For details see [Checkout Manager Details](08_Checkout_Manager_Details.md). ###### Involved Modules and their function - **Controller**: Website Controller that controls the flow. - **Cart**: Cart is the cart and user should be able to modify the cart all the time. - **CheckoutManager**: One-Stop API for controller to manage checkout, start and handle payments and commit orders. - **OrderManager**: API for working with orders - creating them, listing them, etc. - **OrderAgent**: API for manipulating single order, also responsible for status management of payments within order. - **PaymentProvider**: Interface to payment provider. - **CommitOrderProcessor**: Worker that handles all steps to commit order after payment was successfully finished by user. ###### See following sub pages for detailed information - [Basic configuration of Checkout Manager](./01_Basic_Configuration.md) - [Setting up Checkout Steps](./03_Checkout_Steps.md) - [Committing Orders](./05_Committing_Orders.md) - [Integrating Payment](./07_Integrating_Payment.md) - [Using Checkout Tenants](./09_Checkout_Tenants.md) --- ## Recurring Payment OpenDxp currently supports recurring payment for the payment provider Datatrans (_Alias_). It is performed via backend operations (server-to-server) which are used to create a new order and a new payment attempt by reusing the payment information available in a previous order, the so-called source order. Recurring payment can for example be used to implement sequential payments like hiring or leasing agreements, or also to perform a one time payment for an authorized user which already committed at least one previous order successfully. #### Additional Information - [Datatrans Documentation](https://www.datatrans.ch/alias-tokenization/using-the-alias) ### Best Practice #### Bad Way ![Recurring Payment Bad](../img/recurring-payment-bad.png) #### Good Way ![Recurring Payment Good](../img/recurring-payment-good.png) ### Implementation The following code will briefly show how to perform a one time payment inside the checkout process for _Wirecard Checkout Page_ (former known as Qpay). ##### CheckoutController.php ```php public function paymentAction(Request $request): Response { $factory = \OpenDxp\Bundle\EcommerceFrameworkBundle\Factory::getInstance(); $checkoutManager = $factory->getCheckoutManager($this->cart); $user = $this->getUser(); // open payment or submit recurring payment if ($request->getMethod() == 'POST') { if ($sourceOrderId = $request->get("recurring-payment")) { /* Recurring Payment */ if ($user && $sourceOrderId) { $sourceOrder = \OpenDxp\Model\DataObject\OnlineShopOrder::getById($sourceOrderId); try { $targetOrder = $checkoutManager->startAndCommitRecurringOrderPayment($sourceOrder, $user->getId()); return $this->redirect($this->generateUrl('checkout', ['action' => 'completed'])); } catch (\Exception $exception) { // show warning } } } } $templateParams = []; $paymentMethods = ["SEPA-DD", "CCARD"]; // supported payment methods if ($user) { $sourceOrders = []; foreach ($paymentMethods as $paymentMethod) { $orderManager = $factory->getOrderManager(); $sourceOrder = $orderManager->getRecurringPaymentSourceOrder($user->getId(), $checkoutManager->getPayment(), $paymentMethod); $sourceOrders[$paymentMethod] = $sourceOrder; } $templateParams['sourceOrders'] = $sourceOrders; } $templateParams['paymentMethods'] = $paymentMethods; return $this->render('checkout/payment.html.twig', $templateParams); } ``` ##### payment.html.php ```twig ?>
{% if sourceOrders is not empty %}

{{ 'checkout.use-recurring-payment'|trans }}

{% for paymentMethod in paymentMethods %} {% if sourceOrders[paymentMethod] is defined %} {% set sourceOrder = sourceOrders[paymentMethod] %} {% set paymentProvider = sourceOrder.paymentProvider.paymentProviderQpay %} {% if paymentProvider %} {% currentPaymentMethod = paymentProvider.Auth_paymentType %}

{{ currentPaymentMethod }} {% if currentPaymentMethod is same as('SEPA-DD') %} {{ paymentProvider.Auth_bankAccountOwner }} {{ paymentProvider.Auth_bankAccountIBAN }} {% elseif currentPaymentMethod is same as('CCARD') %} {{ paymentProvider.Auth_maskedPan }} {{ paymentProvider.Auth_expiry }} {% endif %}

{% endif %} {% endif %} {% endfor %}
{% endif %}
``` ##### ecommerce.yaml ```yaml payment_manager: providers: qpay: profiles: sandbox: secret: 'CHCSH7UGHVVX2P7EHDHSY4T2S4CGYK4QBE4M5YUUG2ND5BEZWNRZW5EJYVJQ' customer: 'D200411' toolkit_password: 'XXXXXXX' # necessary for recurPayment operation optional_payment_properties: - paymentType - transactionIdentifier # necessary for recurPayment based on SEPA DIRECT DEBIT recurring_payment_enabled: true # enable recurring payment ``` --- ## Payment Manager The Payment Manager is responsible for all aspects concerning payment. The main aspect is the implementation of different Payment Provider to integrate them into the framework. ### Basic workflow 1. [SHOP] Init payment provider (`$payment->initPayment()`). 2. [SHOP] User click pay button and is redirected to the payment provider page. 3. [PAYMENT PROVIDER] User fill up payment information and is redirected back to the shop. 4. [SHOP] Check if the payment is authorised (`$payment->handleResponse()`). At this step the order can be committed. 5. [SHOP] Clearing payment if its required (`$payment->executeDebit()`) For more information about integrating Payment into checkout processes see [Integrating Payment Docs](../13_Checkout_Manager/07_Integrating_Payment.md). ### Configuration Configuration of Payment Manager takes place in the `opendxp_ecommerce_config.payment_manager` config section: ```yaml opendxp_ecommerce_config: payment_manager: # service ID of payment manager implementation - following value is default value an can be omitted payment_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\PaymentManager # configuration of payment providers, key is name of provider providers: datatrans: # service ID of payment provider implementation provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\Payment\Datatrans # active profile - you can define multiple profiles in the section below profile: sandbox # available profiles with options - options vary on the provider implementation as the profiles: sandbox: merchant_id: 1000011011 sign: 30916165706580013 use_digital_signature: false live: merchant_id: merchant_id_id sign: sign_id use_digital_signature: false mode: live ogone: provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\Payment\OGone profile: sandbox profiles: sandbox: secret: D343DDFD3434 pspid: MyTestAccount mode: sandbox # encryptionType: SHA256 or SHA512 (optional) live: secret: D343DDFD3434 pspid: MyLiveAccount mode: live # encryptionType: SHA256 or SHA512 (optional) mpay24: provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\Payment\Mpay24Seamless profile: testsystem profiles: _defaults: #paypal_activate_item_level: true partial: Shared/Includes/Shop/Payment/paymentMethods.html.php payment_methods: cc: paypal: sofort: invoice: testsystem: merchant_id: 95387 password: 7&jcQ%v6RB testSystem: true debugMode: true live: merchant_id: todo password: todo testSystem: false debugMode: false hobex: provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\Payment\Hobex profile: sandbox profiles: sandbox: entityId: '8a829418530df1d201531299e097175c' authorizationBearer: 'OGE4Mjk0MTg1MzBkZjFkMjAxNTMxMjk5ZTJjMTE3YWF8ZzJnU3BnS2hLUw==' testSystem: true payment_methods: - VISA - MASTER - SOFORTUEBERWEISUNG - SEPA ``` The payment provider name will be referenced from the checkout manager configuration and can be used to fetch a specific provider from the payment manager. ### Payment Providers Following Payment Providers are available as a dedicated bundle to be integrated into the E-commerce framework: - [PayPalSmartButton](https://github.com/open-dxp/payment-provider-paypal-smart-payment-button-bundle) - [Unzer (former Heidelpay)](https://github.com/open-dxp/payment-provider-unzer-bundle) #### Other Payment Providers (not yet migrated to OpenDXP; contact us for more information) - [Datatrans](https://github.com/open-dxp/payment-provider-datatrans-bundle) - [Klarna](https://github.com/open-dxp/payment-provider-klarna-bundle) - [OGone](https://github.com/open-dxp/payment-provider-ogone-bundle) - [MPay24](https://github.com/open-dxp/payment-provider-mpay24-seamless-bundle) - [PayU](https://github.com/open-dxp/payment-provider-payu-bundle) - [Hobex](https://github.com/open-dxp/payment-provider-hobex-bundle) ### Further Payment Aspects - [Recurring Payments](10_Recurring_Payments.md) --- ## Working with Order Lists The Order List are a one stop API for filtering and listing order objects. Of course default OpenDxp object lists also can be used for listing order objects. But Order Lists provide additional functionality in terms of predefined filters etc. ### Basic - Get Newest Orders ```php getOrderManager(); $orderList = $orderManager->createOrderList(); // get the newest 10 orders $orderList->setOrder( 'order.orderDate desc' ); $orderList->setLimit( 10, 0 ); // iterate /** @var \OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\OrderListItemInterface $order */ foreach($orderList as $order) { echo $order->getOrdernumber(); } // ALTERNATE: use knp paginator service: PaginatorInterface $paginator $paginator = $paginator->paginate( $orderList, $request->get('page', 1), 10 ); foreach($paginator as $order) { ... } ``` #### Basic - Using Filter ```php getOrderManager(); $orderList = $orderManager->createOrderList(); // create date time filter $filterDate = new \OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\Listing\Filter\OrderDateTime(); $filterDate->setFrom( new DateTime('20.01.2015') ); $filterDate->setTill( new DateTime('31.01.2015') ); // add filter $orderList->addFilter( $filterDate ); ``` #### Basic - list Order Items ```php getOrderManager(); $orderList = $orderManager->createOrderList(); // get only orders that are committed $orderList->setListType( $orderList::LIST_TYPE_ORDER_ITEM ); $orderList->setOrderState( AbstractOrder::ORDER_STATE_COMMITTED ); ``` #### Advanced - Custom Condition ```php getOrderManager(); $orderList = $orderManager->createOrderList(); // e.g. - search for a specify order number $query = $orderList->getQuery(); $query->where('order.ordernumber = ?', 'ord_554b425dcae53'); // e.g. - search for a user comment $query = $orderList->getQuery(); $query->where('order.comment like ?', '%hallo world%'); ``` #### Expert - High Performance > avoid loading of OpenDxp object's for higher performance ```php getOrderManager(); $orderList = $orderManager->createOrderList(); // add all required fields to the select $orderList->addSelectField(['OrderNumber' => 'order.orderNumber']); $orderList->addSelectField(['TotalPrice' => 'order.totalPrice']); $orderList->addSelectField(['Items' => 'count(orderItem.id)']); ``` #### Expert - Extended Conditions via Joins ```php joinCustomer( \OpenDxp\Model\DataObject\Customer::classId() ); $orderList->getQuery()->where('customer.id = ?', 12345); // e.g. filter product number $orderList->joinProduct( \OpenDxp\Model\DataObject\Product::classId() ); $orderList->getQuery()->where('product.productNumber = ?', 'CMD1191'); ``` #### Generic Filter > Namespace: \OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\Listing\Filter | Filter | Description | | --------------- | ----------- | | OrderDateTime | Date Range Filter | | OrderSearch | Search order for a specified keyword | | Payment | Filter by payment state (ok or fail) | | Product | Filter by product and its variants | | ProductType | Filter ordered products for the given class names | | CustomerObject | Filter orders by given Customer Object | | Search | Generic search filter for searches against a given DB column | | Search\Customer | Search for customer name | | Search\CustomerEmail | Search for customer email | | Search\PaymentReference | Search for a payment reference | --- ## Working with Order Agent The Order Agent is a one stop API for working with orders, e.g. changing state of orders, modifying quantity of items, etc. and keeps track of these changes in a change log. See following examples for how Order Agent can be used: ### Change item quantity ```php getParam('id')); $order = $orderItem->getOrder(); // create new order agent $orderManager = Factory::getInstance()->getOrderManager(); $orderAgent = $orderManager->createOrderAgent($order); // change amount to 5 /** @var \OpenDxp\Model\Element\Note $log */ $log = $orderAgent->itemChangeAmount($orderItem, 5); // add user comment $log->addData('message', 'text', 'customer has changed the order by phone'); $log->save(); ``` ### Changelog Usage ```php getParam('id')); // create new order agent $orderManager = Factory::getInstance()->getOrderManager(); $orderAgent = $orderManager->createOrderAgent($order); // get changelog /** @var \OpenDxp\Model\Element\Note $log */ foreach($orderAgent->getFullChangeLog() as $log) { ... } ``` --- ## Order Manager The Order Manager is responsible for all aspects of working with orders except committing them (which is the responsibility of the Commit Order Processor). These aspects contain among other things: * Creating orders based on carts * Order Storage (by default as OpenDxp objects) * Loading orders * Loading order lists and filter them ([Order List](./01_Working_with_Order_Lists.md)) * Working with orders after order commit ([Order Agent](./02_Working_with_Order_Agent.md)) ### Configuration The configuration takes place in the `opendxp_ecommerce_framework.order_manager` config section and is [tenant aware](../04_Configuration/README.md). ```yaml opendxp_ecommerce_framework: order_manager: tenants: _defaults: # service ID of order manager implementation order_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\V7\OrderManager # options for oder manager options: # OpenDxp object class for orders order_class: \OpenDxp\Model\DataObject\OnlineShopOrder # OpenDxp object class for order items order_item_class: \OpenDxp\Model\DataObject\OnlineShopOrderItem # Class for order listing list_class: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\Listing # Class for order item listing list_item_class: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\Listing\Item # Default parent folder for new orders, will be parsed by strftime() # @deprecated since open-dxp/ecommerce-framework-bundle v1.0.0, please use `order_parent_path` instead # NB: this configuration node will be ignored when the new one is set parent_order_folder: /order/%%Y/%%m/%%d # deprecated and discouraged # Default parent folder for new order items, can use Carbon date format parameters wrapped by `*` eg. *D* order_parent_path: /order/*Y*/*M*/*D* # Options for oder agent order_agent: # service ID of order agent factory - builds order agents individual to each order factory_id: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\Order\AgentFactory # options for order agent factory - available options vary by factory implementation factory_options: agent_class: OpenDxp\Bundle\EcommerceFrameworkBundle\OrderManager\V7\OrderAgent # inherits from _defaults default: ~ # inherits from _defaults, but sets another order folder otherFolder: options: # parent_order_folder: /order_otherfolder/%%Y/%%m/%%d # deprecated and discouraged order_parent_path: /order_otherfolder/*Y*/*M*/*D* ``` --- ## Tracking Manager The Tracking Manager enables e-commerce transaction tracking for e-commerce websites built with the framework. Due to different tracker implementations, it supports different tracking services. Current implementations of trackers are * **Google Tag Manager (GTM)**: `\\OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\Tracker\GoogleTagManager` * **Google Analytics Classic**: `\OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\Tracker\Analytics\Ecommerce` * **Google Analytics Universal**: `\OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\Tracker\Analytics\UniversalEcommerce` * **Google Analytics Enhanced E-Commerce**: `\OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\Tracker\Analytics\EnhancedEcommerce` ### Supported Tracking Actions The Tracking Manager supports several tracking actions that can be used. These tracking actions are delegated to the trackers. * Product Impression * Tracks product impression * `$trackingManager->trackProductImpression($product)` * Product View * Tracks product view (of detail page) * `$trackingManager->trackProductView($product)` * Category View * Tracks a category page view * `$trackingManager->trackCategoryPageView($category)` * Cart Product Action Add * Tracks action for adding product to cart * `$trackingManager->trackCartProductActionAdd($cart, $product, $quantity)` * Cart Product Action Remove * Tracks action for removing product from cart * `$trackingManager->trackProductActionRemove($cart, $product, $quantity)` * Cart Update * Tracks a generic cart update for trackers not supporting add/remove. This can be sent on every cart list or cart change. * `$trackingManager->trackProductActionRemove($cart, $product, $quantity)` * Checkout * Tracks start of checkout with first step * `$trackingManager->trackCheckout($cart)` * Checkout Step * Tracks checkout step * `$trackingManager->trackCheckoutStep($step, $cart, $stepNumber, $checkoutOption)` * Checkout Complete * Tracks checkout complete * `$trackingManager->trackCheckoutComplete($order)` There are 2 deprecated actions which are still supported by should be replaced with their new counterparts: * Product Action Add (use `trackCartProductActionAdd` instead) * Tracks action for adding product to cart * `$trackingManager->trackProductActionAdd($product, $quantity)` * Product Action Remove (use `trackCartProductActionRemove` instead) * Tracks action for removing product from cart * `$trackingManager->trackProductActionRemove($product, $quantity)` > Be aware: Depending on the used tracking service some of these actions might not be available. > If so, the tracking action is ignored for this tracker. ### Configuration The configuration takes place in the `opendxp_ecommerce_framework.tracking_manager` config section. If no `TrackingItemBuilder` is configured, the `TrackingItemBuilder` will fall back to the default implementation `\OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\TrackingItemBuilder`. Further information about `TrackingItemBuilder` see below. ```yaml opendxp_ecommerce_framework: # tracking manager - define which trackers (e.g. Google Analytics Universal Ecommerce) are active and should # be called when you track something via TrackingManager tracking_manager: # service ID of tracking manager - the following is the default value and can be omitted tracking_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\TrackingManager trackers: # enable the core enhanced_ecommerce tracker with default options enhanced_ecommerce: enabled: true my_custom_tracker: # use already defined enhanced ecommerce tracker id: OpenDxp\Bundle\EcommerceFrameworkBundle\Tracking\Tracker\Analytics\EnhancedEcommerce # options vary by tracker implementation options: template_prefix: App:Tracking/analytics/enhanced # service id for item builder item_builder_id: App\Ecommerce\Tracking\TrackingItemBuilder # List of assortment and checkout tenants where this tracker should be activated for. tenants: # Add list of assortment tenants where the tracker should be activated for. Empty array means activated for all tenants. assortment: [] # Add list of checkout tenants where the tracker should be activated for. Empty array means activated for all tenants. checkout: [] ``` ### Tracking Manager With Tenants The Tracking Manager supports tenants in a different way than the other framework modules. While with the other modules, the tenant configuration takes place on the highest level of configuration and each configuration is only valid for one tenant, the tenant configuration in the tracking manager takes place within the trackers them self. There a list of assortment and checkout tenants for which the tracker should be enabled can be provided (see configuration above). If nothing is set or an empty array is provided, the tracker is active for all tenants. ### Working with Tracking Manager For utilizing the Tracking Manager, just call the corresponding methods of the TrackingManager in your controller. The framework does the rest (adding necessary code snippets to your view, etc.). See the following examples #### Product Impression ```php paginate($products, $request->get('page', 1)); foreach ($paginator as $product) { $trackingManager->trackProductImpression($product); } // ... } } ``` #### Checkout ```php trackCheckout($this->getCart()); ... } } ``` ### Project Specific Data Adding project specific data to tracking items by extending the `TrackingItemBuilder` class. The extending class has to be defined as service and configured on the tracker configuration (see above). #### Example for Additional Data in Product Impressions Define a custom item builder: ```php setId($product->getOSProductNumber()); $item->setList($this->getImpressionListName()); self::$impressionPosition++; $item->setPosition(self::$impressionPosition); return $item; } } ``` And define it as service: ```yaml services: App\Ecommerce\Tracking\TrackingItemBuilder: ~ ``` ### External Links [Google Documentation Enhanced E-Commerce](https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce) --- ## Events and Event Listeners ### General This bundle provides additional Events. It's recommended to have a look into the OpenDxp [Events and Event Listeners documentation](https://docs.opendxp.io/docs/core-framework/Extending_OpenDxp/Event_API_and_Event_Manager) ### Available Events - [Ecommerce::Index Service](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Event/IndexServiceEvents.php) - [Ecommerce::Checkout Manager](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Event/CheckoutManagerEvents.php) - [Ecommerce::Commit Order Processor](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Event/CommitOrderProcessorEvents.php) - [Ecommerce::Order Agent](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Event/OrderAgentEvents.php) - [Ecommerce::Order Manager](https://github.com/open-dxp/ecommerce-framework-bundle/blob/1.x/src/Event/OrderManagerEvents.php) --- ## Changelog(Ecommerce-framework) ### 1.1.0 - [CHORE] [MIGRATION] The installer keeps its state in the settings store. Run the migrations after the update. They mark an existing installation as installed. - [BUGFIX] The index configurations and workers, the cart manager, the order manager and the filter types are abstract services. The bundle derives a service per tenant from them. A container that makes its services public failed on them. - [BUGFIX] The `locale` of the interpreter `ObjectValue` is optional, as its documentation says - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] Change to new css color variable prefix naming [#8](https://github.com/open-dxp/ecommerce-framework-bundle/pull/8) ### 1.0.1 - [CHORE] Update payment provider links and migration notes in documentation [#5](https://github.com/open-dxp/ecommerce-framework-bundle/pull/5) - [CHORE] Update branding names [#6](https://github.com/open-dxp/ecommerce-framework-bundle/pull/6) - [ENHANCEMENT] Add php 8.5 support [#7](https://github.com/open-dxp/ecommerce-framework-bundle/pull/7) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update test suite [#1](https://github.com/open-dxp/ecommerce-framework-bundle/pull/1) - [CHORE] Update test files [#2](https://github.com/open-dxp/ecommerce-framework-bundle/pull/2) - [CHORE] Rector level 0 [#3](https://github.com/open-dxp/ecommerce-framework-bundle/pull/3) - [CHORE] Update naming references [#4](https://github.com/open-dxp/ecommerce-framework-bundle/pull/4) --- ## E-Commerce Framework *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP E-Commerce Framework is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Why OpenDXP E-Commerce Framework The e-commerce environment has fundamentally changed and e-commerce projects often face new challenges like: - **complex product structures:** lots of data attributes, complex product relations, configurable product systems, different sources for products - **complex pricing structures:** product dependent price sources, tier pricing, pricing matrices, individual pricing rules, integration of remote pricing services - **complex availability calculations** - **thousands customer groups with:** customer group specific prices, customer group specific assortments - **individual checkouts:** individual integration of backend systems, integration of multi-channel processes into checkout workflow - **individual design** - **highly agile projects with changing requirements:** 'fail fast', fast changing environments and requirements - etc. We think for these challenges a default shop system that pops out of a box, that has a fixed product data model, fixed workflows, a template based frontend and needs to be connected and integrated with other systems via interfaces is not the tool to go for. We think for these challenges you need... - a **framework for developers** to build **outstanding e-commerce solutions for customers**, - with a native integration into OpenDXP, - with a component based architecture - and a strict separation between backend functionality and frontend presentation. That is the idea behind the E-Commerce Framework of OpenDXP. Like OpenDXP itself, it is not a ready made system, it is a set of tools and functionality to help building e-commerce applications really fast and flexible. ### Provided Functionality in a Nutshell - Tools for indexing, listing, searching and filtering products - Implementations of carts, wish lists, comparison lists, etc. - Concepts for flexible and complex pricing, taxes and availability functionality - Functionality and tools for implementing checkout processes - Pricing Rules and Vouchers - Tools for working with and managing Orders - Concepts for setting up multi tenant and multi shop solutions ### Installation ```json { "require": { "open-dxp/ecommerce-framework-bundle": "^1.1" } } ``` - Execute: `$ bin/console opendxp:bundle:install OpenDxpEcommerceFrameworkBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\EcommerceFrameworkBundle\Migrations'` - Read the [changelog](CHANGELOG.md) before you update. - Coming from an earlier package? Read [Migrating to OpenDXP](doc/03_Installation/01_Migrating_to_OpenDXP.md). ### Working With E-Commerce Framework Following aspects are short-cuts into the documentation for start working with the E-Commerce Framework: - [Architecture Overview](./doc/01_Architecture_Overview.md) - [Installation](./doc/03_Installation/README.md) and [Configuration](./doc/04_Configuration/README.md) - [Indexing and Listing Products](./doc/05_Index_Service/README.md) - [Filtering Products](./doc/07_Filter_Service/README.md) - [Working with Prices](./doc/09_Working_with_Prices/README.md) - [Working with Carts](./doc/11_Cart_Manager.md) - [Setting up Checkouts](./doc/13_Checkout_Manager/README.md) - [Integrating Payment Functionality](./doc/15_Payment/README.md) - [Working with Orders](./doc/17_Order_Manager/README.md) - [Tracking Manager](./doc/19_Tracking_Manager.md) - [Events](./doc/20_Event_API_and_Event_Manager.md) *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore ecommerce-framework-bundle (7a0ab7f / v1.3.5)](https://github.com/pimcore/ecommerce-framework-bundle/tree/7a0ab7f567077ed8304f302799ccd43227bc1325), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Docker We created a sample docker setup for running Elasticsearch locally on your machine. Feel free to customize and use this as a template to create your own setup. #### Docker Compose Setup This will create an Elasticsearch container (`elastic`) and a Kibana container (`kibana`). They will communicate between each other via an encrypted connection! If you do not need an encrypted connection just comment out the ssl stuff (see code comments) ```yaml #docker-compose.yaml services: php: user: '1000:1000' # set to your uid:gid supervisord: user: '1000:1000' # set to your uid:gid db: ports: - "3306:3306" create_certs: container_name: elastic_create_certs image: elasticsearch:8.4.3 command: > bash -c ' if [[ ! -f ./certs/certs-bundle.zip ]]; then echo "Generating CA"; #bin/elasticsearch-certutil ca --silent --pass "password" --pem --out ./certs/certs-bundle.zip; bin/elasticsearch-certutil ca --silent --pem --out ./certs/certs-bundle.zip; unzip ./certs/certs-bundle.zip -d ./certs; fi if [ ! -f ./certs/certs.zip ]; then echo "Creating certs"; echo -ne \ "instances:\n"\ " - name: elastic\n"\ " dns:\n"\ " - elastic\n"\ " - localhost\n"\ " ip:\n"\ " - 127.0.0.1\n"\ > ./certs/instances.yml; bin/elasticsearch-certutil cert --silent --pem --ca-cert ./certs/ca/ca.crt --ca-key ./certs/ca/ca.key --in ./certs/instances.yml --out ./certs/certs.zip; unzip ./certs/certs.zip -d ./certs; fi echo "Setting file permissions" chown -R root:root ./certs; find . -type d -exec chmod 750 \{\} \;; find . -type f -exec chmod 640 \{\} \;; echo "Waiting for Elasticsearch availability"; until curl --insecure -s --cacert ./certs/ca/ca.crt https://elastic:9200 | grep -q "missing authentication credentials"; do sleep 30; done; echo "Setting kibana_system password"; until curl --insecure -s -X POST --cacert ./certs/ca/ca.crt -u "elastic:somethingsecret" -H "Content-Type: application/json" https://elastic:9200/_security/user/kibana_system/_password -d "{\"password\":\"somethingsecret\"}" | grep -q "^{}"; do sleep 10; done; echo "All done!" ' user: "0" working_dir: /usr/share/elasticsearch volumes: - opendxp-enterprise-elastic-certs:/usr/share/elasticsearch/certs elastic: container_name: elastic-10 image: elasticsearch:8.4.3 environment: - discovery.type=single-node - "ES_JAVA_OPTS=-Xms1g -Xmx1g" - xpack.security.enabled=true - ELASTIC_PASSWORD=somethingsecret # DISABLE LINES BELOW IF SSL IS NOT NEEDED! #CONFIG BELOW USES PEM - xpack.security.http.ssl.enabled=true - xpack.security.http.ssl.key=certs/elastic/elastic.key - xpack.security.http.ssl.certificate=certs/elastic/elastic.crt - xpack.security.http.ssl.certificate_authorities=certs/ca/ca.crt - xpack.security.http.ssl.verification_mode=certificate - xpack.security.transport.ssl.enabled=true - xpack.security.transport.ssl.key=certs/elastic/elastic.key - xpack.security.transport.ssl.certificate=certs/elastic/elastic.crt - xpack.security.transport.ssl.certificate_authorities=certs/ca/ca.crt - xpack.security.transport.ssl.verification_mode=certificate # CONFIG BELOW USES KEYSTORES #- xpack.security.transport.ssl.enabled=true #- xpack.security.transport.ssl.keystore.password=elastic #- xpack.security.transport.ssl.truststore.password=elastic #- xpack.security.transport.ssl.keystore.path=certs/elasticsearch01.p12 #- xpack.security.transport.ssl.verification_mode=certificate #- xpack.security.http.ssl.enabled=true #- xpack.security.http.ssl.keystore.password=elastic #- xpack.security.http.ssl.truststore.password=elastic #- xpack.security.http.ssl.keystore.path=certs/elasticsearch01.p12 #- xpack.security.http.ssl.verification_mode=certificate ports: - 9200:9200 volumes: - opendxp-enterprise-elastic:/usr/share/elasticsearch/data - opendxp-enterprise-elastic-certs:/usr/share/elasticsearch/config/certs deploy: resources: limits: cpus: '1' memory: '2G' kibana: container_name: kibana-10 image: kibana:8.4.3 ports: - 5601:5601 environment: - ELASTICSEARCH_HOSTS=https://elastic:9200 - XPACK_SECURITY_ENABLED=true - ELASTICSEARCH_USERNAME=kibana_system - ELASTICSEARCH_PASSWORD=somethingsecret # DISABLE LINES BELOW IF SSL IS NOT NEEDED! - ELASTICSEARCH_SSL_CERTIFICATEAUTHORITIES=config/certs/ca/ca.crt #- ELASTICSEARCH_SSL_CERTIFICATEAUTHORITIES=config/certs/ca/ca.crt #- ELASTICSEARCH_SSL_VERIFICATIONMODE=certificate #- SERVER_SSL_ENABLED=true #- SERVER_SSL_KEY=config/certs/kibana.key #- SERVER_SSL_CERTIFICATE=config/certs/kibana.crt #- SERVER_SSL_PASSWORD=kibana #- SERVER_SSL_KEYPASSPHRASE=kibana volumes: - opendxp-enterprise-elastic-certs:/usr/share/kibana/config/certs volumes: opendxp-enterprise-elastic: opendxp-enterprise-elastic-certs: ``` Use `docker-compose up -d` to run the configured stack. Also `docker compose logs -f` could be helpful to debug certain errors. --- ## Changelog(Elasticsearch-client) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [CHORE] Update branding names [#2](https://github.com/open-dxp/elasticsearch-client-bundle/pull/2) - [ENHANCEMENT] Add php 8.5 support [#3](https://github.com/open-dxp/elasticsearch-client-bundle/pull/3) - [CHORE] Update GitHub workflows: remove deprecated `cs_fixer_mode` option fro… [#4](https://github.com/open-dxp/elasticsearch-client-bundle/pull/4) ### 1.0.0 - [NEW FEATURE] Initial release --- ## Elasticsearch Client Bundle This bundle provides a central configuration and factory feature for creating elasticsearch clients to be used in other bundles. It allows to configure one or more elasticsearch clients with different configuration settings. The corresponding settings are then registered as services and can be injected into any services. Supported elasticsearch version: Elasticsearch 8 *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP Elasticsearch Client Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Installation Install bundle via composer ```bash composer require open-dxp/elasticsearch-client-bundle ``` This bundle is a standard symfony bundle. If not required and activated by another bundle, it can be enabled by adding it to the `bundles.php` of your application. ### Configuration The Configuration takes place in symfony configuration tree where multiple elasticsearch clients can be configured as follows. It is possible to configure one or more clients if necessary. By default, a `default` client with host set to `localhost:9200` is available and can be customized. For details on the configuration opens have a look at inline documentation via command `bin/console config:dump-reference OpenDxpElasticsearchClientBundle` Also see the [Elasticsearch Docs](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/connecting.html) for more information. ```yaml opendxp_elasticsearch_client: es_clients: default: hosts: ['elastic:9200'] username: 'elastic' password: 'somethingsecret' logger_channel: 'opendxp.elasicsearch' statistics: hosts: ['statistics-node:9200'] logger_channel: 'opendxp.statistics' #optional options ca_bundle: 'path/to/ca/cert' ssl_key: 'path/to/ssl/key' ssl_cert: 'path/to/ssl/cert' ssl_password: 'secretePW' ssl_verification: false #true is the default value http_options: proxy: 'http://localhost:8125' cloud_id: '123456789' api_key: 'secret-apikey' cloud: cloud_id: '123456789' api_key: 'secret-apikey' ``` ### Integration into other Bundles For each of the configured clients, a client service is registered in the symfony container. The naming schema follows `opendxp.elasticsearch_client.`. These client services can be injected into and used by other services then. *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore elasticsearch-client (312f317 / v1.1.0)](https://github.com/pimcore/elasticsearch-client/tree/312f31746aec6051941f9ef1913cb30d30b4ea07), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Google Analytics In order to use Google Analytics you have to install the OpenDxpGoogleMarketingBundle. Make sure to enable it in the bundles.php ### Disabling the Google Analytics Code Injecting the code can be disabled by calling `disable()` in the `GoogleAnalyticsCodeListener`. For example, in a controller action in an autowired controller: ```php disable(); // ... } } ``` Of course you can also inject the listener into a custom service. ### Customizing the tracking code If you want to influence the generated tracking code, you have multiple possibilities to do so. The tracker code is divided into multiple code blocks which can be expanded and altered individually. As reference, please see: - the definition of available blocks in the [Tracker implementation](../src/Tracker/Tracker.php#L32) - the [templates](../templates/Analytics/Tracking/Google/Analytics) which are rendered when generating the tracking code and which define where the content of each blocks is rendered #### Adding code to a block The central part of the Google tracking is the `OpenDxp\Bundle\GoogleMarketingBundle\Tracker\Tracker` class which is defined as service and which provides a `addCodePart()` method which allows you to add custom code snippets to a specific block: ```php addCodePart('console.log("foo");'); // append a part to a specific block $tracker->addCodePart('console.log("foo");', Tracker::BLOCK_BEFORE_TRACK); // prepend a part to a specific block $tracker->addCodePart('console.log("foo");', Tracker::BLOCK_AFTER_TRACK, true); // you can also add the code only for a specific site // if you want to do so, you need to pass a SiteId object which identifies a tracking site $tracker->addCodePart('console.log("foo");', Tracker::BLOCK_AFTER_TRACK, true, SiteId::forMainDomain()); // ... } } ``` #### Influencing generated code through the `CODE_TRACKING_DATA` event Before the tracking code is generated, the `GoogleAnalyticsEvents::CODE_TRACKING_DATA` event is dispatched which gives you full control over the generated code: ```php 'onTrackingData' ]; } public function onTrackingData(TrackingDataEvent $event): void { // append data to a block $event->getBlock(Tracker::BLOCK_AFTER_TRACK)->append([ 'console.log("foo");' ]); // completely empty the after track block $event->getBlock(Tracker::BLOCK_AFTER_TRACK)->setParts([]); // the data array is the data which will be passed to the template $data = $event->getData(); $data['foo'] = 'bar'; $event->setData($data); // you can also completely replace the rendered template $event->setTemplate('@App/Analytics/Tracking/Google/trackingCode.html.twig'); } } ``` #### Overriding the rendered template As you can see in the sample event listener above, you can change the template which will be used for the tracking code. If you set a custom template, you can extend the core one and just override the blocks you want: ```twig {# templates/Analytics/Tracking/Google/Analytics/universalTrackingCode.html.twig #} {% extends "@OpenDxpGoogleMarketing/Analytics/Tracking/Google/Analytics/universalTrackingCode.html.twig" %} {% block track %} {{ parent() }} console.log('hello world'); {% endblock %} {% block afterScriptTag %} {{ parent() }} {% endblock %} ``` --- ## Google Services Integration Menus and buttons may vary depending on the current GUI version ### Console - APIs * [https://console.developers.google.com/project](https://console.developers.google.com/project) * *Menu:* `[+ Create project]` * Project name: **project-sk** * *Menu:* `Select project` * *Menu:* `IAM & admin` / `Service accounts` * `[+ Create service account]` * Service account name: **api_id** (email) * Role: App Engine / **App Engine Viewer** * `[Done]` * `[+ Create service account]` * Service account name: **api_email** (email) * Role: Project / **Viewer** * Create key (optional): `[Create key]` * Key type: **JSON** * `Download json` * `[Done]` * *Menu:* `APIs & Services` / `Credentials` * `[+ Create credential]` > `API key` * **s_api_key** > `[Restrict key]` * Name: **s_api_key** * IP addresses (web servers, ...) * Add an item: **80.241.1.1** * **b_api_key** > `[Restrict key]` * Name: **b_api_key** * HTTP referrers (web sites) * Add an item: **\*.l-project**, **\*.project.sk** * *Menu:* `APIs & services` / `Library` - **Google Analytics API** > `[Enable]` - **Custom Search API** > `[Enable]` ### Analytics * [https://analytics.google.com/](https://analytics.google.com/) * *Menu:* `Administrator` * `[Create new account]` * Account name: **project** * Web * Website name: **project.sk** * Website URL: **https://www.project.sk/** * Industry category: * Reporting Time Zone: * `Get Tracking ID`: **track_id** * *Menu:* `All website data` * `View settings` * Search tracking: ON * query parameter = **q** * `User Management` * `[+]` > `Add user` * Add email address = **api_email** * Read and analysis * `[+]` > `Add user` * Add email address: owner@gmail.com * Read and analysis ### Configuring Google Services in OpenDXP **APIs** * copy **JSON** to `/config/opendxp/google-api-private-key.json` * edit `/config/config.yaml` or use System Settings in admin interface * services/google/client_id = **api_id** * services/google/email = **api_email** * services/google/simple_api_key = **s_api_key** * services/google/browser_api_key = **b_api_key** **Analytics** * *OpenDXP admin menu:* `Marketing` / `Marketing settings` * *Tab:* `Google Analytics` * Track-ID = **track_id** * Advanced Integration > Profile = **All website data** * *Tab:* `Google Search Console` * Verification Filename = **html_ver** --- ## Changelog(Google-marketing) ### 1.1.1 - [CHORE] Show placeholders instead of example credentials in the commented default configuration - [CHORE] Check dependencies, code and commits for security issues ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [CHORE] Update branding names [#6](https://github.com/open-dxp/google-marketing-bundle/pull/6) - [ENHANCEMENT] Add php 8.5 support [#7](https://github.com/open-dxp/google-marketing-bundle/pull/7) - [CHORE] Remove unused POEditor export workflow and refine PHP-CS-Fixer workfl… [#8](https://github.com/open-dxp/google-marketing-bundle/pull/8) - [CHORE] Simplify PHP-CS-Fixer workflow by removing `cs_fixer_mode` parameter [#9](https://github.com/open-dxp/google-marketing-bundle/pull/9) ### 1.0.1 - [CHORE] Update README for clarity on OpenDXP independence and licensing [#4](https://github.com/open-dxp/google-marketing-bundle/pull/4) - [BUGFIX] Fix extension alias [#5](https://github.com/open-dxp/google-marketing-bundle/pull/5) ### 1.0.0 - [NEW FEATURE] Initial release - [ENHANCEMENT] PHP 8.4 & Symfony 7.3 [#1](https://github.com/open-dxp/google-marketing-bundle/pull/1) - [CHORE] Fix tests [#2](https://github.com/open-dxp/google-marketing-bundle/pull/2) --- ## Installation(Newsletter) ##### Minimum Requirements * open-dxp/opendxp:^1.0 ### Installation Process Install bundle via composer: ```bash composer require open-dxp/newsletter-bundle ``` Enable bundle in `config/bundles.php`: ```php return [ ... OpenDxp\Bundle\NewsletterBundle\OpenDxpNewsletterBundle::class => ['all' => true], ... ]; ``` Install bundle via console: ```bash php bin/console opendxp:bundle:install OpenDxpNewsletterBundle ``` Check if the bundle has been installed: ```bash php bin/console opendxp:bundle:list +---------------------------------+---------+-----------+----+-----+-----+ | Bundle | Enabled | Installed | I? | UI? | UP? | +---------------------------------+---------+-----------+----+-----+-----+ | OpenDxpNewsletterBundle | ✔ | ✔ | ❌ | ✔ | ❌ | +---------------------------------+---------+-----------+----+-----+-----+ ``` ##### Config options ```yaml #### SYMFONY MAILER TRANSPORTS framework: mailer: enabled: true transports: opendxp_newsletter: smtp://user:pass@smtp.example.com:port messenger: routing: 'OpenDxp\Bundle\NewsletterBundle\Messenger\SendNewsletterMessage': opendxp_core ``` ```yaml opendxp_newsletter: source_adapters: defaultAdapter: opendxp_newsletter.document.newsletter.factory.default csvList: opendxp_newsletter.document.newsletter.factory.csv sender: name: 'Han Solo' email: 'han.solo@opendxp.com' return: name: 'Luke Skywalker' email: 'luke.skywalker@opendxp.com' debug: email_addresses: 'han.solo@opendxp.com,luke.skywalker@opendxp.com' use_specific: true default_url_prefix: 'https://my-host.com' ``` ### Uninstallation Uninstalling the bundle does not clean up `newsletter` documents only the predefined document types. Before uninstalling make sure to remove or archive all dependent documents. You can also use the following command to clean up you database. Create a backup before executing the command. All data will be lost. ```bash bin/console opendxp:document:cleanup newsletter ``` ### Best Practice and Example See [Newsletter Config](./19_Newsletter_Config.md) for a complete example and how to set up your newsletter. ### Document Types This bundle introduces a new document type: | Type | Description | |--------------------------------------------|----------------------------------------------| | [Newsletter](./05_Newsletter_Documents.md) | Like an email but specialized for newsletter | ### OpenDxp Twig Extensions This bundle also adds a new twig extension. For more information checkout the main documentation | Test | Description | |-------------------------------|-------------------------------------------| | `opendxp_document_newsletter` | Checks if object is instanceof Newsletter | --- ## Newsletter Document Newsletter documents are the way to create and send newsletters directly within OpenDxp. They are based on the normal OpenDxp documents and therefore support everything as pages do - starting from MVC pattern and template creation to document composing within OpenDxp backend with areas, drag&drop etc. ### Additional Settings Newsletter documents provide following additional settings compared to default documents: ![Newsletter settings](./img/newsletter_settings.png) - Subject: Subject of the newsletter. - From: From-Address of the newsletter. As fallback, OpenDxp system settings are used. - Add Tracking Parameters to Links: Adds tracking parameters to all links within the newsletter. - Tracking Parameter 'Source', 'Medium', 'Name': Values for the tracking parameters. - Sending Mode: - Single (Render every Mail individually): Document is rendered for each recipient - necessary for individual newsletters. - Batch (Render Mail only once): Document is rendered once - no individual newsletters possible, but faster. ### Newsletter Sending The Newsletter Sending Panel provides the functionality for sending the newsletter. ![Newsletter sending panel](./img/newsletter_sending_panel.png) #### Address Source Adapter The Address Source Adapter is responsible for extracting the email addresses the newsletter should be sent to. It has to be selected before another action can take place. Currently following adapters ship with OpenDxp. It is easily possible to integrate custom adapters - see section below. - Default Object List: Extracts email addresses based on OpenDxp objects. - CSV List: Uses a CSV as source for email addresses. - Column from a report: Uses a custom report as source for email adresses. - Please make sure to enable the OpenDxpCustomReportsBundle before you use this feature. #### Test Sending Once a Address Source Adapter is selected, a test sending to a specified email address can be made with the button `Send Test-Newsletter`. #### Sending the Newsletter With `Send Newsletter Now` the newsletter is sent to all recipients. The sending itself is done based on the system settings of OpenDxp. There you also can configure an external SMTP sending service for mass mail sending. ### Creating a Custom Address Source Adapter It is easily possible to implement custom address source adapter. Following files have to be created: - JavaScript Class: This class defines the user interface in the sending panel. It has to be located in the namespace `opendxp.document.newsletters.addressSourceAdapters`, named like the adapter (e.g. `opendxp.document.newsletters.addressSourceAdapters.myAdapter`) and implement the methods `initialize`, `getName`, `getLayout` and `getValues`. As sample see [csvList](https://github.com/open-dxp/newsletter-bundle/blob/1.x/public/js/document/newsletters/addressSourceAdapters/csvList.js) - PHP Class: This class is the server side implementation of the adapter. It is responsible for retrieving and preparing the email addresses. It needs to implement the interface `AddressSourceAdapterInterface`. As sample see [csvList](https://github.com/open-dxp/newsletter-bundle/blob/1.x/src/Document/Newsletter/AddressSourceAdapter/CsvList.php). - Register your Adapter Source Factory as Service. If you are using a very simple Adapter Source, you can use the DefaultFactory ```yml app.document.newsletter.factory.myAdapter: class: OpenDxp\Document\Newsletter\DefaultAddressSourceAdapterFactory arguments: - 'App\Document\Newsletter\AddressSourceAdapter\MyAdapter' ``` - If you are using a more complex Source Adapter, you can create your own Factory by implementing the interface OpenDxp\Document\Newsletter\AddressSourceAdapterFactoryInterface - Add your Adapter Factory to the configuration: ```yml opendxp_newsletter: source_adapters: myAdapter: app.document.newsletter.factory.myAdapter ``` --- ## Newsletter Configuration ### General The main advantage is that you can send completely customized / personalized newsletters by using all the data stored in the system (products, ...). The content of the e-mail is rendered individually for every recipient (the user object is available in the action and view), this gives you the absolute freedom for your content. The newsletter framework is just a wrapper for existing functionality in OpenDxp. This makes it easy to use and gives you all the advantages OpenDxp offers you. The newsletter content is assembled in an *Newsletter* document. Therefore, your newsletter template is just a simple action and view. In the view you can use all features known from the other document types (page, snippets...). As mentioned before, this document is rendered individually for every user, that makes it possible to include content depending on the user data. If your *mailing list* is stored in objects, you can find few special data components for that case. ### Basic Setup **Class definition** The class definition below shows how to build a class used by the newsletter list. ![Class definition for the newsletter](./img/newsletter_class_definition.png) The purpose of the fields gender, *firstname*, *lastname* and *email* should be clear. *newsletterActive* and *newsletterConfirmed* are used to save the state of the user (also used by the frontend framework). The *newsletterActive* data component tells the newsletter framework whether to send the newsletter to this user or not. The *newsletterConfirmed* component is used for double opt-in (provided by the frontend framework). **Only if newsletterActive and newsletterConfirmed are ticked the user in the object receives the newsletter.** The *newsletterConfirmed* cannot be set in the admin interface, the reason is simple: the frontend framework logs every activity to *Notes & Events* including the IP etc. from the user, so it's possible to track every modification the user has made to his profile. Now if the editor is able to change this important setting the audit trail is pitted and it's not clear why the user receives the newsletter. Of course it's possible to change the value via API (eg. in importers). #### URL prefix for static assets You are able to configure the default URL prefix in order to make sure, that your static assets (e.g. images or CSS files) are getting prefixed correctly. ```yml opendxp_newsletter: default_url_prefix: 'https://my-host.com' ``` ### Newsletter Frontend Framework Once you have setup your data class, it's possible to use the newsletter frontend framework. This simple framework allows you to create a hassle free subscribe/confirm/unsubscribe workflow. ### Example #### Controller For example, `\NewsletterController`: `src/Controllers/NewsletterController.php` ```php request->all(); $success = false; if ($newsletter->checkParams($params)) { try { $params['parentId'] = 1; // default folder (home) where we want to save our subscribers $newsletterFolder = Model\DataObject::getByPath('/crm/newsletter'); if ($newsletterFolder) { $params['parentId'] = $newsletterFolder->getId(); } $user = $newsletter->subscribe($params); // user and email document // parameters available in the email: gender, firstname, lastname, email, token, object // ==> see mailing framework $newsletter->sendConfirmationMail($user, Model\Document\Email::getByPath('/en/advanced-examples/newsletter/confirmation-email'), ['additional' => 'parameters']); // do some other stuff with the new user $user->setDateRegister(new \DateTime()); $user->save(); $success = true; } catch (\Exception $e) { echo $e->getMessage(); } } return $this->render('Newsletter/subscribe.html.twig', ['success' => $success]); } public function confirmAction(Request $request): Response { $success = false; $newsletter = new Newsletter('person'); // replace "person" with the class name you have used for your class above (mailing list) if ($newsletter->confirm($request->request->getString('token'))) { $success = true; } return $this->render('Newsletter/confirm.html.twig', ['success' => $success]); } public function unsubscribeAction(Request $request): Response { $newsletter = new Newsletter('person'); // replace "person" with the class name you have used for your class above (mailing list) $unsubscribeMethod = null; $success = false; if ($request->request->getString('email')) { $unsubscribeMethod = 'email'; $success = $newsletter->unsubscribeByEmail($request->request->getString('email')); } if ($request->request->getString('token')) { $unsubscribeMethod = 'token'; $success = $newsletter->unsubscribeByToken($request->request->getString('token')); } return $this->render('Newsletter/unsubscribe.html.twig', [ 'success' => $success, 'unsubscribeMethod' => $unsubscribeMethod, ]); } } ``` #### Views The subscribe action view: `templates/Newsletter/subscribe.html.twig` ```twig {% extends 'layout.html.twig' %} {% set request = app.request %} {% block content %} {% if not success %} {% if request.get('submit') %}
{{ 'Sorry, something went wrong, please check the data in the form and try again!'|trans }}


{% endif %}

{% else %}
{{ 'Success, Please check your mailbox!'|trans }}
{% endif %} {% endblock %} ``` The confirm action view: `templates/Newsletter/confirm.html.twig` ```twig {% extends 'layout.html.twig' %} {% block content %} {% if not success %}

{{ 'Sorry, something went wrong, please sign up again!'|trans }}

{% else %}

{{ 'Thanks for confirming your address!'|trans }}

{% endif %} {% endblock %} ``` The unsubscribe action view: `templates/Newsletter/unsubscribe.html.twig` ```twig {% extends 'layout.html.twig' %} {% set request = app.request %} {% block content %} {% if not success %} {% if unsubscribeMethod %}
{% if unsubscribeMethod == 'email' %} Sorry, we don't have your address in our database. {% else %} Sorry, your unsubscribe token is invalid, try to remove your address manually: {% endif %}
{% endif %}

{% else %}

{{ 'Unsubscribed'|trans }}

{% endif %} {% endblock %} ``` #### Confirmation E-Mail The confirmation e-mail (See: `\OpenDxp\Tool\Newsletter::sendConfirmationMail`) is a simple e-mail document. In this document the following Twig parameters are available: * `{{ firstname }}` * `{{ lastname }}` * `{{ token }}` * `{{ email }}` * `{{ gender }}` * `{{ object.someMethod }}` In the document editmode you can create the confirmation email by choosing **Add email -> Standard-Mail**: ![Create email document](./img/newsletter_create_document_confirmation.png) To define the confirmation URL in editmode. You have to add controller / action and token information. You can then simply append the token to the URL in you template by referencing to the `token` variable e.g. `{{ token }}`. #### Sending Newsletters ##### Create a Newsletter Document To send a newsletter you need an email document, which is used as content for the newsletter (nothing special to consider). In this document the following Twig parameters are available: * `{{ firstname }}` * `{{ lastname }}` * `{{ token }}` * `{{ email }}` * `{{ gender }}` * `{{ object.someMethod }}` ![Create newsletter document](./img/newsletter_create_newsletter_document.png) ##### Get UserData in the Email Template ```php $userObject = $this->getParam('object'); $firstname = $userObject->getFirstname(); $lastname = $userObject->getLastname(); ... ``` #### Send a Test Message In newsletter documents, there is additional tab in the top panel, it's called *Newsletter Sending Panel*. It's a good practise to check newsletter before it would be used with real emails. ![Send a test newsletter](./img/newsletter_test_sending.png) #### Send the Newsletter To send the newsletter you have to specify a source adapter. We're going to use customer objects as a source, therefore we need to choose the *Default object list* adapter. And the *Customer* class as the source. Choose the adapter: ![Newsletter - objects list source adapter](./img/newsletter_objects_list_adapter.png) Choose the class: ![Newsletter - objects list source adapter class](./img/newsletter_objects_list_adapter_class.png) and at the end, just push the **Send Newsletter Now** button. --- ## Changelog(Newsletter) ### 1.1.0 - [BUGFIX] The payloads and results of the handlers are no longer registered as services. A container that makes its services public failed on them - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] OpenDxp / Admin-Bundle ^1.4 support added ### 1.0.1 - [ENHANCEMENT] PHP 8.5 support added ### 1.0.0 - [NEW FEATURE] Initial release --- ## Migrating to OpenDXP(Newsletter) ### Migrating from `pimcore/newsletter-bundle:1.3` to `open-dxp/newsletter-bundle:1.x` - PHP namespace changed to `OpenDXP\Bundle\NewsletterBundle` - top-level configuration node changed to `opendxp_newsletter` - Bundle name changed to `OpenDxpNewsletterBundle` --- ## Installation of the Number Sequence Generator Bundle ### Bundle Installation To install the Number Sequence Generator Bundle, follow the three steps below: 1) Install the required dependencies: ```bash composer require open-dxp/number-sequence-generator-bundle ``` 2) Make sure the bundle is enabled in the `config/bundles.php` file. The following lines should be added: ```php return [ // ... OpenDxp\Bundle\NumberSequenceGeneratorBundle\OpenDxpNumberSequenceGeneratorBundle::class => ['all' => true], // ... ]; ``` 3) Install the bundle: ```bash bin/console opendxp:bundle:install OpenDxpNumberSequenceGeneratorBundle ``` --- ## Changelog(Number-sequence-generator) ### 1.1.0 - [BUGFIX] [MIGRATION] The installer marked an installation with the old name of the bundle from before OpenDXP. The bundle then counted as not installed. A migration marks it with the current name - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [ENHANCEMENT] Add php 8.5 support [#2](https://github.com/open-dxp/number-sequence-generator-bundle/pull/2) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update workflows & files [#1](https://github.com/open-dxp/number-sequence-generator-bundle/pull/1) --- ## Number Sequence Generator Bundle *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP Number Sequence Generator Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Installation - Execute: `$ bin/console opendxp:bundle:install OpenDxpNumberSequenceGeneratorBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\NumberSequenceGeneratorBundle\Migrations'` ### Continues numbers Generates continous numbers for example for order numbers or customer numbers. ```php public function exampleAction(OpenDxp\Bundle\NumberSequenceGeneratorBundle\Generator $generator) { /* * Generates the next order number (increments current order number by 1) * If no order number was generated before it will start with 10000 */ $next = $generator->getNext('ordernumber', 10000); /* * Receive the current order number without incrementing the counter. */ $current = $generator->getCurrent('ordernumber'); /* * Sets the order number to 35017 in the database. */ $generator->setCurrent('ordernumber', 35017); } ``` ### Random numbers (either numeric or alphanumeric) Generates unique random numbers. ```php public function __construct(Generator $generator) { $this->generator = $generator; } public function generateCode() { $code = $this->generator->generateCode("vouchercode", \OpenDxp\Bundle\NumberSequenceGeneratorBundle\RandomGenerator::ALPHANUMERIC, 32); } ``` ### Documentation Overview - [Installation](./doc/01_Installation.md) *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore number-sequence-generator (04fc42e / v2.0.1)](https://github.com/pimcore/number-sequence-generator/tree/04fc42e91eeadc54e9f30b5793c4faed7a409373), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.ch. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Changelog(Object-merger) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.1 - [ENHANCEMENT] PHP 8.5 Support added ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update & Fix workflows [#1](https://github.com/open-dxp/object-merger-bundle/pull/1) --- ## Migrating to OpenDXP(Object-merger) ### Migrating from `pimcore/object-merger` to `open-dxp/object-merger-bundle` * Renamed bundle to `OpenDxpObjectMergerBundle` * Moved bundle to new namespace `OpenDxp\Bundle\ObjectMergerBundle` --- ## Object Merger Bundle *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP ObjectMerger Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** The object merger plugin allows to show the difference between two objects and merge them field by field. For the keyvalue datatype the field is even broken down into key/value pairs. Open the object selection menu via the Extras | Compare Objects menu item. ![Screenshot](doc/menu.png) You can either paste the full path of the two objects or use the magnifier class to open the search dialog. ![Screenshot](doc/choose.png) Ideally, the two objects should be of the same type. ![Screenshot](doc/select.png) Click on the Compare button to show the difference between the two objects. You will see a tab for every language. If the objects don't contain any localized fields the tab label will be "Default". The number inside the parenthesis indicate the current number of differences. The first row shows the full path of both objects. Below that all object fields are listed. There are six columns: * The exclamation mark indicates that the field content differs * The second column is the field label * The (grayed out) button indicates the field type * The fourth column summarizes the content of the source object. Changes are always applied from the left object to the right object. * The button in the middle allows to overwrite the data of the target object with the one from the source object. The button turns into a "revert" button which will undo the change. * The sixth column summarizes the new content of the target object. ![Screenshot](doc/diff1.png) Click on save to apply the changes. *** ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](doc/Migrating_to_OpenDXP.md). ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore object-merger (685231e / v4.1.0)](https://github.com/pimcore/object-merger/tree/685231eb6198eb3b764903bcdba4c7b3d26a605e), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.ch. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Installation of the Opensearch Client Bundle :::info This bundle is only supported on OpenDxp Core Framework 1.x. ::: ## Bundle Installation To install the Opensearch Client Bundle, follow the three steps below: 1) Install the required dependencies: ```bash composer require open-dxp/opensearch-client ``` 2) This bundle is a standard symfony bundle. If not required and activated by another bundle, it can be enabled by adding it to the `bundles.php` of your application. ```php use OpenDxp\Bundle\OpenSearchClientBundle\OpenDxpOpenSearchClientBundle; // ... return [ // ... OpenDxpOpenSearchClientBundle::class => ['all' => true], // ... ]; ``` --- ## Configuration of the Opensearch Client Bundle The Configuration takes place in symfony configuration tree where multiple opensearch clients can be configured as follows. It is possible to configure one or more clients if necessary. By default, a default client with host set to localhost:9200 is available and can be customized. Also see the [Opensearch Docs](https://opensearch.org/docs/latest/clients/php/) for more information. ```yaml opendxp_open_search_client: clients: default: hosts: ['https://opensearch:9200'] password: 'admin' username: 'somethingsecret' logger_channel: 'opendxp.opensearch' log_404_errors: true #Enable logging of 404 errors (default: false) statistics: hosts: ['https://statistics-node:9200'] logger_channel: 'opendxp.statistics' # Optional options ssl_key: 'path/to/ssl/key' ssl_cert: 'path/to/ssl/cert' ssl_password: 'somethingsecret' ssl_verification: false #true is the default value aws: aws_region: 'eu-central-1' aws_service: 'es' aws_key: 'aws_key' aws_secret: 'aws_secret' ``` --- ## Usage of the Opensearch Client Bundle The Opensearch Client can be injected into any service setting the argument of your service: ```yaml App\Service\MyService: arguments: $openSearchClient: '@opendxp.open_search_client.' ``` The Client can then be used in your service: ```php OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP Opensearch Client Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Compatibility with OpenSearch | OpenDXP Client Version | OpenSearch Version | |------------------------|--------------------| | ^1.0 | 1.0.0 - 2.1.0 | ### Documentation Overview - [Installation](./doc/01_Installation.md) - [Configuration](./doc/02_Configuration.md) - [Usage](./doc/03_Usage.md) *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore opensearch-client (82f1635 / v1.1.1)](https://github.com/pimcore/opensearch-client/tree/82f1635f4ef883ef1e4c9b9e39e2ba94d6e53d95), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Changelog(Payment-provider-paypal-smart-payment-button) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Updated license files [#1](https://github.com/open-dxp/payment-provider-paypal-smart-payment-button-bundle/pull/1) --- ## Payment Provider PayPal Smart Payment Buttons *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP E-Commerce Framework Payment Provider - PayPal Smart Payment Buttons is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Installation Install latest version with Composer: ```bash composer require open-dxp/payment-provider-paypal-smart-payment-button-bundle ``` Enable bundle via console: ```bash php bin/console opendxp:bundle:enable OpenDxpPaymentProviderPayPalSmartPaymentButtonBundle php bin/console opendxp:bundle:install OpenDxpPaymentProviderPayPalSmartPaymentButtonBundle ``` For configuration details see further below. For additional information of PayPal API credentials see [API Docs](https://developer.paypal.com/docs/api/overview/) ### Configuration The Payment Manager is responsible for implementation of different Payment Provider to integrate them into the framework. For more information about Payment Manager, see [Payment Manager Docs](https://github.com/open-dxp/opendxp/blob/1.x/doc/Development_Documentation/10_E-Commerce_Framework/13_Checkout_Manager/07_Integrating_Payment.md). Configure payment provider in the `opendxp_ecommerce_config.payment_manager` config section: ```yaml opendxp_ecommerce_framework: payment_manager: payment_manager_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\PaymentManager providers: paypal: provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\Payment\PayPalSmartPaymentButton profile: sandbox profiles: sandbox: client_id: client_secret: # defines, if payment caputure should take place automatic or manual, default is automatic capture_strategy: automatic # defines mode of PayPal API, default value is sandbox mode: sandbox # defines PayPal application context for shipping, default value is NO_SHIPPING # see https://developer.paypal.com/docs/api/orders/v2/#definition-application_context shipping_preference: NO_SHIPPING # defines PayPal application context for user action, default value is PAY_NOW # see https://developer.paypal.com/docs/api/orders/v2/#definition-application_context user_action: PAY_NOW live: client_id: client_secret: mode: live ``` ### Implementation Integrate the PayPal payment button to your view template Integrate PayPal payment button and overwrite a few methods like in the sample. At least `createOrder` and `onApprove` need to be overwritten. ```php
``` 4) Create a startPaymentAction in your controller Initialize checkout manager, call `startOrderPaymentWithPaymentProvider` of the payment implementation. It is creating an order at PayPal and its response is the default PayPal response, which need to be returned as a json response of the action. ```php //in your payment controller, e.g. startPaymentAction public function startPaymentAction() { // ... some other stuff $paymentConfig = new AbstractRequest($config); $response = $checkoutManager->startOrderPaymentWithPaymentProvider($paymentConfig); $checkoutManager = Factory::getInstance()->getCheckoutManager($cart); $paymentInformation = $checkoutManager->initOrderPayment(); $payment = $checkoutManager->getPayment(); $config = [ 'return_url' => $returnUrl, 'cancel_url' => $cancelUrl . 'payment?error=cancel', 'OrderDescription' => 'My Order ' . $order->getOrdernumber() . ' at opendxp.io', 'InternalPaymentId' => $paymentInformation->getInternalPaymentId() ]; $paymentConfig = new AbstractRequest($config); $response = $checkoutManager->startOrderPaymentWithPaymentProvider($paymentConfig); return new \Symfony\Component\HttpFoundation\JsonResponse($response->getJsonString(), 200, [], true); } ``` 5) Handle Response of PayPal In handle response just call `handlePaymentResponseAndCommitOrderPayment` of checkout manager. It does the rest - which is checking at PayPal if payment was authorized by the payer and committing the order. Depending on your settings (see below), the payment is also automatically captured. If not you need to capture the payment manually by calling `$payment->executeDebit()`. ```php public function handleResponseAction() { // ... do some stuff $checkoutManager = Factory::getInstance()->getCheckoutManager($cart); $params = array_merge($request->query->all(), $request->request->all()); $order = $checkoutManager->handlePaymentResponseAndCommitOrderPayment($params); // optional to clear payment // if this call is necessary depends on payment provider and configuration. // its possible to execute this later (e.g. when shipment is done) // $payment = $checkoutManager->getPayment(); // $paymentStatus = $payment->executeDebit(); // $orderAgent = Factory::getInstance()->getOrderManager()->createOrderAgent($order); // $orderAgent->updatePayment($paymentStatus); // ... check order state and redirect user to error page or order success page } ``` #### Further Information For further information and/or more custom integrations, also have a look at following resources: * [PayPal Developer Documentation](https://developer.paypal.com/docs/checkout/) * [PayPal Rest APIs](https://developer.paypal.com/docs/api/overview/) * [PayPal PHP SDK](https://github.com/paypal/PayPal-PHP-SDK) *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore payment-provider-paypal-smart-payment-button (9992d59 / v2.0.1)](https://github.com/pimcore/payment-provider-paypal-smart-payment-button/tree/9992d59badb8f8c04b8193ac0c224e4891adcc77), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2025 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Changelog(Payment-provider-unzer) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [CHORE] Require PHP 8.3 or 8.4. The Unzer SDK does not support PHP 8.5 yet ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Update bundle files [#1](https://github.com/open-dxp/payment-provider-unzer-bundle/pull/1) --- ## Payment Provider Unzer *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP E-Commerce Framework Payment Provider - Unzer is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Unzer Web Integration To integrate Unzer web integration see [Unzer docs](https://docs.unzer.com/integrate/web-integration) and follow following steps. The basic flow goes as following: - Unzer gets initialized via java script and depending on activated payment methods additional form fields are injected to view template. - User selects payment method and enters additional information if necessary (e.g. credit card information). - Information is submitted to unzer, payment transaction is started and payment id is returned. - Payment id is submitted back to OpenDxp and OpenDxp payment transaction is started. - If necessary user is redirected to payment provider (e.g. Paypal). - If user comes back from external payment site, payment state is checked server-to-server between OpenDxp and unzer and if successful order is committed and user is redirected to success page. ### Installation Install latest version with composer: ```bash composer require open-dxp/payment-provider-unzer-bundle ``` Enable bundle via console: ```bash php bin/console opendxp:bundle:enable OpenDxpPaymentProviderUnzerBundle php bin/console opendxp:bundle:install OpenDxpPaymentProviderUnzerBundle ``` ### Configuration Setup payment provider in e-commerce framework configuration. The access keys you find in Unzer documentation (or you will get them from Unzer for production integrations). ```yml unzer: provider_id: OpenDxp\Bundle\EcommerceFrameworkBundle\PaymentManager\Payment\Unzer profile: sandbox profiles: sandbox: publicAccessKey: s-pub-2a10gsZJ2IeiiK80Wh68qrOzu4IZse6k privateAccessKey: s-priv-2a10BF2Cq2YvAo6ALSGHc3X7F42oWAIp ``` Payment Information: Order payment section "Payment Informations" stores information about every payment trial by Customer. Add additional fields in "PaymentInfo" fieldcollection, so that Order Manager stores information in Order object: ![PaymentInfo Additional Data](./doc/img/unzer_paymentinfo.png) **Create View Template** Create view template for payment method selection. This view template - needs to include a javascript and a css from Unzer. - has a list of all provided payment methods and depending of the payment method additional form elements. - includes a java script that handles data communication the data to Unzer. - has an additional form that submits successful payment information (Unzer payment id) back to OpenDxp. **Sample template with Creditcard, Paypal and Sofort** ```twig {% do opendxp_head_link().appendStylesheet('https://static.unzer.com/v1/unzer.css') %} {% do opendxp_head_script().appendFile('https://static.unzer.com/v1/unzer.js') %} {% do opendxp_inline_script().appendFile(asset('static/js/payment.js')) %} {# custom payment js, see below #}

{{ 'checkout.payment' | trans }}

``` **Sample Javascript (payment.js) with Creditcard, Paypal and Sofort** ```javascript $(document).ready(function() { let unzerInstance = new unzer(_config.accessKey, {locale: 'en-GB'}); let $errorHolder = $('#error-holder'); let Card = unzerInstance.Card(); // Rendering input fields Card.create('number', { containerId: 'card-element-id-number', onlyIframe: false }); Card.create('expiry', { containerId: 'card-element-id-expiry', onlyIframe: false }); Card.create('cvc', { containerId: 'card-element-id-cvc', onlyIframe: false }); let ccForm = document.getElementById('cc-form'); let submitPaymentResultForm = document.getElementById('js-submit-payment-result'); // General event handling let buttonDisabled = {}; let submitButton = document.getElementById('submit-button'); submitButton.disabled = true; let successHandler = function(data) { console.log('success'); data.method = data.method ? data.method : 'card'; $('.js-payment-method-hidden').val(data.method); $('.js-payment-id-hidden').val(data.id); submitPaymentResultForm.submit(); }; let errorHandler = function(error) { console.log('error'); $errorHolder.html(error.message); }; Card.addEventListener('change', function(e) { if (e.success) { buttonDisabled[e.type] = true; submitButton.disabled = false; $errorHolder.html('') } else { buttonDisabled[e.type] = false; submitButton.disabled = true; $errorHolder.html(e.error) } submitButton.disabled = !(buttonDisabled.number && buttonDisabled.expiry && buttonDisabled.cvc); }); ccForm.addEventListener('submit', function(event) { event.preventDefault(); console.log('creditcard form submit'); Card.createResource() .then(successHandler) .catch(errorHandler) }); $('#js-redirect-payment-method-paypal').on('click', function(e){ e.preventDefault(); var Paypal = unzerInstance.Paypal(); Paypal.createResource() .then(successHandler) .catch(errorHandler) }); $('#js-redirect-payment-method-paypal-sofort').on('click', function(e){ e.preventDefault(); var Sofort = unzerInstance.Sofort(); Sofort.createResource() .then(successHandler) .catch(errorHandler) }); }); ``` 5) **Create Controller Action for Payment Selection** The only special thing in this controller action is to get public access key out of payment provider and assign it to the template. ```php /** * @Route("/checkout-payment", name="shop-checkout-payment") * * @param Factory $factory * @return array */ public function checkoutPaymentAction(Factory $factory) { $cartManager = $factory->getCartManager(); $cart = $cartManager->getOrCreateCartByName('cart'); $checkoutManager = $factory->getCheckoutManager($cart); $paymentProvider = $checkoutManager->getPayment(); $accessKey = ''; if($paymentProvider instanceof Unzer) { $accessKey = $paymentProvider->getPublicAccessKey(); } return [ 'cart' => $cart, 'accessKey' => $accessKey ]; } ``` 6) **Create Controller Action for Starting Payment** To this action the paymentId of Unzer is submitted after payment transaction is started successfully on client side. Additionally an error action is defined to extract the error messages from Unzer. ```php /** * @Route("/checkout-start-payment", name="shop-checkout-start-payment") * * @param Request $request * @param Factory $factory * @return RedirectResponse */ public function startPaymentAction(Request $request, Factory $factory, LoggerInterface $logger) { try { $cartManager = $factory->getCartManager(); $cart = $cartManager->getOrCreateCartByName('cart'); /** @var CheckoutManagerInterface $checkoutManager */ $checkoutManager = $factory->getCheckoutManager($cart); $paymentInfo = $checkoutManager->initOrderPayment(); /** @var OnlineShopOrder $order */ $order = $paymentInfo->getObject(); $paymentConfig = new UnzerRequest(); $paymentConfig->setInternalPaymentId($paymentInfo->getInternalPaymentId()); $paymentConfig->setPaymentReference($request->get('paymentId')); $paymentConfig->setReturnUrl($this->generateUrl('shop-commit-order', ['order' => $order->getOrdernumber()], UrlGeneratorInterface::ABSOLUTE_URL)); $paymentConfig->setErrorUrl($this->generateUrl('shop-checkout-payment-error', [], UrlGeneratorInterface::ABSOLUTE_URL)); $response = $checkoutManager->startOrderPaymentWithPaymentProvider($paymentConfig); if($response instanceof UrlResponse) { return new RedirectResponse($response->getUrl()); } } catch (\Exception $e) { $this->addFlash('danger', $e->getMessage()); $logger->error($e->getMessage()); return $this->redirectToRoute('shop-checkout-payment'); } } /** * @Route("/payment-error", name = "shop-checkout-payment-error" ) */ public function paymentErrorAction(Request $request, LoggerInterface $logger) { $logger->error('payment error: ' . $request->get('merchantMessage')); if($clientMessage = $request->get('clientMessage')) { $this->addFlash('danger', $clientMessage); } return $this->redirectToRoute('shop-checkout-payment'); } ``` 7) **Create Controller Action for Commit Order** Finally commit order and redirect user to order success page. ```php /** * @Route("/payment-commit-order", name="shop-commit-order") * * @param Request $request * @param Factory $factory * @param LoggerInterface $logger * @param Translator $translator * @param SessionInterface $session * @return RedirectResponse * @throws \OpenDxp\Bundle\EcommerceFrameworkBundle\Exception\UnsupportedException */ public function commitOrderAction(Request $request, Factory $factory, LoggerInterface $logger, Translator $translator, SessionInterface $session) { $order = OnlineShopOrder::getByOrdernumber($request->query->get('order'), 1); $cartManager = $factory->getCartManager(); $cart = $cartManager->getOrCreateCartByName('cart'); /** * @var CheckoutManagerInterface $checkoutManager */ $checkoutManager = $factory->getCheckoutManager($cart); try { $order = $checkoutManager->handlePaymentResponseAndCommitOrderPayment([ 'order' => $order ]); } catch(\Exception $e) { $logger->error($e->getMessage()); } if(!$order || $order->getOrderState() !== AbstractOrder::ORDER_STATE_COMMITTED) { $this->addFlash('danger', $translator->trans('checkout.payment-failed')); return $this->redirectToRoute('shop-checkout-payment'); } if (!$session->isStarted()) { $session->start(); } $session->set("last_order_id", $order->getId()); return $this->redirectToRoute('shop-checkout-completed'); } ``` ### Important Configuration Please make sure that `serialize_precision` is set to a very high value, or even better to `-1` in order to prevent rounding issues with the unzer sdk. For details also see https://docs.unzer.com/integrate/php-sdk/installation/#php-configuration *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore payment-provider-unzer (d76cca0 / v2.0.1)](https://github.com/pimcore/payment-provider-paypal-smart-payment-button/tree/d76cca089cd2c6a60b805409915a66b88918793c), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2025 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## OpenDxp Concepts for Personalization The following core concepts are the essential parts of OpenDxps personalization engine. ### Target Group It is recommended to group your visitors into target groups. They help you to keep track and have an overview about what content you need to provide and about which content is delivered to what visitor. So, a *Target Group* is an entity which is used to personalize content for. Target groups are defined centrally, have an unique name and can have a description. ![Target Groups](../img/user_docs/target-groups.jpg) See [Define Target Groups](./03_How_to_Personalize_Content/01_Define_Target_Groups.md) for further information. ### Global Targeting Rule *Global Targeting Rules* define the rule set based on which visitor profiling and content personalization takes place. Thus they allow to assign target groups, redirect the visitor to certain pages or inject code snippets (special java scripts, etc.) to the response based on behavioral conditions. Available conditions are Browser, Country, GeoPoint, Device, Language, Operating System, Referring Site, Search Engine, Target Group, Time On Site, URL and Visited Pages Before. They can be combined with boolean operators (AND, OR, NOT) and brackets to archive complex conditions. ![Targeting Rules Conditions](../img/user_docs/targeting-rules-conditions.jpg) Each targeting rule has name, may have a description and a scope: * **Hit**: Actions are executed on every request. * **Session**: Actions are executed once a session. * **Session (with variables)**: Actions are executed once a session and when visitor information changes, e.g. every time when assigned target groups of current visitor change. * **Visitor**: Actions are executed once per visitor. The session expiry depends on the used storage engine. In default configuration the session expires when browser is closed. See [Dev Docs](../02_Development_Documentation/09_Targeting_Storage.md) for details. The visitor is identified via a browser cookie (named `_pc_vis`). As long as this cookie is available, a visitor is identified as unique. See [Visitor Profiling](./03_How_to_Personalize_Content/03_Visitor_Profiling.md) and [Create Personalized Content](./03_How_to_Personalize_Content/05_Create_Personalized_Content.md) for further information. ### Personalized Document Content OpenDxp Documents provide the possibility to create varying content variants for each defined target group. Once a target group is selected, all content elements within the document can be overwritten and personalized. For not overwritten content elements, the content is inherited from the default variant of the document. When delivering content to the visitor, the best matching variant is picked by OpenDxp. *Best matching* is in this case is the variant of the target group with highest assignment count of the current visitor that has content set. ![Personalized Document Content](../img/user_docs/personalized-documents.jpg) See [Create Personalized Content](./03_How_to_Personalize_Content/05_Create_Personalized_Content.md) and [Deliver Personalized Content](./03_How_to_Personalize_Content/07_Deliver_Personalized_Content_and_Debug.md) for further information. --- ## Define Target Groups It is recommended to group your visitors into target groups. They help you to keep track and have an overview about what content you need to provide and about which content is delivered to what visitor. Thus, *Target Groups* are the core entities for personalizing content. Target groups are defined centrally, have an unique name, can have a description and may be deactivated. ![Target Groups](../../img/user_docs/target-groups.jpg) The threshold is needed in combination with [visitor profiling](./03_Visitor_Profiling.md). Based on the behavior, a visitor can get target groups assigned. Thus a visitor can belong to multiple target groups with a specific assignment count (= times a target group got assigned and represents a certain relevance). Once the assignment count passes the configured threshold, the visitor really belongs to the target groups and it is used for personalized content. See [visitor profiling](./03_Visitor_Profiling.md) for further information on profiling visitors and assigning target groups. --- ## Visitor Profiling Visitor profiling is the process of getting to know visitors and assign one or multiple target groups based on their behaviour. The result of the ongoing profiling process is a set of target groups, that are assigned with a certain assignment relevance to the current visitor. ![Associated Target Groups](../../img/user_docs/target-groups-assignment.jpg) OpenDxp provides two ways for profiling visitors based on their behavior. #### Associate Target Groups directly with OpenDxp Documents It is possible to associate OpenDxp documents directly with target groups. This can be configured in `Settings` tab of each document as soon as there are target groups defined in the system. ![Associate Target Groups with Documents](../../img/user_docs/target-groups-documents.jpg) Once one or more target groups are associated with a document, the selected target groups are assigned to the visitor and the assignment count is increased by one, each time this document opened by the user. #### Use Global Targeting Rules to Assign Target Groups *Global Targeting Rules* define a rule set based on which visitors can be profiled. Multiple conditions can be combined to complex criteria for assigning target groups to the current visitor based on their behavior. ![Targeting Rules Action](../../img/user_docs/targeting-rules-action.jpg) When assigning a target group via global targeting rules, also a assignment weight can be specified. This increases the assignment count of the target group respectively. For more fine-grained profiling possibilities see our [Customer Management Framework](https://github.com/open-dxp/customer-data-framework/tree/1.x/README.md) with its [Customer Segment functionality](https://github.com/open-dxp/customer-data-framework/tree/1.x/doc/11_CustomerSegments.md) and its [extensions to the OpenDxp targeting engine](https://github.com/open-dxp/customer-data-framework/tree/1.x/doc/30_Personalization.md). --- ## Create Personalized Content The simplest way to create personalized content is with OpenDxp documents. They provide the possibility to create varying content variants for each defined target group. ![Personalized Document Content](../../img/user_docs/personalized-documents.jpg) Once a target group is selected, all content elements within the document can be overwritten and personalized. To overwrite a certain element, use context menu of the element and select overwrite. ![Personalized Document Content](../../img/user_docs/personalized-documents-overwrite.jpg) All not overwritten content elements are greyed and inherit the content from the default variant of the document. --- ## Deliver Personalized Content Once target groups are defined, visitor profiling rules are set and personalized content is created, it is time to deliver the personalized content to the right people. OpenDxp provides two ways to deliver personalized Content: #### Delivering Personalized Content with Documents When a document is delivered to the visitor, the best matching variant is picked by OpenDxp based on following rule: * If the visitor has only one assigned target group and content exists for that target group, the personalized variant for that target group will be used * If the visitor has multiple assigned target groups, they will be sorted by their assignment count. The first target group in the sorted list which has personalized content for the document will be used. This logic is repeated for every document and sub-request. This means you can show personalized content for a given target group on a document, but have content for different target groups in snippets or renderlets rendered on the same page. You can see which target groups were applied to which document in the profiler. As you can see in the screenshot below, the main document used the target group `basketball` while the footer snippet was rendered with the target group `female`. ![Targeting Profiler Target Groups](../../img/targeting_profiler_target_groups.png) For further debug information see below. #### Delivering Personalized Content with Global Targeting Rules In addition to OpenDxp document delivery, global targeting rules provide two actions with further possibilities to deliver personalized content to the visitor. 1) **Redirect**: The visitor can be redirected when certain conditions match. E.g. redirect visitor on its first visit to your site to a special landing page. 2) **Code-Snippet**: The code snippet action allows to inject a code snippet to the response when certain conditions match. This opens up lots of possibilities such as restyling the page by injecting CSS, adding additional functionality by adding JS Snippets or even injecting whole HTML code blocks. ![Targeting Rule Code Snippet Action](../../img/user_docs/targeting-rules-action2.jpg) ### Verify What Happens - aka Debug The personalization configuration can become quite complex really quick. To get to know what happens, which rules matched for a certain request, which target groups are assigned and what data is collected, OpenDxp injects several information the Symfony profiler bar. ![Profiler Bar Popup](../../img/user_docs/profiler1.jpg) On the detail page you can find all information about matching targeting rules, assigned target groups, chosen target groups for document delivery, all stored visitor information and content of the visitor storage. ![Profiler Information](../../img/user_docs/profiler2.jpg) --- ## How to Personalize Content On the following pages you find a short tutorial for how to personalize content. As the OpenDxp behavioral targeting engine is very powerful and flexible, there are multiple ways to archive a result and the outlined way is just one of many. The typical workflow of personalizing content contains following steps: 1) [Define Target Groups](./01_Define_Target_Groups.md) 2) [Setup Visitor Profiling](./03_Visitor_Profiling.md) 3) [Create Personalized Content](./05_Create_Personalized_Content.md) 4) [Deliver Personalized Content](./07_Deliver_Personalized_Content_and_Debug.md) For a live demo with a predefined rule set see our [Demo](https://demo.opendxp.io). --- ## Examples for Personalization and Targeting The following pages show a few examples to better understand how things can be achieved with the OpenDxp targeting engine. All mentioned rules here are configured and set up in our [demo](https://demo.opendxp.io) and can be tested there. ### Visitor Profiling The result of the ongoing profiling process is a set of target groups, that are assigned with a certain assignment relevance to the current visitor. So visitor profiling rules are always some conditions that result in assignment of an target group. #### Learning about customer interests based on behaviour ###### Assign Target Groups to Documents If there is a document, directly associate this document with a target group. ![Tenant Switches Settings](../../img/user_docs/examples_technical-guy1.jpg) Every time a visitor visits that page, it gets the `technical-guy` target group assigned. Since one visit might be a coincidence, multiple visits might hint for a technical interest of that visitor. To filter out the coincidence visitors, a threshold can be defined at the target group. So not before the third visit, the target group is actually assigned to the visitors profile. ![Technical Guy Settings](../../img/user_docs/examples_technical-guy2.jpg) For a real-life example please have a look at our [public demo instance](https://demo.opendxp.io/en/More-Stuff/Demo-Features/Personalization). ###### Global Targeting Rules with simple Conditions & Actions Regular visits in a certain shopping category (e.g. football) indicate an interest in football. To track that information, add a global targeting rule with a URL condition and an action to assign the corresponding target group. To eliminate coincidence visits, e.g. an additional `time on site` condition can be added, like at the `profiling_football` targeting rule at the demo. ![Technical Guy Settings](../../img/user_docs/examples_football1.jpg) The action should be executed on every request that matches the criteria - so use the scope `Hit` here. By doing so, the assignment count of the target group gets increased every time and so a certain relevance for the target groups can be identified - e.g. visitor is more interested in football that in basketball. #### Guessing customer characteristics based on behaviour ###### Global Targeting Rule with more complex Conditions Similar to the category interest tracking, customer characteristics like favorite color or even gender can be guessed. To do so, add for example a targeting rule that tracks product filtering for blue products and assigns corresponding target groups like the `profiling_blue-lover` rule does in the demo. ![Profiling Blue Lover](../../img/user_docs/examples_bluelover.jpg) #### Classify customers based on behaviour ###### Identify regular customers In addition to collecting customer characteristics, you also could classify customers based on number of orders they made. For example once a new customer creates an additional order, it becomes a regular customer. See the `profiling_regular-customer` rule in the demo for details. ![Classify Regular Customer](../../img/user_docs/examples_regular-customer.jpg) In this case, it is important that the action is executed only once. Therefore choose `Visitor` as scope. ![Scope to Visitor](../../img/user_docs/examples_regular-customer2.jpg) These are only a few simple examples for visitor profiling with OpenDxps targeting engine. ### Personalize Content #### Personalize content using global targeting rules ###### Redirect visitor to a certain landing page One example for content personalization is to redirect a visitor to a special landing page that is answering this questions. In our demo the example `personalize_redirect-to-landingpage` redirects visitors with language german that visited 5 pages on our website to a landing page. ![Redirect to Landingpage](../../img/user_docs/examples_redirect.jpg) Of course this should happen not after every hit but only once per session, so scope is set to `session`. ###### Inject special content to mobile visitors Another use case could be, that special users (e.g. mobile users from a certain country) should see a slightly different layout. See the `personalize_device-mobile` rule of our demo how this can be archived by injecting additional CSS code to the page. ![Inject CSS](../../img/user_docs/examples_mobile-device.jpg) #### Personalized content documents The most common and most flexible way to customize content is to create customized variants of documents for certain target groups. See [Create Personalized Content](../03_How_to_Personalize_Content/05_Create_Personalized_Content.md) and [Deliver Personalized Content](../03_How_to_Personalize_Content/07_Deliver_Personalized_Content_and_Debug.md) for details. In our demo several different variants of the portal page are set up - e.g. for target groups `football`, `basketball`, `handball` and others. Just try archive the corresponding target groups and see what happens. ![Personalized Variant for Basketball](../../img/user_docs/examples_basketball.jpg) --- ## Visitor Info The `VisitorInfo` is the central data object which is passed to every part of the targeting system. A new `VisitorInfo` is created for every request and enriched with data throughout the matching process. Starting from an empty object, data will be added to the `VisitorInfo` from several components, making it hold all relevant targeting data for the current request. ### Visitor ID To identify returning visitors, the engine needs some kind of unique identificator which will be assigned to each visitor. This identificator, internally referred to as `visitor ID`, is expected to be generated or set by the browser and to be stored as a cookie. When creating a `VisitorInfo` the targeting engine tries to load a visitor ID from the `_pc_vis` cookie. This ID is (by default) generated by the frontend on event: * when loading a site with targeting enabled and no visitor ID was previously set, a random string is generated If you want to manually set the visitor ID in your frontend code you can do so with the following call which is exposed by the targeting JS implementation: ```js _ptg.api.setVisitorId('my-custom-visitor-id'); ``` The visitor ID will be used for every action where a unique identificator is needed, e.g. when identifying returning visitors or when persisting data for a specific visitor to a targeting storage. Upon setting a visitor ID, it is stored in 2 places of the user's browser: * a `_pc_vis` cookie * a `_ptg.user` local storage entry. This entry contains some persistent data about the user (e.g. an activity log and a list of previous visitor IDs) which may be used in later enhancements of the targeting framework. If the visitor ID cookie is missing but the local storage entry contains an ID that ID will be used to write a new cookie. ### Accessing the Visitor Info in your code Similar to the security token in Symfony's security system, you can fetch the current `VisitorInfo` from a `VisitorInfoStorage`. This storage is defined as service an can simply be injected into your services or used as controller action argument when your controllers are registered as service. You can just define the `VisitorInfoStorageInterface` as dependency and Symfony and the service configuration take care of the rest. As an example, a sample service working with the `VisitorInfo`: ```php visitorInfoStorage = $visitorInfoStorage; } public function getVisitorId(): ?string { // always check if there is a visitor info before trying to fetch it if (!$this->visitorInfoStorage->hasVisitorInfo()) { return null; } $visitorInfo = $this->visitorInfoStorage->getVisitorInfo(); return $visitorInfo->getVisitorId(); } } ``` And the matching service definition: ```yaml services: _defaults: autowire: true autoconfigure: true public: false # if using autowiring you're already set by just defining your service - the # type hint against the VisitorInfoStorageInterface is enough to enable autowiring App\Targeting\MyService: ~ # if you don't use autowiring you need to manually wire your dependency App\Targeting\MyService: arguments: $visitorInfoStorage: '@OpenDxp\Bundle\PersonalizationBundle\Targeting\VisitorInfoStorageInterface' ``` If your controllers are defined as services, you can make use of argument injection: ```php null ]; // always check if there is a visitor info before trying to fetch it if ($visitorInfoStorage->hasVisitorInfo()) { $visitorInfo = $visitorInfoStorage->getVisitorInfo(); $data['visitorId'] = $visitorInfo->getVisitorId(); } return new JsonResponse($data); } } ``` --- ## Conditions Conditions are logical blocks which can be combined with other conditions inside a target rule. A condition is expected to implement `match()` method which always returns a boolean. To implement a condition, you need to implement 2 parts: * A PHP class implementing the [`ConditionInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Condition/ConditionInterface.php). Have a look at [existing implementations](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Condition) to get an idea how to implement your own conditions. * A frontend JS class defining the admin UI for your condition. You can have a look at [this bundle's conditions](https://github.com/open-dxp/personalization-bundle/tree/1.x/public/js/settings/conditions.js) for UI examples and at the [Customer Management Framework](https://github.com/open-dxp/customer-data-framework/tree/1.x/src/Resources/public/js/opendxp/targeting/conditions.js) as example for a third-party integration. ### Implementing a Condition As stated before, a condition needs to implement the [`ConditionInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Condition/ConditionInterface.php). The most important method in the interface is the `match()` method which receives the current `VisitorInfo` instance and is expected to return a boolean which indicates if the condition matches or not. As an example let's build a condition which matches if the current time of the day is later than the configured one. E.g. if configured to `15:00`, the condition would start to match at `15:00` until midnight. Start by creating a condition class implementing the `ConditionInterface`. For simplicity's sake we just check the current hour, not the full time. ```php hour = $hour; } public static function fromConfig(array $config): self { $hour = $config['hour'] ?? null; if (!empty($hour)) { $hour = (int)$hour; } // build an instance from the config as configured // in the admin UI return new self($hour); } public function canMatch(): bool { // basic validation if the condition is able to match return null !== $this->hour && $this->hour >= 0 && $this->hour <= 23; } public function match(VisitorInfo $visitorInfo): bool { $hour = (int)(new \DateTime())->format('H'); return $hour >= $this->hour; } } ``` After implementing your condition, you need to register it to the system with the following configuration. The identifier `timeoftheday` will later be used from your JS implementation, so make sure you choose a unique name and to reuse the same name when implementing the JS class. ```yaml opendxp_personalization: targeting: conditions: timeoftheday: App\Targeting\Condition\TimeOfTheDay ``` #### Building a Condition Instance When an instance of your condition is build, by default the [`ConditionFactory`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/ConditionFactory.php) will call the static `fromConfig()` method with the data configured in the admin UI. Avoid injecting any services or custom data into your condition and use the data provider system instead to add data to the `VisitorInfo`. However, if you need more control over how your condition is built you can either: * overwrite the `ConditionFactory` service definition (not recommended) and implement your own logic instead of calling `fromConfig()` * or handle the `TargetingEvents::BUILD_CONDITION` event and set an instance of your condition on the event. The `BuildConditionEvent` contains all the info you need to build a condition instance (type, class name, config data). If you set a condition on the event via `setCondition`, the standard logic will be omitted and the event condition will be used. ### Condition Data If your condition needs any outside data, implement the [`DataProviderDependentInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/DataProviderDependentInterface.php) and define a list of data provider keys which need to be set on the `VisitorInfo` before matching. We'll enhance our `TimeOfTheDay` condition on the [Data Providers](./05_Data_Providers.md) chapter. For further examples, you can take a look at [existing core conditions](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Condition). ### Condition Variables An important part are [variable conditions](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Condition/VariableConditionInterface.php) which support the `session_with_variables` rule matching scope. A condition implementing this interface is expected to return an array of the variables which led to match the condition in the `getMatchedVariables()` method. This data will be used to determine if the rule was already applied with the exact same data. You should implement this interface whenever possible. To get started, you can use the [`AbstractVariableCondition`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Condition/AbstractVariableCondition.php) which contains helper methods to collect variable data. Make sure you build your data in a deterministic way (e.g. using the same order of keys in an array structure or the same format when serializing data) as a hash of this data is used to compare it to previous evaluations in order to decide if a rule needs to be applied. As example: the country condition sets the ISO country code which led to match as its data (based on GeoLocation). If a rule is executed in the `session_with_variables` scope the the country condition is the only condition on that rule, it won't be executed twice for the same resolved country. Taking our `TimeOfTheDay` condition, it can easily be enhanced to store variables. The variable we'll store will be the resolved current hour. ```php format('H'); if ($hour >= $this->hour) { $this->setMatchedVariable('hour', $hour); return true; } return false; } } ``` ### Admin UI To make your condition configurable, you need to create a JS class defining the admin interface for your condition. To do so, create a class extending `opendxp.bundle.personalization.settings.condition.abstract` and register it to the system by calling `opendxp.bundle.personalization.settings.conditions.register()`. Have a look at [this bundle's conditions](https://github.com/open-dxp/personalization-bundle/tree/1.x/public/js/settings/conditions.js) and the [Customer Management Framework](https://github.com/open-dxp/customer-data-framework/tree/1.x/src/Resources/public/js/opendxp/targeting/conditions.js) for examples. Start by adding a new JS file implementing the admin UI panel for your condition: ```javascript // /public/js/targeting/conditions.js (function () { 'use strict'; opendxp.bundle.personalization.settings.conditions.register( 'timeoftheday', Class.create(opendxp.bundle.personalization.settings.condition.abstract, { getName: function () { return 'Time of the Day'; }, getPanel: function (panel, data) { var id = Ext.id(); var storeData = []; for (var i = 0; i < 24; i++) { storeData.push([i, i]); } return new Ext.form.FormPanel({ id: id, forceLayout: true, style: 'margin: 10px 0 0 0', bodyStyle: 'padding: 10px 30px 10px 30px; min-height:40px;', tbar: opendxp.bundle.personalization.settings.conditions.getTopBar(this, id, panel, data), items: [ { name: 'hour', fieldLabel: 'Hour', xtype: 'combo', store: storeData, mode: 'local', width: 300, value: ('undefined' !== typeof data.hour) ? data.hour : 0, editable: false, triggerAction: 'all' }, { xtype: 'displayfield', hideLabel: true, value: 'Matches if the current hour is >= the configured one.', cls: 'opendxp_extra_label' }, { xtype: 'hidden', name: 'type', value: 'timeoftheday' // the identifier chosen before when registering the PHP class } ] }); } }) ); }()); ``` As soon as you [configured OpenDxp to load the newly created file](https://docs.opendxp.io/docs/core-framework/Extending_OpenDxp/Bundle_Developers_Guide/Loading_Service_Definitions) you should see your new condition in the list of available conditions: ![Time of the Day Condition](../img/targeting_custom_condition_timeoftheday.png) --- ## Data Providers A data provider is a service implementing the [`DataProviderInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/DataProvider/DataProviderInterface.php). Components (e.g. conditions) which implement the [`DataProviderDependentInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/DataProviderDependentInterface.php) can define a set of data providers they depend on, triggering the data provider to load its data before the component is used. A data provider does not directly return its value, but is expected to set it on the `VisitorInfo` instance instead. As best practice, the core data providers expose their storage key as constant. This constant is used to store and retrieve the data from the `VisitorInfo` storage. As example: the [GeoIP](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/DataProvider/GeoIp.php) data provider defines the [GeoIP::PROVIDER_KEY](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/DataProvider/GeoIp.php#L28) constant which is used when storing and retrieving the data. ### Implementing a Data Provider A data provider is simply a class implementing the `DataProviderInterface` which is registered as service. Basically a data provider can do anything, however the core data providers do the following: * They store their information on a storage key which is exposed as constant * They always set their content key. If no data can be resolved (e.g. GeoIP is unable to resolve a location), `null` is set. * Before loading data, core providers check if there already is an entry for the own storage key and abort loading if that is the case. As an example let's assume the `DateTime` used in the `TimeOfTheDay` condition (as implemented on the [Conditions](./03_Conditions.md) page) is more complex than a simple `new DateTime()`, i.e. because the date is fetched from a third party or involves calculation logic. Instead of creating it inside the condition which does not have access to services we move it to a reusable `DateTime` data provider which stores the current `DateTime` on the `VisitorInfo`. ```php has(self::PROVIDER_KEY)) { // abort if there already is data for this provider return; } // assume creating the date is more complex (e.g. involves other services // which are injected via DI) $visitorInfo->set(self::PROVIDER_KEY, new \DateTimeImmutable()); } } ``` Next, register your new data provider as service: ```yaml services: _defaults: autowire: true autoconfigure: true public: false App\Targeting\DataProvider\DateTime: ~ ``` And register the provider to the targeting engine with its provider key: ```yaml opendxp_personalization: targeting: data_providers: datetime: App\Targeting\DataProvider\DateTime ``` ### Consuming a Data Provider To consume a data provider, implement the `DataProviderDependentInterface` in your components and specify a list of data providers to use. As an example, let's update the `TimeOfTheDay` condition to fetch the current `DateTime` from our new provider: ```php get(DateTime::PROVIDER_KEY); if (!$dateTime) { // provider did not provide a valid date - nothing to match against return false; } $hour = (int)$dateTime->format('H'); if ($hour >= $this->hour) { $this->setMatchedVariable('hour', $hour); return true; } return false; } } ``` As you can see, instead of creating a new `DateTime` instance, the condition now expects an instance on the `DateTime::PROVIDER_KEY` storage on the `VisitorInfo`. The targeting engine takes care of loading every provider the condition depends on before starting to match. The `DataProviderDependentInterface` can not only be used from conditions, but also from action handlers and other data providers (a data provider can depend on another data providers' data). --- ## Action Handlers After a targeting rule matched it executes one or more actions as configured in the admin UI. These actions are actually executed by action handlers, which are services implementing the [`ActionHandlerInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/ActionHandler/ActionHandlerInterface.php). As with conditions, an action handler consists of 2 parts: * A PHP class implementing the [`ActionHandlerInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/ActionHandler/ActionHandlerInterface.php). Have a look at [existing implementations](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Targeting/ActionHandler) to get an idea how to implement your own action handlers. * A frontend JS class defining the admin UI for your action handler as shown on the actions tab of a targeting rule. You can have a look at [OpenDxp's core actions](https://github.com/open-dxp/personalization-bundle/tree/1.x/public/js/settings/actions.js) for UI examples and at the [Customer Management Framework](https://github.com/open-dxp/customer-data-framework/tree/1.x/src/Resources/public/js/opendxp/targeting/actions.js) as example for a third-party integration. ### Implementing an Action Handler As example, we'll implement a simple `Log` action handler which will log each matched rule with a configured log level. The action handler is a normal service which can depend on other services (as we do with the logger here). You can't rely on a visitor ID being set or a rule being passed. The visitor ID might be inexistent on the first request to the site and action handlers might be executed from outside the matching engine without passing a rule. Always check those values before using them! ```php logger = $logger; } public function apply(VisitorInfo $visitorInfo, array $action, Rule $rule = null): void { $level = $action['level'] ?? 'info'; $this->logger->log( $level, 'Matched target rule {ruleName} for visitor ID {visitorID} with config {config}', [ 'visitorID' => $visitorInfo->hasVisitorId() ? $visitorInfo->getVisitorId() : '(no visitor ID)', 'ruleName' => $rule ? $rule->getName() : '(no rule)', 'config' => json_encode($action) ] ); } } ``` Next, register your action handler as service. **Note:** we're using autowiring here to make sure the logger is automatically injected. If you don't use autowiring, enhance the service definition accordingly. ```yaml services: _defaults: autowire: true autoconfigure: true public: false App\Targeting\ActionHandler\Log: ~ ``` As last step, register the action handler to the targeting engine. Make sure the identifier is unique to your provider as you'll need to use it when implementing the admin UI JS part. ```yaml opendxp_personalization: targeting: action_handlers: log: App\Targeting\ActionHandler\Log ``` #### Postponed Actions If your action handler needs to apply data in a later stage of the request/response cycle it can register an `action` on the `VisitorInfo` which can be consumed later. Currently only the `response` action scope is defined which is executed in the `onKernelResponse` event, but more action scopes might be added in the future. Have a look at the [CodeSnippet](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/ActionHandler/CodeSnippet.php) action handler as example. It registers an action via `$visitorInfo->addAction()` and implements the `ResponseTransformingActionHandlerInterface::transformResponse()` which is called by the targeting engine for every action registered with the `response` scope. ### Admin UI To make your action handler appear in the admin UI, you need to create and register a JS class defining the admin interface for your action. Create a class extending `opendxp.settings.targeting.action.abstract` and register it to the system by calling `opendxp.bundle.personalization.settings.actions.register()`. Have a look at [this bundle's actions](https://github.com/open-dxp/personalization-bundle/tree/1.x/public/js/settings/actions.js) and the [Customer Management Framework](https://github.com/open-dxp/customer-data-framework/tree/1.x/src/Resources/public/js/opendxp/targeting/actions.js) for examples. Start by adding a new JS file implementing the admin UI panel for your action: ```javascript // public/js/targeting/actions.js (function () { 'use strict'; opendxp.bundle.personalization.settings.actions.register( 'log', Class.create(opendxp.bundle.personalization.settings.action.abstract, { getName: function () { return 'Log'; }, getPanel: function (panel, data) { var id = Ext.id(); return new Ext.form.FormPanel({ id: id, forceLayout: true, style: 'margin: 10px 0 0 0', bodyStyle: 'padding: 10px 30px 10px 30px; min-height:40px;', tbar: opendxp.bundle.personalization.settings.actions.getTopBar(this, id, panel), items: [ { name: 'level', fieldLabel: 'Level', xtype: 'combo', store: [ ['debug', 'Debug'], ['info', 'Info'], ['notice', 'Notice'], ['warning', 'Warning'], ['error', 'Error'], ['critical', 'Critical'], ['alert', 'Alert'], ['emergency', 'Emergency'] ], mode: 'local', width: 300, value: ('undefined' !== typeof data.level) ? data.level : 'info', editable: false, triggerAction: 'all' }, { xtype: 'hidden', name: 'type', value: 'log' } ] }); } }) ); }()); ``` As soon as you [configured OpenDxp to load the newly created file](https://docs.opendxp.io/docs/core-framework/Extending_OpenDxp/Bundle_Developers_Guide/Loading_Service_Definitions) you should see your new action in the list of available actions: ![Log Action](../img/targeting_custom_action_log.png) --- ## Targeting Storage [TOC] To persist data between requests, the targeting engine makes use of a targeting storage service which is responsible for persisting the given data to a storage. In general, the storage always receives an instance of the `VisitorInfo` it should store/retrieve data for and a `scope` which defines how data is handled. There are 2 fixed scopes which are used depending on what is needed: | Scope | Description | |-----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `session` | Valid for the current session, expires afterwards. Depending on the implementation, a session is either defined by a timeout of inactivity or by natively being handled by the storage system. E.g. the DB and Redis storage handle expiration by expiring data after a certain amount of time while Session and Cookie storage just make use of the session and cookie lifetime. | | `visitor` | Valid for the whole lifetime of the visitor. When a visitor returns with its unique ID, its data will still be usable while session data would have expired. | ### Configuring the Targeting Storage The targeting storage needs to be defined as service and its service ID needs to be configured with the following config entry: ```yaml opendxp_personalization: targeting: storage_id: OpenDxp\Bundle\PersonalizationBundle\Targeting\Storage\CookieStorage ``` ### Implement a Custom Targeting Storage Basically, a targeting storage is a class implementing the [`TargetingStorageInterface`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Storage/TargetingStorageInterface.php) which is registered as service. Details how to handle data varies heavily on the underlying storage, but you can take the [core storages](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Storage) as starting point. ### Core Storage Implementations OpenDxp implements different storage engines which each has its pros and cons. In general it is recommended to start with the default implementation - **JWT signed cookie** - and subsequently choose the engine which fits your requirements best. In the future more storage implementations are planned which combine features of multiple engines together, e.g. a storage handling multiple backends which are selected depending on if the visitor already has a visitor ID or not. #### Cookie (default) Stores data in a cookie in the user's browser. Can either be used with a plaintext cookie or with a JWT signed one to make sure the cookie data isn't being tampered with. The cookie storage delegates the actual cookie write/read operation to a `CookieSaveHandler` which does the actual cookie work. Below is an overview of save handlers: | Handler | Description | Notes | |-----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------| | `JWT` (default) | Stores cookie data as JWT signed JSON using the `kernel.secret` parameter to sign and verify the data. This is done to make sure the data can't be altered on the client side to inject malicious data into the targeting engine. | | | `JSON` | Stores cookie data as JSON string. | Use only for testing! | To change the save handler, override the [service definition](https://github.com/open-dxp/personalization-bundle/tree/1.x/config/targeting.yaml#L24) and set your own handler. Note that using plain text cookie data is inherently insecure and can open vulnerabilities by injecting malicious data into the client cookie. Use only for testing! Default session scope timeout: 30 minutes. This is also enforced in the JWT handler by setting an expiration value for the signed data to the same timeout as the cookie. This means even if somebody changes the cookie lifetime on the client side the data will still expire when loaded on the backend. Pros * Easy to use as no additional config is needed and it can store data without needing a visitor ID * Fast and easy to debug Cons * Cookie size is limited and bloats requests - can only be used when the amount of generated targeting data is limited and implementations take care of keeping data to a minimum. * Inherently insecure when used with an unsigned cookie. #### Db Stores data in the database. Default session scope timeout: 30 minutes Pros * Easy to use as no additional config is needed Cons * Can only store data when a visitor ID is present as the ID is part of the primary key * DB can fill up quickly - not to be used on large sites #### Redis Stores data in a redis DB. To use this storage, define a service using the storage implementation as class and add connection details to the service definition. An example is shipped with the [core service definitions](https://github.com/open-dxp/personalization-bundle/tree/1.x/config/targeting.yaml#L35). Default session scope timeout: 30 minutes Pros * Can efficiently handle large amounts of data * Natively supports data expiration Cons * Can only store data when a visitor ID is present as the ID is part of the key * Needs a dedicated Redis DB independent of the cache one (needs to be configured on the service definition) #### Session Stores data in the session. Default session scope timeout: PHP session timeout To use the session storage, an additional config entry is needed as the session listeners are disabled by default for performance reasons: ```yaml opendxp_personalization: targeting: # enable session support session: enabled: true # use the session storage storage_id: OpenDxp\Bundle\PersonalizationBundle\Targeting\Storage\SessionStorage ``` Pros * Easy to use as no additional config is needed * Can store data without a visitor ID Cons * Can't persistently store data for a visitor * Session size is limited * Slow depending on session storage * Might not work properly in conjunction with full page caches. OpenDxp's full page cache is disabled when the session contains targeting data, but if using something else it might be difficult to handle. Use with care when using full page caches! --- ## Frontend JavaScript When targeting is enabled, a snippet of JavaScript in injected into every response. This snippet contains some information needed by the frontend regarding the application state (e.g. if debug mode is enabled) and includes the script [`opendxp/static6/js/frontend/targeting.js`](https://github.com/open-dxp/personalization-bundle/blob/1.x/public/js/targeting.js) which handles the frontend behaviour of the targeting engine (e.g. exposes an API to set the visitor ID). The whole targeting logic is handled inside the `window._ptg` object. The frontend code provides a couple of extension points which are documented on this page. ### Setting a custom Visitor ID The `targeting.js` exposes a method to set a visitor ID programmatically. By doing so, the visitor ID will be set and stored in the visitor ID cookie which is delivered to the backend. ```js _ptg.api.setVisitorId('my-custom-visitor-id'); ``` Make sure to use a unique visitor ID for each visitor! ### Change/extend the code snippet injected into the Response The code which is injected into the response is generated by the [`TargetingCodeGenerator`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/Code/TargetingCodeGenerator.php) which fires a [TargetingEvents::TARGETING_CODE](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Event/TargetingEvents.php#L30) event. This event can be used to influence data and the used template which is used to render the code snippet: ```php 'onTargetingCode', ]; } public function onTargetingCode(TargetingCodeEvent $event): void { // add code to a code block (see TargetingCodeGenerator and the default // template for a list of blocks and their location) $event ->getBlock(TargetingCodeGenerator::BLOCK_BEFORE_SCRIPT) ->append([ 'console.log("Custom targeting code");' ]); // completely override the rendered template $event->setTemplate('@App/Targeting/targetingCode.html.twig'); } } ``` The listener above sets a custom template which can either extend the core one or define a completely custom output: ```twig {# templates/Targeting/targetingCode.html.twig #} {% extends '@OpenDxpPersonalization/Targeting/targetingCode.html.twig' %} {% block beforeScriptTag %} {{ parent() }} {% endblock %} ``` ### Frontend Data Providers Some conditions or data providers might need data from the frontend. To make this possible, a backend implementation can call `$visitorInfo->addFrontendDataProvider()` during the matching process to inform the frontend that it needs data from a specific provider. These frontend data providers need to be implemented and registered to the frontend JS and are expected to deliver their data to the backend in some way (e.g. by storing data in a cookie or by sending it through an async request). Currently, this feature is only sparsely used, but the [`GeoLocation`](https://github.com/open-dxp/personalization-bundle/tree/1.x/src/Targeting/DataProvider/GeoLocation.php) data provider which can read the visitor location from browser geolocation data informs the frontend that it needs data from the `geolocation` frontend data provider. This information is added to the browser response, triggering the `targeting.js` to execute this frontend data provider. The data provider in turn stores its data as cookie which is consumed by the (backend) data provider on the next request. #### Implementing a Custom Frontend Data Provider Simply register your frontend data provider on the `window._ptg.dataProviders` object before `targeting.js` is loaded. As example a simple provider which does nothing more than logging the current user agent to the console: ```js // /public/js/targeting/frontend.js (function () { window._ptg = window._ptg || {}; window._ptg.dataProviders = window._ptg.dataProviders || {}; window._ptg.dataProviders.userAgent = function() { console.log('The current user agent is ' + navigator.userAgent); }; }()); ``` Taking the example listener above, we use a custom code snippet template to load our script: ```twig {# templates/Targeting/targetingCode.html.twig #} {% block targetingScript %} {{ parent() }} {% endblock %} ``` To actually execute the provider, add the following call somewhere in your matching process (e.g. while loading data from a data provider): ```php $visitorInfo->addFrontendDataProvider('userAgent'); ``` --- ## Development Documentation The following section describes the technical concepts and aspects of the OpenDxp targeting engine. For usage description and feature listing see your [user docs](../01_Usage/01_Concepts.md) first. ### Setup You need to enable targeting either by setting the following config ```yaml opendxp_personalization: targeting: enabled: true ``` or using the cookie `opendxp_targeting_enabled=1`. if you'd like to use geo-related conditions in your targeting rules it's necessary to configure the underlying data provider first. #### Configuring the MaxMind GeoIP Data Provider Follow the [official instructions](https://dev.maxmind.com/geoip/geoipupdate/) for obtaining and updating the GeoIP database. Store the database file at the location of your choice, the default location used by _geoipupdate_ is `/usr/share/GeoIP/GeoLite2-City.mmdb` Set the path to the database file in your `parameters.yaml` to enable the geo support in OpenDxp: ```yaml opendxp.geoip.db_file: /usr/share/GeoIP/GeoLite2-City.mmdb ``` ### Basic concepts | Concept | Description | |------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `VisitorInfo` | Contains run-time information on the current visitor and is used by all conditions and action handlers to collect/apply data. | | `DataProvider` | Can be used by other components such as conditions to fetch data about the current visitor. E.g. the `Device` data provider loads device info from the user-agent string. Data is only loaded on demand if really needed by a component. | | `Condition` | A condition which is being matched. Conditions are configured in the Admin UI for global targeting rules. | | `ActionHandler` | A targeting rule can have one or multiple actions which are executed when its conditions match. These actions are executed by an action handler. E.g. the `Redirect` action handler creates a `RedirectResponse` which is used to redirect the visitor to another page. | | `Storage` | Where data about the visitor is persisted to. Each storage implementation supports storage for the `session` and the `visitor` scope. Session scoped data is only valid for the current session - either defined by a expiry time or by technical implications of the storage (e.g. the Cookie storage just sets a session cookie for the session storage). Visitor data is valid for the lifetime of the visitor and should be persisted, but depending on the used storage (e.g. Session Storage) this might not be possible. Different storages exist, e.g. cookie, JWT signed cookie, DB, session and redis which all have their advantages and disadvantages. | | `Targeting Rule` | A condition/action combination executing one or more actions if a set of conditions match (similar to pricing rules in the ecommerce framework). Targeting rules are usually executed on every request but depending on their scope (hit, visitor, session, session with variables) this can be limited. | | `Target Group` | An entity which is used to target content for. A document/snippet can define personalized content for a specific target group (e.g. a special banner for a target group "Outdoor Interested"). By matching targeting rules and by configuring target groups to be tracked when visiting documents, a visitor will be assigned a list of target groups (they will be stored to storage and be added to the `VisitorInfo` object at runtime). When rendering the document, a `DocumentTargetingConfigurator` selects the content which matches best for the target groups which are available on the `VisitorInfo`. | ### VisitorInfo and Visitor ID When a request is handled, the targeting engine first creates a new `VisitorInfo` instance. This instance is a data container which will be used throughout the targeting process to store and pass data between different components of the system. See [Visitor Info](./01_Visitor_Info.md) for details. ### Target Rule Matching After building the `VisitorInfo` and resolving the visitor ID, the matching engine processes every defined targeting rule. Based on the rule's scope a rule might be skipped (e.g. a `session` rule is applied only once per session). Every condition gets the instance of the `VisitorInfo` and needs to decide if it matches its configured data. To fetch additional data about the visitor, a condition can request data from one or more `DataProvider` implementations. As an example the `Device` data provider is able to resolve and cache device info from the user agent string by using the `DeviceDetector` library. The `Operating System` condition just defines the `Device` data provider as dependency and can rely on the device data being added the `VisitorInfo` before matching. The targeting engine takes care of requesting data from a data provider only once per request, even if multiple conditions rely on its data. If a rule matches, a list of actions is applied. Example actions are issuing a redirect or assigning a target group to the current visitor. Actions (which are executed by action handlers) can request data from data providers in the same way as conditions. ### Targeting Storage Some data needs to be persisted between requests. To do so, the targeting implementations makes use of a `TargetingStorage` which implements a key-value store for targeting data. Data can be set for the `visitor` (valid for the whole lifetime of a visitor) or for the `session` level. When storing data to an external storage, the previously resolved visitor ID is used to store data for a specific visitor. Examples for data which is persisted to storage: * assigned target groups - either set from targeting rules or automatically tracked when visiting a document which defines target groups to apply (as set on the document settings tab) * already matched rules with `session` scope to avoid to repeatedly execute them for the same visitor * first request to site in the current session (e.g. to calculate the time on site) For further details see [Targeting Storage](./09_Targeting_Storage.md). ### Content Targeting After matching all rules, a `VisitorInfo` may have different assigned target groups. When rendering a document which has targeted content for multiple target groups, the following logic is applied to determine which version to use for the current visitor: * If the visitor has only one assigned target group and content exists for that target group, the personalized version for that target group will be used * If the visitor has multiple assigned target groups, they will be sorted by their assignment count. The first target group in the sorted list which has personalized content for the document will be used. This logic is repeated for every document and sub-request. This means you can show personalized content for a given target group on a document, but have content for different target groups in snippets or renderlets rendered on the same page. You can see which target groups were applied to which document in the profiler. As you can see in the screenshot below, the main document used the target group `basketball` while the footer snippet was rendered with the target group `female`. ![Targeting Profiler Target Groups](../img/targeting_profiler_target_groups.png) #### Manually applying Content Targeting The logic defined above can be applied to any document. Documents which are loaded through OpenDxp's standard routing and rendering features will be automatically configured, but you also manually configure any document to use personalized content by using the `DocumentTargetingConfigurator` service. As example, when handling a document inside a controller which is registered as service: ```php configureTargetGroup($document); //... } } ``` ### Extending the Targeting Engine The targeting engine is designed in a way to be easily extendable by third party code to extend and customize the engine's behaviour. See the following resources for further details: * [Conditions](./03_Conditions.md) * [Data Providers](./05_Data_Providers.md) * [Action Handlers](./07_Action_Handlers.md) * [Targeting Storage](./09_Targeting_Storage.md) * [Frontend Javascript](./11_Frontend_Javascript.md) ### Debugging Targeting Data As shown above, targeting date is added to the Symfony profiler. In addition you can enable a dedicated targeting toolbar which also works outside the `dev` environment when you are logged into the admin interface. The toolbar is only shown if a `opendxp_targeting_debug` cookie exists and is set and its value evaluates to true. You can set the cookie with the following [bookmarklet](https://en.wikipedia.org/wiki/Bookmarklet) (just drag the link to your bookmarks bar): * Enable OpenDxp Targeting Toolbar ### Opt-in for Targeting A user has the possibility to enable targeting at any time, by setting the following cookie `opendxp_targeting_enabled=1` . > Since privacy laws vary from country to country, we recommend that you consult with your legal team or company to check what needs to be done before using this features. --- ## Changelog(Personalization) ### 1.1.0 - [BUGFIX] The payloads and results of the handlers are no longer registered as services. A container that makes its services public failed on them - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.3 - [BUGFIX] Do not set the document again on kernel.controller [#5](https://github.com/open-dxp/personalization-bundle/pull/5) ### 1.0.2 - [ENHANCEMENT] Add admin-bundle 1.4 compatibility [#4](https://github.com/open-dxp/personalization-bundle/pull/4) ### 1.0.1 - [CHORE] Update branding names [#2](https://github.com/open-dxp/personalization-bundle/pull/2) - [ENHANCEMENT] Add php 8.5 support [#3](https://github.com/open-dxp/personalization-bundle/pull/3) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix tests [#1](https://github.com/open-dxp/personalization-bundle/pull/1) --- ## Installation(Personalization) ### Installation Process Install bundle via composer: ```bash composer require open-dxp/personalization-bundle ``` Enable bundle in `config/bundles.php`: ```php return [ ... OpenDxp\Bundle\PersonalizationBundle\OpenDxpPersonalizationBundle::class => ['all' => true], ... ]; ``` Install bundle via console: ```bash bin/console opendxp:bundle:install OpenDxpPersonalizationBundle ``` ##### Config :::info By default, targeting would be disabled. To enable it, you can either use the cookie `opendxp_targeting_enabled=1` or set the following config: ::: ```yaml opendxp_personalization: targeting: enabled: true ``` ### Uninstallation Before uninstalling the bundle, the `Target Group` references must be removed from DataObject classes, Custom services and Ecommerce Pricing Rules manually. --- ## Personalization Bundle OpenDXP provides a very powerful integrated behavioral targeting and personalization engine. With this toolkit, it is possible to profile visitors based on their behavior, assign target groups to them and provide personalized content to these target groups. This makes it possible to show your customers contextual, relevant, and personalized content. *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP Personalization Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** Before starting with Personalization you should know about the following OpenDXP concepts: * [Target Group](./doc/01_Usage/01_Concepts.md#target-group) * [Global Targeting Rule](./doc/01_Usage/01_Concepts.md#global-targeting-rule) * [Personalized Document Content](./doc/01_Usage/01_Concepts.md#personalized-document-content) After reading everything about the base concepts, you are [ready to get started with personalizing content](./doc/01_Usage/03_How_to_Personalize_Content/README.md). > For details on how to extend OpenDXP's targeting engine and use targeting information in custom modules > see our [Dev Docs](./doc/02_Development_Documentation/README.md) ### Features in a Nutshell - Add behavioral targeting and personalization to OpenDXP. - Allow defining target groups. - Set up visitor profiling with rules based on their behavior. - Allow creating personalized versions of documents for defined target groups. - Deliver personalized content to target groups. ### Documentation Overview ##### Usage Documentation * [OpenDXP Concepts for Personalization](./doc/01_Usage/01_Concepts.md) * [How to Personalize Content](./doc/01_Usage/03_How_to_Personalize_Content/README.md) * [Define Target Groups](./doc/01_Usage/03_How_to_Personalize_Content/01_Define_Target_Groups.md) * [Setup Visitor Profiling](./doc/01_Usage/03_How_to_Personalize_Content/03_Visitor_Profiling.md) * [Create Personalized Content](./doc/01_Usage/03_How_to_Personalize_Content/05_Create_Personalized_Content.md) * [Deliver Personalized Content](./doc/01_Usage/03_How_to_Personalize_Content/07_Deliver_Personalized_Content_and_Debug.md) * [Examples for Personalization and Targeting](./doc/01_Usage/05_Examples/README.md) ##### Development Documentation * [Installation](./doc/Installation.md) * [Setup and Basic Concepts](./doc/02_Development_Documentation/README.md) * [Visitor Info](./doc/02_Development_Documentation/01_Visitor_Info.md) * [Conditions](./doc/02_Development_Documentation/03_Conditions.md) * [Data Providers](./doc/02_Development_Documentation/05_Data_Providers.md) * [Action Handler](./doc/02_Development_Documentation/07_Action_Handlers.md) * [Targeting Storage](./doc/02_Development_Documentation/09_Targeting_Storage.md) * [Frontend JavaScript](./doc/02_Development_Documentation/11_Frontend_Javascript.md) *** ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore personalization-bundle (03c5e04 / v1.1.1)](https://github.com/pimcore/personalization-bundle/tree/03c5e044acd2361ed4a4355ecac0a90fb37e4306), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Installation(Perspective-editor) ### Bundle Installation 1. Install the required dependencies: ```bash composer require open-dxp/perspective-editor-bundle ``` 2. Make sure the bundle is enabled in the `config/bundles.php` file. The following lines should be added: ```php use OpenDxp\Bundle\PerspectiveEditorBundle\OpenDxpPerspectiveEditorBundle; // ... return [ // ... OpenDxpPerspectiveEditorBundle::class => ['all' => true], // ... ]; ``` 3. Install the bundle: ```bash bin/console opendxp:bundle:install OpenDxpPerspectiveEditorBundle ``` Installation routine just adds an additional permission to `users_permission_definitions` table. Also, make sure, that `customviews.php` and `perspectives.php` files are writeable for php. They can be located at OpenDxp default locations for config files: `OPENDXP_CUSTOM_CONFIGURATION_DIRECTORY` or `OPENDXP_CONFIGURATION_DIRECTORY`. If they don't exist, they are created at `OPENDXP_CONFIGURATION_DIRECTORY`. ### Configuration To make the bundle work, just make sure, users have the necessary permissions. - Perspective Editor: all users with `perspective_editor` permission have all access. - Custom Views Editor: all users with `perspective_editor` permission have read access, only admin users have write access (due to risk of potential security issues as SQL conditions can be configured in the UI). --- ## Customize Menu Entry List Custom view and perspective settings also allow configuring the context menu and toolbar menu entries. It might be necessary to add additional entries due to bundles or application code. This is possible with following two events: ```javascript onPerspectiveEditorLoadStructureForPermissions onPerspectiveEditorLoadPermissions ``` Registering for `onPerspectiveEditorLoadStructureForPermissions` enables you to add a new menu structure, which will then be passed to the `onPerspectiveEditorLoadPermissions` event. Registering for `onPerspectiveEditorLoadPermissions` enables you to add custom visibility settings for your bundle either to one of the default built-in entries or to your own structure you may have created in the `onPerspectiveEditorLoadStructureForPermissions` event. Add one or both events to the `opendxpReady` hook of your bundle. Example 1: Add a custom visibility setting to one of the built-in entries: ```javascript document.addEventListener(opendxp.events.onPerspectiveEditorLoadPermissions, (e) => { const context = e.detail.context; const menu = e.detail.menu; const permissions = e.detail.permissions; if(context == 'toolbar' && menu == 'search' && permissions[context][menu].indexOf('items.advancedObjectSearch') == -1) { permissions[context][menu].push('items.advancedObjectSearch'); } }); ``` Example 2: Add your custom structure with custom entries ```javascript document.addEventListener(opendxp.events.onPerspectiveEditorLoadStructureForPermissions, (e) => { if(e.detail.context == 'toolbar') { e.detail.structure['customEntry'] = {}; } }); document.addEventListener(opendxp.events.onPerspectiveEditorLoadPermissions, (e) => { const context = e.detail.context; const menu = e.detail.menu; const permissions = e.detail.permissions; if(context == 'toolbar' && menu == 'customEntry') { if(permissions[context][menu] == undefined) { permissions[context][menu] = []; } if(permissions[context][menu].indexOf('hidden') == -1) { permissions[context][menu].push('hidden'); ... } } }); ``` For all available built-in entries please have a look at [MenuItemPermissionHelper](https://github.com/open-dxp/perspective-editor-bundle/blob/1.x/src/Resources/public/js/opendxp/perspective/menuItemPermissionHelper.js). --- ## Migrating to OpenDXP(Perspective-editor) ### Migrating from `pimcore/perspective-editor:^1.8` to `open-dxp/perspective-editor-bundle` * Changed PHP namespace to `OpenDxp\Bundle\PerspectiveEditorBundle` * Changed Bundle name to `OpenDxpPerspectiveEditorBundle` * Changed top-level config node to `opendxp_perspective_editor` * Replaced class-names, translations, labels, etc.: * `pimcore` => `opendxp` (yaml identifiers, config keys, translations) * `Pimcore` => `OpenDxp` (PHP identifiers, namespaces, classes) * `PIMCORE` => `OPENDXP` (PHP constants) * `pimcore`(company/vendor) => `open-dxp` (composer package, github/packagist references) --- ## Changelog(Perspective-editor) ### 1.1.0 - [BUGFIX] `config:dump-reference` and the configuration errors show the key `opendxp_perspective_editor` - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [BUGFIX] Update composer package name for perspective editor [#4](https://github.com/open-dxp/perspective-editor-bundle/pull/4) ### 1.0.1 - [CHORE] Update branding names [#2](https://github.com/open-dxp/perspective-editor-bundle/pull/2) - [ENHANCEMENT] Add php 8.5 support [#3](https://github.com/open-dxp/perspective-editor-bundle/pull/3) ### 1.0.0 - [NEW FEATURE] Initial release --- ## Changelog(Qrcode) ### 1.1.0 - [ENHANCEMENT] [MIGRATION] The bundle has an installer: `bin/console opendxp:bundle:install OpenDxpQrcodeBundle` registers the permission for the QR codes. An existing installation is marked as installed by the migrations. - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 - [CHORE] Require `symfony/config` ^7.4, which the bundle uses ### 1.0.0 - [NEW FEATURE] Initial Release --- ## Migrating to OpenDXP(Qrcode) ### Migrating from gal-digital-gmbh/pimcore-qrcode-bundle - Namespace changed from `GalDigitalGmbh\PimcoreQrcodeBundle` to `OpenDxp\Bundle\QrCodeBundle` --- ## QR-Code Bundle Adds a backend configuration view for QR-Codes. This project is a fork of the [GAL Digital - QR-Code bundle (883684f / v2.0.0)](https://github.com/gal-digital-gmbh/pimcore-qrcode-bundle/commits/main), which is licensed under GPLv3. ### Requirements OpenDxp >= 1.0 ### Installation Require the bundle ```bash composer require open-dxp/qrcode-bundle ``` Add the bundle to the `config/bundles.php` file to enable it. The following lines should be added: ```php return [ OpenDxp\Bundle\QrcodeBundle\OpenDxpQrcodeBundle::class => ['all' => true], ]; ``` Execute: `$ bin/console opendxp:bundle:install OpenDxpQrcodeBundle` ### Upgrading - Execute: `$ bin/console doctrine:migrations:migrate --prefix 'OpenDxp\Bundle\QrcodeBundle\Migrations'` - Read the [changelog](CHANGELOG.md) before you update. - Coming from an earlier package? Read [Migrating to OpenDXP](docs/Migrating_to_OpenDXP.md). *** ### Configuration Per default, qr codes will be stored in `config/qrcode/*.yaml`. If you want to change the write target, adjust it like this: ```yaml opendxp_qrcode: config_location: qrcode: write_target: type: 'settings-store' ``` *** ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE](LICENSE). ### Copyright © GAL Digital GmbH © 2026 OpenDXP Contributors — GPLv3 *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. --- ## Changelog(System-info) ### 1.1.0 - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.0.2 - [ENHANCEMENT] Add php 8.5 support [#7](https://github.com/open-dxp/system-info-bundle/pull/7) ### 1.0.1 - [CHORE] Update branding names [#6](https://github.com/open-dxp/system-info-bundle/pull/6) ### 1.0.0 - [NEW FEATURE] Initial release - [ENHANCEMENT] PHP 8.4 & Symfony 7.3 [#1](https://github.com/open-dxp/system-info-bundle/pull/1) - [CHORE] Fix Tests [#2](https://github.com/open-dxp/system-info-bundle/pull/2) --- ## System Info Bundle System Info & Tools bundle provides additional tools for checking system information in OpenDXP Admin UI. *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP System Info Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Tools: #### PHP Info A simple interface that implement `phpinfo()` to provide PHP installation information. You can check via Admin UI `Tools` / `System Info & Tools` / `PHP Info` menu. #### PHP OPcache Status A clean interface based on [`amnuts/opcache-gui`](https://github.com/amnuts/opcache-gui) for Zend OPcache information, showing statistics, settings and cached files, and providing a real-time update for the cache information. You can check via Admin UI `Tools` / `System Info & Tools` / `PHP OPcache Status` menu. *** ### Upstream Origin & Version Transparency This project is a fork of [Pimcore system-info-bundle (4016f47 / v1.0.3)](https://github.com/pimcore/system-info-bundle/commit/4016f47a9ebf18c07f346729fa0f2f8844dc369f), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Migrating to OpenDXP(3) ### Migrating from `pimcore/web-to-print-bundle` to `open-dxp/web-to-print-bundle` * Renamed bundle to `OpenDxpWebToPrintBundle` (composer package: `open-dxp/web-to-print-bundle`) * BC breaks * Removed deprecated `Chromium` driver. If you want to continue chromium, migrate to Gotenberg Chromium instead of native Chromium driver. * Removed support for `Gotenberg` v1 (`gotenberg/gotenberg-php`). Use version `^2.2` instead. --- ## Installation(3) ### Installing processor dependencies If you want to use Gotenberg as processor, you need to install additional dependencies. For more information and installation informations have a look at [Document Types and Available PDF Processors](../01_Doc_Types_and_Available_Processors.md#available-pdf-processors) ### Installation Process After installing the bundle and the required dependencies of the processor you wish to use, you need to configure the settings under *Settings > Web-to-Print*. There you will find detailed notes about the options and settings available. depending on which processor you will use. ### Uninstallation Uninstalling the bundle does not clean up `printpages` or `printcontainers`. Before uninstalling make sure to remove or archive all dependent documents. You can also use the following command to clean up you database. Create a backup before executing the command. All data will be lost. ```bash bin/console opendxp:document:cleanup printpage printcontainer ``` --- ## Document Types and Available PDF Processors ### Document Types This bundle introduces 2 new document types: | Type | Description | |----------------------------------------------------------|-----------------------------------------------------------------------------| | [PrintPage](./02_Print_Documents.md#printpage) | Like pages, but specialized for print (PDF preview, rendering options, ...) | | [PrintContainer](./02_Print_Documents.md#printcontainer) | Organizing print pages in chapters and render them all together. | ### Available PDF Processors | Name | Description | |--------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | [Gotenberg](https://gotenberg.dev/) | A Docker service with Chromium and LibreOffice support | | [PDF Reactor](https://www.pdfreactor.com/) | A REST solution for rendering complex catalogs, please visit the official website for further information. Currently OpenDXP supports PDFreactor 10, 11, 12 | | [Dompdf](https://github.com/dompdf/dompdf) | A PHP-based HTML to PDF converter. | > For details on how to install and configure these processors, please see [Additional Tools Installation](https://docs.opendxp.io/docs/core-framework/Installation_and_Upgrade/System_Setup_and_Hosting/Additional_Tools_Installation) page in the Core. You can also add your own Processors as long as they extend the abstract OpenDxp\Bundle\WebToPrintBundle\Processor class. Set the full class name in the web2print settings, for example "App\Web2Print\Processor\WkHtmlToPdf". --- ## Print Documents Print documents are the way to create print-ready PDFs directly within OpenDXP. They are based on the normal OpenDXP documents and therefore support everything as pages do - starting from MVC pattern and template creation to document composing within OpenDXP backend with areas, drag&drop etc. Once activated, print documents are integrated into the default documents tree. But of course you can setup your custom views to have separate trees for web documents and print documents. Just use our completely redesigned [custom views](https://github.com/open-dxp/opendxp/blob/1.x/doc/05_Objects/01_Object_Classes/05_Class_Settings/20_Custom_Views.md) and all [new perspectives features](https://github.com/open-dxp/opendxp/blob/1.x/doc/18_Tools_and_Features/13_Perspectives.md). For more detail-information on the settings see later. ### Web-To-Print Document Types #### PrintPage PrintPages are the documents that contain the actual content - with all the areas, editables, images, and so on. They are based on the normal OpenDXP documents and to content editing should be quite self explaining. ![PrintPages - add new](./img/printdocuments_printpages_menu.png) #### PrintContainer PrintContainers are a special document type to represent containers of PrintPages. They do not have content for their own, they just combine all sub pages to one single output PDF. By doing so they allow to structure big print documents like catalogs, pricelists, books, etc. Of course, PrintContainers can be nested. So, one can use a root container, that contains several chapter containers that then contain the actual print pages. ![PrintContainer - tree](./img/printdocuments_printcontainers_tree.png) Even they don't have content for their own, PrintContainers are based on normal OpenDXP documents. Therefore, they also need a controller and a view. They have to make sure, that all sub pages are included into one single output view. OpenDXP ships with default implementations (`Web2PrintController`, `containerAction`) in skeleton and demo installation package. ### PDF Rendering Both web-to-print documents have an additional tab that is the place for rendering documents to print-ready PDFs. When rendering, the print is first rendererd to HTML, then rendered as a Twig template (yes, you can use Twig expressions in the document) and then rendered to an PDF. PDF rendering itself is done by an third party renderer. Currently we support [pdfreactor](https://www.pdfreactor.com/) and [Gotenberg](https://gotenberg.dev/). Please see their documentation for details concerning template possibilities. Depending on the renderer, there might be settings possible for the rendering process. The provided settings might be extended in future. For details of settings please see section below or renderer documentation. #### Sandbox Restrictions Print document renders user controlled twig templates in a sandbox with restrictive security policies for tags, filters & functions. Please use following configuration to allow more in template rendering: ```yaml opendxp: templating_engine: twig: sandbox_security_policy: tags: ['if'] filters: ['upper'] functions: ['include', 'path'] ``` ### Special PDFreactor Settings **Printermarks**: With PDFreactor there comes a out-of-the-box feature to add printermarks to the PDF. They can be activated by the printermarks rendering setting. Technically they are implemented by an additional CSS-file which needs to be included. ### Settings In the web-to-print settings, the used PDF renderer is specified. Depending on the renderer, there are additional settings to be made. Additional explanation can be found directly in the settings form. These settings have to be set properly before starting PDF rendering. ### Relevant Log Files If PDF rendering doesn't work properly, following log files should give you a hit for the reason. * `var/log/dev.log` or `var/log/prod.log` - contains general logging information for rendering process at INFO level * `var/log/web2print-output.log` - contains output of rendering PHP process (if any). It is recreated on every rendering process. ### Color management and images If you are using the PDFReactor renderer, use CMYK CSS color specifications (see PDFReactor documentation on details). There are two possible workflows for images: 1) Use print-ready source images (for example TIFF files with the correct ICC Profiles) in your documents with "Print (...)" thumbnail format setting. This keeps the colorspace correct when used for print rendering and converts to RGB for preview and edit-mode. 2) Keep RGB style PNG/Jpeg images in the CMYK PDF files and let the printing house take care of converting them to the correct colorspace. Option 2) is preferred, as colorspace conversions are tricky and error-prone due to tightly coupled printer hardware dependencies. --- ## Extending PDF Creation Config for PDF/X Conformance Sometimes it is necessary to add additional configuration options to the PDF processing configuration in the OpenDXP backend UI - for example when creating PDF/X conform PDFs with PDF Reactor. ![Config Options](./img/configs.jpg) But also for other use cases, it might be necessary to hook into the PDF creation process and modify the configuration before creating the file. **Solution** To do so, OpenDXP provides two events: - [`PRINT_MODIFY_PROCESSING_OPTIONS`](https://github.com/open-dxp/web-to-print-bundle/blob/1.x/src/Event/DocumentEvents.php#L56): Event to modify the processing options displayed in the OpenDXP backend UI. For example add additional options like `AppendLog` and `My Additional ...` in the screenshot above. - [`PRINT_MODIFY_PROCESSING_CONFIG`](https://github.com/open-dxp/web-to-print-bundle/blob/1.x/src/Event/DocumentEvents.php#L73) Event to modify the configuration for the PDF processor when the PDF gets created. For example read values for additional options and apply these values to the configuration of the PDF processor accordingly or do some other stuff. ###### Example for adding Additional Config Services in Container: ```yml app.event_listener.test: class: App\EventListener\PDFConfigListener tags: - { name: kernel.event_listener, event: opendxp.document.print.processor.modifyProcessingOptions, method: modifyProcessingOptions } - { name: kernel.event_listener, event: opendxp.document.print.processor.modifyConfig, method: modifyConfig } ``` Implementation of Listener ```php getArguments(); $options = $arguments['options']; $processor = $event->getProcessor(); if ($processor instanceof \OpenDxp\Bundle\WebToPrintBundle\Processor\PdfReactor) { //add option to append log into generated PDF (pdf reactor functionality) $options[] = ['name' => 'appendLog', 'type' => 'bool', 'default' => false]; } $arguments['options'] = $options; $event->setArguments($arguments); } public function modifyConfig(\OpenDxp\Bundle\WebToPrintBundle\Event\Model\PrintConfigEvent $event): void { $arguments = $event->getArguments(); $processor = $event->getProcessor(); if ($processor instanceof \OpenDxp\Bundle\WebToPrintBundle\Processor\PdfReactor) { //check if option for appending log to PDF is set in configuration and apply it to reactor config accordingly if ($arguments['config']->appendLog == 'true'){ $arguments['reactorConfig']['appendLog'] = true; } } $event->setArguments($arguments); } } ``` ###### Example for adding PDF/X Conformance Services in Container see above. Implementation of Listener ```php getArguments(); $processor = $event->getProcessor(); if($processor instanceof \OpenDxp\Bundle\WebToPrintBundle\Processor\PdfReactor) { //Set pdf reactor config for generating PDF/X conform PDF $arguments['reactorConfig']['conformance'] = \Conformance::PDFX4; $arguments['reactorConfig']["outputIntent"] = [ 'identifier' => "ISO Coated v2 300% (ECI)", 'data' => base64_encode(file_get_contents('/path-to-color-profile/ISOcoated_v2_300_eci.icc')) ]; } $event->setArguments($arguments); } } ``` ### Gotenberg PDF Engines When using Gotenberg, please also take in consideration https://github.com/gotenberg/gotenberg-php#pdf-format --- ## Changelog(Web-to-print) ### 1.2.0 - [BUGFIX] The payloads and results of the handlers are no longer registered as services. A container that makes its services public failed on them - [CHORE] Replace Codeception with Pest and `open-dxp/test-foundation` - [CHORE] Require `open-dxp/opendxp` ^1.5 ### 1.1.3 - [ENHANCEMENT] Add admin-bundle 1.4 compatibility [#10](https://github.com/open-dxp/web-to-print-bundle/pull/10) ### 1.1.2 - [BUGFIX] Correct printpage check-pdf-dirty route name [#8](https://github.com/open-dxp/web-to-print-bundle/pull/8) ### 1.1.1 - [ENHANCEMENT] Add php 8.5 support [#7](https://github.com/open-dxp/web-to-print-bundle/pull/7) ### 1.1.0 - [NEW FEATURE] Added new PDF processor [DomPdf](doc/01_Doc_Types_and_Available_Processors.md#available-pdf-processors) ([@PRinguinDevs](https://github.com/open-dxp/web-to-print-bundle/pull/5)) ### 1.0.1 - [CHORE] Dependency updates [#4](https://github.com/open-dxp/web-to-print-bundle/pull/4) ### 1.0.0 - [NEW FEATURE] Initial release - [CHORE] Fix workflows [#1](https://github.com/open-dxp/web-to-print-bundle/pull/1) - [CHORE] Update README.md [#2](https://github.com/open-dxp/web-to-print-bundle/pull/2) --- ## Web To Print Bundle Adds the ability to create web-to-print documents in OpenDXP and to convert them into a PDF. *** ### Disclaimer > OpenDXP is a community-driven fork based on the Pimcore® Community Edition (GPLv3). > OpenDXP is independent and maintained by its community and contributors. > It is not affiliated with, endorsed by, or sponsored by Pimcore GmbH. > Original credits: [Pimcore GmbH](https://www.pimcore.com) **OpenDXP WebToPrint Bundle is based on the Pimcore® Community Edition and remains licensed under GPLv3.** *** ### Features in a Nutshell - Add web2print support for generating PDFs to OpenDXP. - Add new OpenDXP-specific Document types to create print documents with OpenDXP Documents (and all related concepts and features). - Allow creating single pages and whole catalogs with chapters, subchapters and table of contents. - Integrate different adapters to render documents to PDFs: Gotenberg, PDF reactor. ### Documentation Overview * [Installation](./doc/00_Installation_and_Upgrade/README.md) * [Document Types and Available PDF Processors](./doc/01_Doc_Types_and_Available_Processors.md) * [Print Documents](./doc/02_Print_Documents.md) * [Extending PDF Creation Config for PDF/X Conformance](./doc/90_Web2Print_Extending_Config_for_PDFX_conformance.md) ### Contributing and Development For details see our [Contributing guide](https://github.com/pimcore/web-to-print-bundle/blob/1.x/CONTRIBUTING.md). *** ### Changelog Before updating, please [check the changelog!](CHANGELOG.md) Coming from an earlier package? Read [Migrating to OpenDXP](doc/00_Installation_and_Upgrade/01_Migrating_to_OpenDXP.md). ### Upstream Origin & Version Transparency This project is a fork of the [Pimcore web-to-print-bundle (500df07 / v1.4.0)](https://github.com/pimcore/web-to-print-bundle/tree/500df07ca3055e300ab6fd9cc8254a405dd3e84f), which is © Pimcore GmbH and licensed under GPLv3. ### License Licensed under the GNU General Public License v3.0 (GPLv3). For details, please see [LICENSE.md](LICENSE.md). ### Copyright © Pimcore GmbH © 2026 OpenDXP Contributors — GPLv3 ### Trademarks Pimcore® is a registered [trademark](https://www.trademarkelite.com/europe/trademark/trademark-detail/009309841/PIMCORE) of Pimcore GmbH. Any use of the Pimcore® mark in this repository is purely descriptive to identify the original upstream project. *** ### Contact For inquiries, suggestions, or contributions, feel free to reach us at contact@opendxp.io. ### About OpenDXP is a community-driven project initiated by [DACHCOM.DIGITAL](https://www.dachcom.com/de-ch) (Rheineck, Switzerland) and maintained by its community and contributors. OpenDXP is independent and not affiliated with Pimcore GmbH. The project’s purpose is to preserve and maintain a GPLv3‑licensed codebase for community use. It is **not positioned as a competitor** to products or services of Pimcore GmbH and does **not** purport to replace or supersede any Pimcore offering. --- ## Changelog(Mate) ### 1.0.6 - [NEW FEATURE] `opendxp_project` names the security advisories that affect an installed OpenDXP package, with the version that fixes each - [CHORE] Check dependencies, code and commits for security issues ### 1.0.5 - [ENHANCEMENT] The extension accepts version 8.1 of `symfony/dotenv`, `symfony/http-client` and `symfony/process` ### 1.0.4 - [ENHANCEMENT] `mate-opendxp-contributing` covers the changelog entry, the commit and the pull request of a change to an OpenDXP package ### 1.0.3 - [ENHANCEMENT] `mate-opendxp-dev` leads to `mate-opendxp-tests` for work on tests ### 1.0.2 - [BUGFIX] `opendxp_upgrade_plan` reads the `composer.lock` of a project in a subdirectory of the repository - [ENHANCEMENT] Requires `symfony/ai-mate` 0.15, whose Composer plugin runs `mate discover` after `composer install` and `composer update` ### 1.0.1 - [BUGFIX] The instructions and the skills refer to the skills by their installed names, such as `mate-opendxp-dev` ### 1.0.0 - [NEW FEATURE] Initial release - [NEW FEATURE] [HIGHLIGHT] `opendxp_update_options` lists the newer releases of the installed OpenDXP packages, `opendxp_upgrade_plan` lists what to do after `composer update`, and the skill `opendxp-upgrade` walks an agent through it > Let your agent update OpenDXP. It reads the tasks, the opt-in features and the migrations of every package straight > from the changelogs and confirms each step with a tool. --- ## Mate Extension An AI agent that works on an OpenDXP project guesses twice. It guesses what the installation contains, and it guesses which mechanism of OpenDXP fits the task. Both guesses produce code that looks right and is wrong. This package is an extension for [Symfony AI Mate](https://symfony.com/doc/current/ai/components/mate.html). Its tools answer from the booted kernel of the installation: the bundles, the data model, the configuration, the document types and areabricks. Its skills tell the agent which mechanism fits a case and which tool to ask first. ### Release Plan | Release | Supported OpenDXP Versions | Supported Symfony Versions | Release Date | Maintained | Branch | |---------|----------------------------|----------------------------|--------------|----------------|--------| | **1.x** | `^1.5` | `^7.4` | 2026 | Feature Branch | 1.x | > [!NOTE] > Mate is still on `0.x`. A minor release of Mate may change how extensions work, so a minor release here may follow it. ### Installation The extension is for development only. Its tools boot the kernel and read the data model and the configuration. Install it with `--dev` and never deploy it. ```bash composer require --dev open-dxp/mate-extension vendor/bin/mate init vendor/bin/mate discover ``` `mate init` asks which command your coding agent uses to run Mate. #### Running Mate in DDEV Mate has to run inside the container, next to the PHP and the database of the project, so you install the extension through DDEV: ```bash ddev composer require --dev open-dxp/mate-extension ``` Then run `mate init` with either of these two commands: ```bash ddev exec vendor/bin/mate init ddev composer exec -- mate init ``` `ddev exec` starts in the root of the DDEV project, so if your `composer.json` lives in a subdirectory such as `backend/app`, pass that directory with `--dir`: ```bash ddev exec --dir /var/www/html/backend/app vendor/bin/mate init ``` `ddev composer exec` always starts in the directory of `composer.json`. The `--` keeps Composer from treating the options of Mate as its own. Then run `mate discover` with the same command, for example `ddev composer exec -- mate discover`. When `mate init` asks which command your agent should use to run Mate, it suggests `ddev exec vendor/bin/mate` if `.ddev` sits next to `composer.json`. You can keep this suggestion. Otherwise it suggests `vendor/bin/mate`, which would run outside the container, so answer with one of these commands instead: ```bash ddev exec --dir /var/www/html/backend/app vendor/bin/mate ddev composer exec -- mate ``` `mate init` then warns that it cannot ask this command for its PHP version. Instead, it pins the PHP version of the container, which is the right one. #### Running Mate with Docker Compose With Docker Compose, Mate runs in the service that runs PHP. In this example, the service is called `php`: ```bash docker compose exec php composer require --dev open-dxp/mate-extension docker compose exec php vendor/bin/mate init docker compose exec php vendor/bin/mate discover ``` When `mate init` asks which command your agent should use to run Mate, answer `docker compose exec -T php vendor/bin/mate`. The `-T` is needed because your agent runs the command without a terminal. #### What Mate sets up `mate init` writes the directory `mate/`, an `AGENTS.md` and a `CLAUDE.md` that imports it. The `AGENTS.md` tells your agent which tools and skills exist and how to call them. `mate discover` picks up the installed extensions and installs their skills into `.agents/skills` and `.claude/skills`, where your agent finds them. The Mate Composer plugin runs it after every `composer install` and `composer update`, but only once `mate init` has written `mate/`. That is why you run `mate discover` yourself right after `mate init`. Composer only runs plugins that the project allows, so an existing project may need to allow it first: ```bash composer config allow-plugins.symfony/ai-mate-composer-plugin true ``` #### Symfony tools The [Symfony extension](https://symfony.com/doc/current/ai/components/mate.html) of Mate adds tools that read the container and the profiler, such as `symfony-services` and `symfony-profiler-list`. The skill `mate-opendxp-dev` uses them when they are installed. The extension is optional: ```bash composer require --dev symfony/ai-symfony-mate-extension ``` ### Tools | Tool | Answers | |--------------------------|------------------------------------------------------------------------------------------------------------| | `opendxp_project` | The core version, PHP, the environment, every bundle with version and enabled state. | | `opendxp_model_schema` | The data object classes with their fields, the relation field types, field collections, bricks and stores. | | `opendxp_site_config` | Website settings with their references resolved, image thumbnails, sites and languages. | | `opendxp_documents` | The document types with their capabilities and the areabricks with their templates. | | `opendxp_docs` | Searches docs.opendxp.io and answers with the matching pages and an excerpt from each. | | `opendxp_update_options` | The newer releases of every OpenDXP package, within the constraint and beyond, with their highlights. | | `opendxp_upgrade_plan` | After `composer update`: the tasks, migrations, deprecations and opt-in features of every changed package. | A tool runs like this: ```bash vendor/bin/mate tools:call opendxp_model_schema --class=Product ``` `opendxp_docs`, `opendxp_update_options` and `opendxp_upgrade_plan` leave the machine. They query the documentation site, which publishes the changelog of every package as `/releases.json`. Point them elsewhere in `mate/config.php`: ```php $configurator->parameters()->set('opendxp_mate.docs_url', 'https://docs.example.com'); ``` ### Skills | Skill | Covers | |------------------------------|-----------------------------------------------------------------------------------------------| | `mate-opendxp-dev` | The entry point. Which tool answers what, and which skill covers a task. | | `mate-opendxp-data-objects` | Field collections, object bricks, classification stores, blocks and every relation type. | | `mate-opendxp-documents` | Document types, editables, blocks, areablocks and areabricks. | | `mate-opendxp-configuration` | Website settings, properties, asset metadata, and where admin-edited configuration is stored. | | `mate-opendxp-upgrade` | What an update would bring, and the update itself through the migrations to the last check. | | `mate-opendxp-contributing` | The changelog entry, the commit and the pull request for a change to an OpenDXP package. | ### Tools and skills of a bundle A bundle ships its own tools and skills. Mate finds them through the `extra.ai-mate` section in the `composer.json` of the bundle: ```json "extra": { "ai-mate": { "scan-dirs": ["src/Mate"], "includes": ["config/mate.php"], "skills": ["skills"] } } ``` Mate installs a skill as `mate-`, so refer to it by that name in instructions and other skills. The tools of a bundle are services of the application and get their dependencies from its container. The bundle registers them as public services when Mate is installed. The file in `includes` tells Mate to fetch each tool from the booted application. Mate reads only PHP files there: ```php $services->set(MyTool::class) ->factory([service(HostKernel::class), 'get']) ->args([MyTool::class]) ->public(); ``` ### License **DACHCOM.DIGITAL AG**, Löwenhofstrasse 15, 9424 Rheineck, Schweiz [dachcom.com](https://www.dachcom.com), dcdi@dachcom.ch Copyright © 2026 DACHCOM.DIGITAL. All rights reserved. For licensing details please visit [LICENSE.md](LICENSE.md) --- ## Changelog(Test-foundation) ### 1.2.9 - [BUGFIX] `opendxp-test install` runs the migrations of a bundle without an installer - [BUGFIX] A request through `Container::testClient()` is the main request, so OpenDXP reads its locale ### 1.2.8 - [NEW FEATURE] `Concurrency::run()` tests race conditions with closures in parallel processes. See [Concurrency](README.md#concurrency) - [NEW FEATURE] `WithoutRollbackTestCase` restores a database snapshot instead of rolling back. See [Tests without rollback](README.md#tests-without-rollback) - [NEW FEATURE] `opendxp-test install` runs the application's own migrations. See [Set up a project](README.md#set-up-a-project) - [BUGFIX] `Admin::actingAs()` grants the roles of the user ### 1.2.7 - [NEW FEATURE] `InstallDefinitions` installs the definitions OpenDXP ships for tests when the parameter `opendxp-definitions` is `true` ### 1.2.6 - [BUGFIX] The first test of an environment reads the system configuration of that environment ### 1.2.5 - [BUGFIX] `opendxp-test install` keeps the definitions of the data object classes, field collections and object bricks of a project ### 1.2.4 - [BUGFIX] `opendxp-test install` shows why the installer of a bundle failed ### 1.2.3 - [ENHANCEMENT] The test skill lists the rules for writing and reviewing tests ### 1.2.2 - [BUGFIX] The pages of a project render through its own default controller instead of the controller of the foundation ### 1.2.1 - [CHORE] Use docs.opendxp.io URIs - [ENHANCEMENT] Ship the test skill through Mate ### 1.2.0 - [ENHANCEMENT] Share the kernel boot of PHPUnit extensions and rework the README [#4](https://github.com/open-dxp/test-foundation/pull/4) ### 1.1.2 - [CHORE] Move test page markup into Twig templates [#3](https://github.com/open-dxp/test-foundation/pull/3) ### 1.1.1 - [BUGFIX] Read a form the server rejects [#2](https://github.com/open-dxp/test-foundation/pull/2) ### 1.1.0 - [NEW FEATURE] `Page` finds what a person sees on a page: texts, fields by their label, buttons and regions, in the kernel browser and in a real browser - [NEW FEATURE] `extra.opendxp-test.optional` takes a version constraint for each optional package ### 1.0.1 - [CHORE] Boot Foundry through its PHPUnit extension [b8234b5](https://github.com/open-dxp/test-foundation/commit/b8234b5b1346a1e5bfdee4f7ba2f8aa1ad29f1c8) - [CHORE] Keep the messages of a test in memory [3819049](https://github.com/open-dxp/test-foundation/commit/38190497710857281441454808631274ff47288b) - [ENHANCEMENT] Hash passwords with the lowest cost in tests [66349f0](https://github.com/open-dxp/test-foundation/commit/66349f0c37d915bbf2925f5b99e4316d65f962e3) ### 1.0.0 - [NEW FEATURE] Initial release --- ## Test Foundation The test foundation gives an OpenDXP bundle or project what it needs to run tests: - a test kernel - test cases that boot the application and run every test in a rolled back transaction - a browser - the commands that build, install and check the application the tests run in Tests are written with [Pest](https://pestphp.com). Test data is created with the [Foundry](https://github.com/zenstruck/foundry) factories that OpenDXP ships in `OpenDxp\Test`. The transaction comes from [DAMADoctrineTestBundle](https://github.com/dmaicher/doctrine-test-bundle). [Testing][testing] in the documentation of OpenDXP describes how you write tests. It also describes the test API of OpenDXP with its factories and expectations. [testing]: https://docs.opendxp.io/docs/core-framework/next/Development_Tools_and_Details/Testing/ [writing-tests]: https://docs.opendxp.io/docs/core-framework/next/Development_Tools_and_Details/Testing/Writing_Tests/ [factories]: https://docs.opendxp.io/docs/core-framework/next/Development_Tools_and_Details/Testing/Factories_and_Stories/ [testkit]: https://github.com/open-dxp/docker-testkit [workflows]: https://github.com/open-dxp/workflows-collection-public ### Set up a bundle These steps take a bundle from no tests to its first green test. The examples use a bundle called `Acme\BlogBundle`. #### 1. Require the package ```bash composer require --dev open-dxp/test-foundation ``` Give the tests a namespace in `composer.json`: ```json { "autoload-dev": { "psr-4": { "Acme\\BlogBundle\\Tests\\": "tests/" } } } ``` #### 2. Add `phpunit.xml.dist` The paths in this file are relative to the application that runs the tests. Your bundle is a dependency there. ```xml tests/Feature ``` The extension of DAMA rolls back the transaction of every test. The extension of Foundry starts Foundry for every test. Without it, no factory works. `InstallDefinitions` installs the data object classes of the package, as [Data object classes](#data-object-classes) describes. Add `tests/Unit` once the bundle has unit tests. PHPUnit stops when a directory it names does not exist. #### 3. Add the test kernel A bundle has no application of its own. The foundation builds one around it, and `tests/Application/TestKernel.php` registers the bundle in it: ```php addBundle(new AcmeBlogBundle()); } } ``` #### 4. Assign the test case `tests/Pest.php` assigns the test case: ```php extend(TestCase::class)->in('Feature'); ``` #### 5. Write the first test `tests/Feature/Application/BootTest.php`: ```php toBeInstanceOf(PostManager::class); }); ``` ### Set up a project A project is its own application. Its kernel lives in `tests/TestKernel.php`. It extends the project's kernel and uses the `Testable` trait: ```php [!NOTE] > `opendxp-test install` runs the project's own migrations after it creates the data object classes. > Migrations in `vendor/` or in a bundle belong to a package. A package with an installer marks them as executed. > The migrations of a bundle without an installer run on the installation. ### Run the tests #### With the testkit The [OpenDXP testkit][testkit] builds the application, installs OpenDXP and runs the tests of a bundle or a project. Your checkout stays untouched: ```bash testkit test ``` #### Without the testkit A project runs its tests in its own environment. `DATABASE_URL` in `.env.test` or `.env.test.local` names an empty database: ```bash APP_ENV=test vendor/bin/opendxp-test install APP_ENV=test vendor/bin/pest APP_ENV=test vendor/bin/opendxp-test analyse . ``` A bundle has no application of its own. You need PHP and an empty database: ```bash mysql -e "CREATE DATABASE blog_tests" mkdir /tmp/blog-tests && cd /tmp/blog-tests echo '{"minimum-stability": "dev", "prefer-stable": true}' > composer.json composer require --no-plugins --no-scripts open-dxp/test-foundation export DATABASE_URL=mysql://root:root@127.0.0.1:3306/blog_tests vendor/bin/opendxp-test bundle /path/to/blog-bundle vendor/bin/opendxp-test install vendor/bin/pest ``` #### In CI The [reusable workflows][workflows] run exactly these commands. The testkit runs them as well. A test that passes with the testkit therefore also passes in CI. ### Directory structure ``` tests/ Feature/ tests that boot the application Unit/ tests that boot nothing Application/ a bundle only: the test kernel and its config/ TestKernel.php a project only: the test kernel config/ a project only: the configuration beside the kernel Fixtures/ the definitions of the data object classes ``` [Writing Tests][writing-tests] describes the rest of the layout and where each piece of test code goes. ### Configuration of the test application The test kernel reads its own configuration from the directory `config/` beside its class file. For a bundle that is `tests/Application/config/`, and for a project `tests/config/`. The kernel loads the configuration in this order: 1. `config/security.yaml` beside the kernel 2. the configuration of the application 3. the configuration of the foundation 4. `config/.yaml` beside the kernel, which is `config/test.yaml` by default Symfony accepts new firewalls only from the first file that names any. A bundle that needs a firewall of its own, like a frontend login, therefore lists all firewalls in `config/security.yaml`. The configuration of the foundation adapts OpenDXP to tests: - The messenger transports of OpenDXP are in memory. - Passwords are hashed with the lowest cost. - OpenDXP sends every mail to `debug@test-foundation.test`. - OpenDXP writes its settings into the settings store, not into files. - The CSRF protection of the admin is switched off. ### Test cases | Test case | What it does | |---------------------------|--------------------------------------------------------------------| | `TestCase` | boots the application and handles requests | | `BrowserTestCase` | the same, plus a real browser | | `EnvironmentTestCase` | the same, in another configuration of the application | | `WithoutRollbackTestCase` | the same, but restores a database snapshot instead of rolling back | Every test runs in a database transaction. The transaction is rolled back after the test. #### Static state Before every test, the test case sets the timezone from the system settings. It also sets up OpenDXP the way the frontend sees it: - Unpublished documents and data objects are hidden. - Data objects inherit the values of their parents. - Localized fields fall back to other languages. After every test, the test case resets what OpenDXP keeps in statics: the runtime cache, the system configuration, the admin mode, the current site and the current static route. A test restores any other static state it changes. #### Tests without rollback Some tests need committed data: - A schema change commits the transaction. - InnoDB updates a full-text index only on commit. - A concurrent process only sees committed data. These tests extend `WithoutRollbackTestCase`. It takes a snapshot of the database before the first of these tests and restores it after each test. The snapshot also undoes the changes made by the processes of `Concurrency::run()`. A test therefore never cleans up after itself. The snapshot is stored in tables prefixed with `snapshot_` in the same database. The database user needs no additional privileges. Files on disk are not restored, such as the files of versions and assets. Schema changes are not restored either. To combine the snapshot with another test case, call `DatabaseSnapshot` in your own test case: ```php use DAMA\DoctrineTestBundle\PHPUnit\SkipDatabaseRollback; use OpenDxp\TestFoundation\DatabaseSnapshot; use OpenDxp\TestFoundation\EnvironmentTestCase; #[SkipDatabaseRollback] abstract class FullPageCacheWithoutRollbackTestCase extends EnvironmentTestCase { protected function setUp(): void { parent::setUp(); DatabaseSnapshot::save(); } protected function tearDown(): void { DatabaseSnapshot::restore(); parent::tearDown(); } protected static function environment(): string { return 'full_page_cache'; } } ``` #### Concurrency Concurrent requests that change the same data can leave it in an inconsistent state. For example, two customers redeem the same voucher code at the same time. `Concurrency::run()` runs closures in parallel and returns their results in the order of the closures. Concurrency tests need committed data. Their folder extends `WithoutRollbackTestCase` in `tests/Pest.php`: ```php pest()->extend(WithoutRollbackTestCase::class)->in('Feature/Concurrency'); ``` The test sends the same request twice at the same time: ```php use OpenDxp\TestFoundation\Concurrency; use OpenDxp\TestFoundation\Container; it('redeems a voucher code only once', function () { VoucherFactory::createOne(['code' => 'WELCOME']); $redeem = function (): int { $client = Container::testClient(); $client->request('POST', '/voucher/WELCOME/redeem'); return $client->getResponse()->getStatusCode(); }; expect(Concurrency::run($redeem, $redeem)) ->toEqualCanonicalizing([ 200, 409, ]); }); ``` Each closure runs in a separate process. Every process behaves like a new request with its own kernel, database connection and session. The processes only see committed data. For this reason, `Concurrency::run()` throws an exception in a test with rollback. A race condition only shows up when the processes reach the critical section at the same time. A test double usually keeps that section open, for example by waiting one second between loading the voucher and saving it. Make sure the test fails when you remove the protection it covers. A closure must return a serializable value, such as a status code. If a process throws an exception, its result is empty and the expectations of the test fail. Models loaded before `Concurrency::run()` do not reflect the changes made by the processes. Reload them with `['force' => true]` or query the database. #### Another configuration Some behaviour only shows in another configuration, for example with the full page cache switched on. `EnvironmentTestCase` boots the application in a Symfony environment of its own: ```php use OpenDxp\TestFoundation\EnvironmentTestCase; abstract class FullPageCacheTestCase extends EnvironmentTestCase { protected static function environment(): string { return 'full_page_cache'; } } ``` The kernel then loads `config/full_page_cache.yaml` instead of `config/test.yaml`. The file imports `test.yaml`, so the environment adds to the test configuration: ```yaml imports: - { resource: test.yaml } opendxp: full_page_cache: enabled: true ``` ### Services `Container` hands out the services of the running application: ```php Container::get(PostManager::class); Container::parameter('acme_blog.posts_per_page'); ``` Every service whose class the package under test or its tests define is public in the test application. Symfony would otherwise remove a private service that nothing injects, and a test could not fetch it. The services of other packages stay as they are. A service definition that only works because Symfony removes it shows up as an error here. Fix it in the package's own configuration. ### Test data #### Factories OpenDXP ships factories for its own models in `OpenDxp\Test\Factory`, with base classes for the factories of your package. [Factories and Stories][factories] explains them. #### Data object classes Put the definitions of your data object classes into `tests/Fixtures/`. The file name is the name of the definition: ``` tests/Fixtures/ classificationstores/ fieldcollections/ classes/Post.json objectbricks/ ``` The `InstallDefinitions` extension installs them once, before the first test. Classes refer to classification stores and field collections, and object bricks refer to classes. The extension therefore installs classification stores first, then field collections, classes and object bricks. The installation changes the schema. A schema change inside a test would end the transaction of that test. That is why the installation runs before the tests. The extension reads `tests/Fixtures` unless you name another directory: ```xml ``` OpenDXP ships definitions for tests in `OpenDxp\Test`: data object classes, an object brick, a field collection and a classification store. Each class has a factory in `OpenDxp\Test\Factory`. The extension installs these definitions before your own when you ask for them: ```xml ``` A project keeps its classes in `var/classes`, and `opendxp-test install` creates them from there. #### Install something else before the first test A PHPUnit extension of your own installs anything else that changes the schema. `BootKernelTrait` boots the kernel that `KERNEL_CLASS` names: ```php use OpenDxp\TestFoundation\PHPUnit\BootKernelTrait; use PHPUnit\Runner\Extension\Extension; use PHPUnit\Runner\Extension\Facade; use PHPUnit\Runner\Extension\ParameterCollection; use PHPUnit\TextUI\Configuration\Configuration; final class InstallSearchIndex implements Extension { use BootKernelTrait; public function bootstrap(Configuration $configuration, Facade $facade, ParameterCollection $parameters): void { $kernel = self::bootKernel(); // install the index $kernel->shutdown(); } } ``` Register the extension in `phpunit.xml.dist` after the extensions of DAMA and Foundry. #### Files A test that cares about the size of a file and not about its content: ```php $path = Files::create('upload.pdf', megabytes: 25); ``` #### Visitors from another country The test application uses a small GeoIP database. It knows one address in each of these countries: AT, BE, CH, DE, FR, HK, HU and US. ```php $browser = Browser::start(); $browser ->client() ->setServerParameter('HTTP_CLIENT_IP', GeoIp::addressIn('CH')); $browser->visit('/'); ``` The database is set in the parameter `opendxp.geoip.db_file`. A bundle that needs other countries sets this parameter to a database of its own. #### Repeat a failing run Random values can make a test fail only once in a while. Foundry prints the seed of its random values after every run: ``` Faker seed used: 1234 ``` Set the environment variable `FOUNDRY_FAKER_SEED` to that number, for example in the `` section of `phpunit.xml.dist`. Every factory then produces the same values again. ### External services A test against an external service reads its address from an environment variable: | Variable | Example | |----------------------------|----------------------| | `OPENDXP_TEST_REDIS_DSN` | `redis://redis:6379` | | `OPENDXP_OPEN_SEARCH_HOST` | `opensearch:9200` | The [testkit][testkit] sets a variable when its configuration lists the service under `services`. The [Pest workflow][workflows] sets it with `enable_redis_service` or `enable_opensearch_service`. A test skips itself when its variable is missing, as [Writing Tests][writing-tests] shows. ### The browser ```php Browser::visit('/en/about-us')->assertSee('About us'); Browser::playwrightActingAs(UserFactory::new()->admin()->create()) ->visit('/admin') ->waitUntilVisible('div#opendxp_panel_tree_objects'); ``` `visit()` sends the request to the kernel directly, and no JavaScript runs. `playwright()` drives a real browser. A test that does this extends `BrowserTestCase` and is in the group `browser`. A browser test never waits for a fixed time. The browser waits on its own, and a `sleep` hides a race. #### A page as a person uses it A frontend test uses `Page`. It finds a field by its label, a region by its ARIA name, and a button or a link by its text, so the test needs no selector: ```php $page = Page::open('/en/contact') ->fillIn('Name', 'Ada') ->select('Topic', 'Support') ->press('Send'); expect($page->notifications())->toBe(['Thank you']); ``` `notifications()` reads every element with `role="alert"` or `role="status"`. `description()` reads the text a field names with `aria-describedby`, like a help text. A bundle builds the page objects of its own pages on top of `Page`. `Page::inBrowser()` opens the page in a real browser. ### The logged in user A test that calls a service directly, without a request, names the logged in backend user with `Admin`: ```php Admin::actingAs(UserFactory::new()->admin()->create()); ``` A service that asks who is logged in is then handed this user. ### Static analysis PHPStan reads the container the test kernel writes. The `phpstan.neon` of the package lists the paths to analyse and points at that container: ```neon parameters: paths: - src symfony: containerXmlPath: %currentWorkingDirectory%/var/cache/test/TestContainerDebug.xml ``` ### Composer keys | The package needs it | Key | |-----------------------------------------------------|-------------------------------| | to run | `require` | | for development, and everyone can install it | `require-dev` | | never, but users may want it | `suggest` | | only for its tests, and not everyone can install it | `extra.opendxp-test.optional` | `extra.opendxp-test.optional` maps each package to a constraint, like `require-dev`: ```json "extra": { "opendxp-test": { "optional": { "open-dxp/formbuilder-bundle": "^1.0" } } } ``` ### Commands `vendor/bin/opendxp-test` builds and checks the application. `DATABASE_URL` and `DATABASE_SERVER_VERSION` name the database. The PHP that runs the commands is the PHP the application uses. | Command | What it does | |----------------------------------------|---------------------------------------------------------------------------------------------------------------------| | `bundle ` | requires the bundle with its `require-dev` and optional packages, and copies the application template and the tests | | `bundle --opendxp ` | the same, with this version of `open-dxp/opendxp` | | `install` | installs OpenDXP, the bundles and the data object classes, and warms the cache | | `analyse [check]` | runs lint, and phpstan, deptrac and phparkitect where the package configures them | | `analyse --baseline` | writes the PHPStan baseline next to `phpstan.neon` | Lint checks the container, the YAML configuration and the Twig templates. It lints the templates of a bundle in the test application. A project lints them in the environment it is deployed to. That is `prod` or `production`, whichever the project configures under `config/packages/`. ### Versions The major version follows OpenDXP. Test foundation 1.x supports OpenDXP 1.x, and 2.x will support OpenDXP 2.x. The test foundation follows semantic versioning. A major version comes when existing tests would break otherwise. That happens with a new major version of Pest, Foundry, PHPUnit or OpenDXP, or when the foundation changes its own API. | Test foundation | OpenDXP | PHP | Pest | |-----------------|---------|---------------|-----------------------------------| | 1.x | 1.5+ | 8.3, 8.4, 8.5 | 4 on PHP 8.3, 5 on PHP 8.4 and up | Composer picks the Pest version that fits the PHP version and the other dependencies of the package. A package whose development dependencies do not allow Pest 5 stays on Pest 4. A test therefore uses only what Pest 4 and Pest 5 both offer. --- ## Testkit Runs the tests and static checks of an OpenDXP bundle, of OpenDXP core or of an OpenDXP project on your machine. A test suite needs an installed OpenDXP application, a database and a compiled container. The testkit builds that application in a slot of its own and runs Pest or the static checks there. Your checkout stays as it is. Nothing is installed into it and nothing is written back. The README of [open-dxp/test-foundation](https://github.com/open-dxp/test-foundation) describes how you set up a package for tests. ### Requirements - Docker and [DDEV](https://ddev.com) - git, rsync and bash - Node.js, only for the MCP server ### Getting started ```bash git clone https://github.com/open-dxp/docker-testkit cd docker-testkit ddev start ``` Then run the tests of a checkout: ```bash /path/to/docker-testkit/testkit test /path/to/your/bundle ``` The target is always the whole git repository, wherever inside it you start. Without a path, the testkit takes the current directory. To call it as `testkit` from anywhere, link it into your PATH: ```bash ln -s /path/to/docker-testkit/testkit ~/.local/bin/testkit ``` If you prefer not to change your PATH, an alias does the same: 1. Open `~/.bashrc` or `~/.zshrc`. 2. Add `alias testkit=/path/to/docker-testkit/testkit`. 3. Open a new terminal. Inside the testkit directory, `ddev test`, `ddev analyse`, `ddev release` and `ddev slots` work as well. They need a path. ### Versions The testkit is not a Composer package. The branch `2.x` is the current version. It installs the test foundation in the version the package requires. ### Commands ``` testkit test [path] [--php 8.3] [--db mariadb] [--fresh] [pest options and test paths] testkit analyse [path] [lint|phpstan|deptrac|phparkitect] [--baseline] [--php 8.3] [--db mariadb] testkit status testkit release [path | --all] ``` Everything the testkit does not know goes to Pest as it stands: ```bash testkit test tests/Feature/Area/ImageTest.php testkit test --filter=Headline testkit test --exclude-group=browser ``` A path counts as the target only when it is a checkout, with a `composer.json` or a `.git`. `analyse` runs every check the package configures. Name one check to run only that one. `analyse --baseline` writes the PHPStan baseline beside the package's `phpstan.neon` into your checkout. It is the only command that writes into a checkout. `--fresh` builds the slot again from nothing. Use it when a dependency was released and you want it. The testkit hands `FOUNDRY_FAKER_SEED` from your shell to the run: ```bash FOUNDRY_FAKER_SEED=819793 testkit test --filter=Headline ``` ### Variables of a project A project that runs on DDEV keeps its local variables under `web_environment` in `.ddev/config.yaml`. The testkit hands them to every command in the slot. A project without DDEV puts the variables its tests need into a versioned `.env.test`, which Symfony loads during tests. ### Configuration `.ddev/testkit.dist.yaml` holds the defaults. Put what you want to change into `.ddev/testkit.yaml`, which is not versioned. Maps are merged key by key, lists are replaced. A change needs `ddev restart`, which empties every slot. | Key | Meaning | |---------------------|-----------------------------------------------------------------------------------| | `slots` | How many runs may happen at the same time. The default is 5. | | `php` | The PHP versions offered and the default one. | | `databases` | The database servers offered and the default one. | | `registry` | A composer repository besides packagist, for closed-source packages. | | `composer_symlinks` | Packages taken from a checkout on your machine instead of from a registry. | | `services` | Services a suite needs, from the catalogue. | | `memory` | The memory limit of the testkit container. All slots share it. The default is 8g. | #### Working on a dependency `composer_symlinks` maps a package name to a checkout: ```yaml composer_symlinks: open-dxp/test-foundation: /home/you/projects/test-foundation open-dxp/opendxp: /home/you/projects/opendxp ``` Every slot that needs such a package links your checkout into `vendor`, and an edit there is live in the next run. The checkout is mounted read-only. Its `composer.json` has to carry the package name you give. A branch has no version a constraint such as `^1.3` would accept. A linked checkout therefore counts as the major version of its newest tag followed by `.99.99`, for example `1.99.99`. #### Services The testkit offers `redis` and `opensearch`, with the same images as CI. Each service sets its variable, as [External services](https://github.com/open-dxp/test-foundation#external-services) lists: ```yaml services: [redis, opensearch] ``` On start, each listed service gets a file `.ddev/docker-compose..yaml`. If you need a different setting, edit that file. The testkit then leaves it alone. When you remove the service from the list, the testkit deletes the file unless you edited it. ### Slots Each run gets a slot: a directory with its own application and its own database. A slot belongs to one checkout, one PHP version and one database server, and either to the tests or to the static checks. The second run of the same combination reuses it and takes seconds. The static checks have a slot of their own because a test installs the class definitions of its fixtures for good. In its own slot, the analysis sees only what the installation built, as it does in CI. A slot is built again when the `composer.json` of the checkout or of a linked package changes, or the lock file or class definitions of a project. Everything else is copied into the slot before every run. When every slot is taken, the slot that was idle longest is built again for the new run. Two runs of the same combination wait for each other. A test that writes outside its transaction, for example by creating a table, leaves that write in the slot for the next run. ```bash testkit status testkit release testkit release --all ``` `ddev stop` releases every slot. It refuses to stop while a run is in a slot. ### Agents `mcp-server/` is an MCP server for Claude Code and any other client that speaks MCP. Its tools are `run_tests`, `run_analysis`, `release_slots` and `testkit_status`. Each takes the path of a checkout. ```bash claude mcp add --scope user opendxp-testkit -- node /path/to/docker-testkit/mcp-server/index.js ``` `ddev start` installs the server's dependencies on the first start. --- ## AI & Testing A coding agent should not guess what your installation contains, and it should not guess whether its change works. These tools give it the facts and a way to check. ### Tools ### Documentation for agents Every page of this documentation is also published as Markdown. [llms.txt](pathname:///llms.txt) lists all of them. [llms-full.txt](pathname:///llms-full.txt) contains the whole documentation in a single file. --- ## OpenDXP Overview OpenDXP is the leading Open Source platform for managing digital data and customer experience. It provides a fully integrated software stack for PIM, MDM, CDP, DAM, DXP/CMS & Digital Commerce. As a platform, OpenDXP provides a solid foundation with generic functionality for all kinds of web applications and therefore allows rapid application development and building customer solutions really fast. Its API driven approach makes it easy to develop with OpenDXP, allows integration into every IT infrastructure and makes it easily extendable. Also headless execution of OpenDXP is possible. OpenDXP is built for developers and should empower them to build great digital experiences easily. As a consequence, OpenDXP is NOT an ‘out-of-the-box’ software product like Wordpress, Magento, Akeneo, WooCommerce, Shopify and others. You need a developer to get started. ## OpenDXP in a Nutshell Our mission is to provide ONE platform for ANY data, ANY channel, ANY process and ANY one. ### ANY Data In OpenDXP any digital content can be managed and put in relation with other content. There are three main element data types in OpenDXP: #### [Data Objects](../05_Objects/README.md) Manage any structured data based on a predefined data model, either manually or automatically via the APIs. Define the structure and attributes of your objects by using the class editor. Manage any data – products (PIM/MDM), categories, customers (CDP), orders (digital commerce), blog articles (DXP/CMS). Data Objects provide the possibility to manage structured data for multiple output channels from a single source. By centralizing data in one place, OpenDXP's data objects enable you to achieve better data completeness and data quality, allowing you to create and maintain a consistent, up-to-date customer experience across multiple touchpoints in less time. #### [Digital Assets](../04_Assets/README.md) Assets are the DAM part of OpenDXP. Store, manage and organize digital files such as images, videos, PDFs, Word/Excel documents in a folder structure. Preview 200+ file types directly in OpenDXP, edit pictures, and enrich files with additional meta-data. Facial recognition for focal points in images is available. Editors only need to maintain one high-resolution version of a file in the system. OpenDXP can automatically generate all required output formats for various channels such as commerce, apps, and websites. Of course, including comprehensive user management and version control. #### [Documents](../03_Documents/README.md) The DXP/CMS part of OpenDXP for managing unstructured content such as the pages of a website and its navigation. Based on Twig templates, documents render physical HTML/CSS pages and provide the capabilities to manage the presentation of data, exactly how customers will experience it. They can be composed by administrators by arranging predefined layout elements. OpenDXP documents provide multi-lingual and multi-site capabilities for websites, including emails and newsletters. Total frontend flexibility enables a perfect blend of content and commerce. You can also use them to create content for offline channels, such as printed catalogs (web-to-print). Most important, all elements (assets, documents or objects) can be linked and set into relation with each other. ### ANY Channel / ANY Process As OpenDXP is a platform that stores data independently from the channel, it can provide the managed data to any channel – simple websites (B2B, B2C), mobile apps, print, digital signage, ... there are basically no limits. In terms of output to the frontend or custom APIs, OpenDXP follows the MVC pattern and is based on the Symfony Framework. If you don't know the MVC pattern yet, please read [this article](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) first. If you are new to Symfony, you should read the [getting started guide](https://symfony.com/doc/current/) of Symfony first. With this knowledge, learning OpenDXP will be much easier. In addition to that, OpenDXP can also be executed in a headless way and therefore integrated into any environment. ### ANY One OpenDXP provides lots of functionality on top of its basic data elements that already cover lots of use cases. But being a platform, OpenDXP can be used for pretty much any use case and can be easily extended if necessary. ### OpenDXP Ecosystem The following list of resources should show you where to get information about OpenDXP and what's going on in the whole ecosystem. * [OpenDXP Documentation](../README.md) * [OpenDXP at Github](https://github.com/open-dxp/opendxp) * [OpenDXP Community Forums](https://github.com/open-dxp/opendxp/discussions) * [OpenDXP at Packagist](https://packagist.org/search/?q=opendxp) ----- Wanna see more - [Let's get started](../01_Getting_Started/README.md) --- ## Docker-Based Installation You can use Docker to set up a new OpenDXP Installation. You don't need to have a PHP environment with composer installed. #### Prerequisites * Your user must be allowed to run docker commands (directly or via sudo). * You must have docker compose installed. * Your user must be allowed to change file permissions (directly or via sudo). #### Follow These Steps 1. Create skeleton project via composer ```bash # empty skeleton package for experienced developers (`open-dxp/skeleton`). docker run -u `id -u`:`id -g` --rm -v `pwd`:/var/www/html opendxp/opendxp:php8.3-latest composer create-project open-dxp/skeleton my-project ``` 2. Go to your new project `cd my-project/` 3. Part of the new project is a docker compose file * Run `` echo `id -u`:`id -g` `` to retrieve your local user and group id * Open the `docker-compose.yaml` file in an editor, uncomment all the `user: '1000:1000'` lines and update the ids if necessary * Start the needed services with `docker compose up -d` 4. Install OpenDXP and initialize the DB `docker compose exec php vendor/bin/opendxp-install --mysql-host-socket=db --mysql-username=opendxp --mysql-password=opendxp --mysql-database=opendxp` (for demo package the installation can take a while) > [!NOTE] > If you choose to install backend search (which is installed by default), you must also adapt the [supervisor configuration](https://github.com/open-dxp/skeleton/blob/1.x/.docker/supervisord.conf#LL5C39-L5C90) and add the `opendxp_search_backend_message` receiver to build up the search index. 5. :heavy_check_mark: DONE - You can now visit your OpenDXP instance: * The frontend: [localhost](http://localhost) * The admin interface, using the credentials you have chosen above: [Admin interface](http://localhost/admin) ### Caching Make sure to use any sort of [caching](../../19_Development_Tools_and_Details/09_Cache/) to improve performance. We recommend Redis cache storage. ### Additional Information & Help If you would like to know more about the installation process or if you are having problems getting OpenDXP up and running, visit the [Installation Guide](../../23_Installation_and_Upgrade/README.md) section. ### Automating the Installation Process For more information about ways to automate the installation process, have a look on [Advanced Installation Topics](../02_Advanced_Installation_Topics/README.md). --- ## Webserver Installation The following guide assumes you're using a typical LAMP environment. If you're using a different setup (eg. Nginx) or you're facing a problem, please visit the [Installation Guide](../../23_Installation_and_Upgrade/README.md) section. ### 1. System Requirements Please have a look at [System Requirements](../../23_Installation_and_Upgrade/01_System_Requirements.md) and ensure your system is ready for OpenDXP. ### 2. Install OpenDXP & Dependencies The easiest way to install OpenDXP is from your terminal using Composer. Change into the root folder of your project: ```bash cd /your/project ``` > [!CAUTION] > Please remember: project root != document root #### Choose a Package to Install We offer 2 different installation packages: * a demo package with exemplary blueprints. * an empty skeleton package for experienced developers. ###### 1. Skeleton Package (only for experienced OpenDXP developers) ```bash COMPOSER_MEMORY_LIMIT=-1 composer create-project open-dxp/skeleton my-project ``` Point the document root of your vhost to the newly created `/public` folder (eg. `/your/project/public`). Keep in mind that OpenDXP needs to be installed **outside** of the **document root**. Specific configurations and optimizations for your web server are available here: [Apache](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/01_Apache_Configuration.md), [Nginx](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/02_Nginx_Configuration.md) OpenDXP requires write access to the following directories (relative to your project root): `/var`, `/public/var` ([Details](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/03_File_Permissions.md)) If you're running the installation using a [custom environment name](../../21_Deployment/03_Configuration_Environments.md), ensure you already have the right config files in place, e.g. `config/packages/[env_name]/config.yaml`. ### 2. Create Database ```bash mysql -u root -p -e "CREATE DATABASE project_database charset=utf8mb4;" ``` For further information please visit out [DB Setup Guide](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/05_DB_Setup.md) ### 3. Launch Installer ``` cd ./my-project ./vendor/bin/opendxp-install ``` This launches the interactive installer with a few questions. Make sure that you set the `memory_limit` to at least `512M` in your `php.ini` file. > [!NOTE] > OpenDxp allows a fully automated installation process. Read more here: [Advanced Installation Topics](../02_Advanced_Installation_Topics/README.md) ###### Open Admin Interface After the installer has finished, you can open the admin interface: `https://your-host.com/admin` ###### Debugging Installation Issues The installer writes a log in `var/log` which contains any errors encountered during the installation. Please have a look at the logs as a starting point when debugging installation issues. ### 5. Maintenance Cron Job Maintenance tasks are handled with Symfony Messenger. The `opendxp:maintenance` command will add the maintenance messages to the bus. However, `opendxp:maintenance` will not process the maintenance messages itself. Independent workers are required to consume these messages from the queues and perform maintenance tasks. In a typical OpenDXP installation, you should set up workers for these transports: | # | Transport name | Purpose | |---|--------------------------------|--------------------------------------------------------------------------------------------------| | 1 | opendxp_core | Core background tasks such as converting videos, rendering Asset previews, etc. | | 2 | opendxp_maintenance | [Maintenance tasks](../../20_Extending_OpenDxp/16_Maintenance_Tasks.md) | | 3 | opendxp_scheduled_tasks | [Scheduled tasks](../../18_Tools_and_Features/03_Scheduling.md) | | 4 | opendxp_image_optimize | Execute optimizers on Asset image thumbnails | | 5 | opendxp_asset_update | Process Asset metadata e.g. Documents page count, Video duration/dimensions, Image previews etc. | | 6 | opendxp_search_backend_message | Update the index for OpenDXP backend search. Only if you install `SimpleBackendSearchBundle` | Beware that the actual transports depend on which core bundles you installed. Therefore, you will need to adjust the list accordingly to your installation. Use `bin/console debug:messenger` to list all available transports. Consuming messages from the queues is performed with the `messenger:consume` command (e.g., `bin/console messenger:consume opendxp_core ...`). You might need to spawn multiple workers, each consuming from a different queue to avoid blocking message processing by long-running tasks. For example: ```bash bin/console messenger:consume opendxp_core opendxp_maintenance opendxp_scheduled_tasks opendxp_search_backend_message opendxp_asset_update bin/console messenger:consume opendxp_image_optimize ``` We recommend following the [Symfony Messenger guide](https://symfony.com/doc/current/messenger.html#deploying-to-production) for setting up worker processes in production. The following is a simplified example of maintenance tasks execution using cron: ```bash # this command needs to be executed via cron or similar task scheduler # it fills the message queue with the necessary tasks, which are then processed by messenger:consume */5 * * * * /your/project/bin/console opendxp:maintenance # it's recommended to run the following command using a process control system like Supervisor # please follow the Symfony Messenger guide for a best practice production setup: # https://symfony.com/doc/current/messenger.html#deploying-to-production */5 * * * * /your/project/bin/console messenger:consume opendxp_core opendxp_maintenance opendxp_scheduled_tasks opendxp_search_backend_message --time-limit=300 */5 * * * * /your/project/bin/console messenger:consume opendxp_asset_update --time-limit=300 */5 * * * * /your/project/bin/console messenger:consume opendxp_image_optimize --time-limit=300 ``` Refer to [Symfony Messenger](../02_Advanced_Installation_Topics/01_Symfony_Messenger.md) for further information on working with the messenger component in OpenDXP. > Depending on installed and activated extensions, it might be necessary to add additional transports to the messenger consume command. Please look at the documentation of corresponding extensions for more details. Keep in mind that the cron job has to run as the same user as the web interface to avoid permission issues (eg. `www-data`). For information about how to handle failed jobs, see this [section](../02_Advanced_Installation_Topics/01_Symfony_Messenger.md). ### Caching Make sure to use any sort of [caching](../../19_Development_Tools_and_Details/09_Cache/) to improve performance. We recommend Redis cache storage. ### 6. Additional Information & Help If you would like to know more about the installation process or if you are having problems getting OpenDXP up and running, visit the [Installation Guide](../../23_Installation_and_Upgrade/README.md) section. ### 7. Further Reading - [Symfony Messenger](../02_Advanced_Installation_Topics/01_Symfony_Messenger.md) - [Advanced Installation Topics](../02_Advanced_Installation_Topics/README.md) - [Apache Configuration](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/01_Apache_Configuration.md) - [Nginx Configuration](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/02_Nginx_Configuration.md) - [Database Setup](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/05_DB_Setup.md) - [Additional Tools Installation](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md) Next up - [Directories Structure](../03_Directory_Structure.md) --- ## Symfony Messenger ### Handle Failed Jobs If maintenance jobs fail during processing, they are discarded from the respective transport after a defined number of retries. However, you can move the failed jobs to a new transport (e.g. `opendxp_failed_jobs`) instead of discarding them completely with following config: ```yaml framework: messenger: transports: opendxp_failed_jobs: dsn: "doctrine://default?queue_name=opendxp_failed_jobs&table_name=messenger_messages_opendxp_failed" opendxp_core: dsn: "doctrine://default?queue_name=opendxp_core" # For RabbitMQ (recommended) use this as example: # dsn: "amqp://rabbitmq:5672/%2f/opendxp_core" failure_transport: opendxp_failed_jobs ``` which can be re-processed later after fixing the underlying issue with command `bin/console messenger:consume opendxp_failed_jobs`. Please follow the [Symfony docs](https://symfony.com/doc/current/messenger.html#saving-retrying-failed-messages) for options on failed jobs processing. We recommend [RabbitMQ](https://www.rabbitmq.com/#getstarted) as a message queue. For a tutorial, check this [link](https://www.rabbitmq.com/tutorials/tutorial-one-php.html). For an example configuration, refer to [this link](https://github.com/open-dxp/skeleton/blob/1.x/.docker/messenger.yaml). --- ## Advanced Installation Topics To fully automate the installation process, options can be passed in the CLI as parameters, rather than adding them interactively. ###### For Docker installation: ```bash docker compose exec php vendor/bin/opendxp-install --admin-username=admin --admin-password=admin \ --mysql-username=username --mysql-password=password --mysql-database=opendxp \ --mysql-host-socket=127.0.0.1 --mysql-port=3306 \ --no-interaction ``` ###### For webserver installation: ```bash ./vendor/bin/opendxp-install --admin-username=admin --admin-password=admin \ --mysql-username=username --mysql-password=password --mysql-database=opendxp \ --mysql-host-socket=127.0.0.1 --mysql-port=3306 \ --no-interaction ``` > [!NOTE] > The `--no-interaction` flag will prevent any interactive prompts. To avoid having to pass sensitive data (e.g. DB password) as command line option, you can also set each parameter as env variable. See `./vendor/bin/opendxp-install` for details. Example: ```bash $ OPENDXP_INSTALL_MYSQL_USERNAME=username OPENDXP_INSTALL_MYSQL_PASSWORD=password ./vendor/bin/opendxp-install \ --admin-username=admin --admin-password=admin \ --mysql-database=opendxp \ --no-interaction ``` #### Installing Bundles ##### Overview of Bundle Lists When installing, you will [interact with](#modifying-required-bundles-and-bundle-recommendations) two lists of bundles: **Recommended Bundles** and **Required Bundles**. - **Recommended Bundles**: - Displayed to users during interactive mode. - These are the bundles users can specify when using the `--install-bundles=commaSeparatedBundleList` option. - **Required Bundles**: - These bundles will automatically be installed in interactive mode, if the user choses to install bundles. - They are installed whenever the `--install-bundles` option is set. ##### Default Recommended Bundles By default, here's what's included in the Recommended Bundles list: - [OpenDxpApplicationLoggerBundle](../../18_Tools_and_Features/17_Application_Logger.md) - [OpenDxpCustomReportsBundle](../../18_Tools_and_Features/29_Custom_Reports.md) - [OpenDxpGlossaryBundle](../../18_Tools_and_Features/21_Glossary.md) - OpenDxpSeoBundle (for SEO-related topics: [Site Declarations](../../18_Tools_and_Features/38_Site_Declarations.md), [Sitemaps](../../18_Tools_and_Features/39_Sitemaps.md) and [Redirects](../../02_MVC/04_Routing_and_URLs/04_Redirects.md)) - OpenDxpSimpleBackendSearchBundle (for default search functionality in Backend UI interface) - [OpenDxpStaticRoutesBundle](../../02_MVC/04_Routing_and_URLs/02_Custom_Routes.md) - [OpenDxpUuidBundle](../../19_Development_Tools_and_Details/19_UUID_Support.md) - OpenDxpWordExportBundle (for import/export functionality for translations in Word format) - OpenDxpXliffBundle (for import/export functionality for translations in Xliff format) ##### Automating Bundle Installation To install specific bundles automatically, use the `--install-bundles[=bundleList]` flag. This flag installs and activates all required bundles and any specified bundles, provided they are part of the recommended bundles list. **Note**: The bundles will be automatically added to `config/bundles.php`. ```bash ./vendor/bin/opendxp-install --admin-username=admin --admin-password=admin \ --mysql-username=username --mysql-password=password --mysql-database=opendxp \ --mysql-host-socket=127.0.0.1 --mysql-port=3306 \ --install-bundles=OpenDxpApplicationLoggerBundle,OpenDxpCustomReportsBundle \ --no-interaction ``` ##### Modifying Required Bundles and Bundle Recommendations The `BundleSetupEvent` is triggered under two circumstances: 1. To preset the installable (recommended) and automatically installed (required) bundles for the `--install-bundles` option. 2. To modify a list of recommended bundles in interactive mode. Required bundles are not installed if the user declines to install bundles. By subscribing or listening to the `BundleSetupEvent`, you can add or remove bundles from the required or recommended lists. For practical examples, refer to the [OpenDXP Skeleton](https://github.com/open-dxp/skeleton). It shows how the [Admin UI Classic Bundle](https://github.com/open-dxp/admin-bundle) is integrated. ```php [ ['bundleSetup'], ], ]; } public function bundleSetup(BundleSetupEvent $event): void { // make bundle installable (using --install-bundles) and recommend it in interactive installation $event->addInstallableBundle('OpenDxpAdminBundle', OpenDxpAdminBundle::class, true); // add required bundle $event->addRequiredBundle('OpenDxpAdminBundle', OpenDxpAdminBundle::class); } } ``` Make sure to register your listener/subscriber under `config/installer.yaml` as described in [Preconfiguring the Installer](#preconfiguring-the-installer). ```yaml services: # default configuration for services in *this* file _defaults: # automatically injects dependencies in your services autowire: true # automatically registers your services as commands, event subscribers, etc. autoconfigure: true # this means you cannot fetch services directly from the container via $container->get() # if you need to do this, you can override this setting on individual services public: false # --------------------------------------------------------- # Event Subscribers # --------------------------------------------------------- App\EventSubscriber\BundleSetupSubscriber: ~ ``` #### Preconfiguring the Installer You can preconfigure the values used by the installer by adding a config file which sets values for the database credentials. This is especially useful when installing OpenDXP on platforms where credentials are available via env vars instead of having direct access to them. To preconfigure the installer, add a config file in `config/installer.yaml` (note: the file can be of any format supported by Symfony's config, so you could also use xml or php as the format), then configure the `opendxp_install` tree: ```yaml # config/installer.yaml opendxp_install: parameters: database_credentials: user: username password: password dbname: opendxp # env variables can be directly read with the %env() syntax # see https://symfony.com/blog/new-in-symfony-3-2-runtime-environment-variables host: "%env(DB_HOST)%" port: "%env(DB_PORT)%" ``` ### Set a Time Zone Make sure to set the corresponding time zone in your configuration. It will be used for displaying date/time values in the admin backend. ```yaml opendxp: general: timezone: Europe/Berlin ``` ### Office Document Preview The feature for displaying a [preview of documents](../../04_Assets/03_Working_with_Thumbnails/05_Document_Thumbnails.md) directly in OpenDXP is optional. To use it, you must install either [Gotenberg](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md#gotenberg) or [LibreOffice](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md#libreoffice-pdftotext-inkscape-) according to your preference. --- ## Directory Structure After installing a OpenDXP package you should see the folder structure described below. The following table should give you a quick overview about the purpose of each folder. In general the directory structure follows the [best practice for Symfony projects](https://github.com/symfony/symfony-demo). | Directory | Description | |------------------------------------------------------|-------------------------------------------| | `/bin/` | Executable files (e.g. bin/console). | | `/config/` | The application configuration. | | `/public/` | This is the **document root** (public folder) for your project - point your vhost to this directory! | | `/src/` | The project's PHP code (Services, Controllers, EventListeners, ...) | | `/templates/`| The application templates. | | `/var/` | Private generated files - not accessible via the web (cache, logs, etc.). | | `/vendor/` | All third-party libraries are there. It's the default location for packages installed by [Composer](https://getcomposer.org/) / [Packagist](https://packagist.org/). | #### The `public/` Directory The web root directory is the home of all public and static files like images, stylesheets and JavaScript files. It is also the place where each front controller (the file that handles all requests to your application) lives, such as the [production controller](https://github.com/open-dxp/skeleton/blob/1.x/public/index.php) #### The `src/` Directory The Kernel class is the main entry point of the Symfony application configuration and as such, it is stored in the `src/` directory. For more information about the folder structure and the architecture in general, please have a look at the [Symfony documentation](https://symfony.com/doc/current/best_practices.html#use-the-default-directory-structure). --- ## Configuration(Getting_Started) OpenDXP's configuration can be found in several places: * Configurations in `var/config/*.(php|yaml)` are written from the admin interface. For example the `system.yaml` file contains the settings from [System Settings](../18_Tools_and_Features/25_System_Settings.md) * The Symfony configuration tree (mainly distributed throughout `*.yaml` files) contains all Symfony as well as most of the OpenDXP related configurations. * A set of `OPENDXP_*` constants which are used to resolve various filesystem paths ### Symfony Configuration Many aspects of OpenDXP can be configured through the [Symfony Config](https://symfony.com/doc/current/bundles/configuration.html) tree defined under the `opendxp` and `opendxp_admin` extension. These values can be changed through config files in `config` (e.g. `config/config.yaml)`). OpenDXP additionally includes a set of standard configuration files which, in contrast to a standard Symfony project, are not located in `config/`, but in the [OpenDxpCoreBundle](https://github.com/open-dxp/opendxp/tree/11.x/bundles/CoreBundle/config/opendxp). This allows us to ship and update default configurations without affecting project code in `config/`. See [Auto loading config and routing definitions](../20_Extending_OpenDxp/13_Bundle_Developers_Guide/03_Auto_Loading_Config_And_Routing_Definitions.md) for details how this works. Standard configs will be merged with your custom config in `config/` to build the final config tree. You can debug the values stored in the tree through the following command: ```bash # this is a core Symfony command and works for every bundle, just omit the # "opendxp" argument to get a list of all bundles $ bin/console debug:config opendxp ``` In addition, you can print a reference of valid configuration sections with the following command: ```bash $ bin/console config:dump-reference opendxp ``` ### OpenDXP constants OpenDXP uses several constants for locating certain directories like logging, assets, versions etc. These constants are defined in [`lib/Bootstrap.php`](https://github.com/open-dxp/opendxp/blob/1.x/lib/Bootstrap.php). If you need to overwrite these constants (e.g. for using a special directory for assets or versions at an object storage at AWS S3), you have multiple ways to do so: * Create a file in `/config/opendxp/constants.php` setting the constants you need. OpenDXP will skip setting any constants which are already defined. * Define an environment variable named after the constant. When defining a constant, OpenDXP will look if an env variable with the same name is defined and use that instead of the default value. * Define an environment variable in a `/.env` file which will be automatically loaded through the [Symfony DotEnv](https://github.com/symfony/dotenv) component if it exists. Environment variables defined here will have the same effect as "real" environment variables. See the [Environment-Specific Configurations](../21_Deployment/03_Configuration_Environments.md) section for more details. The [OpenDXP Skeleton](https://github.com/open-dxp/skeleton) repository contains an example file, [`constants.example.php`](https://github.com/open-dxp/skeleton/blob/1.x/config/opendxp/constants.example.php). The following file is an example of how you can overwrite some paths: ```php {{ opendxp_input("headline", {"width": 540}) }} {% for i in opendxp_iterate_block(opendxp_block('contentblock')) %}

{{ opendxp_input('subline') }}

{{ opendxp_wysiwyg('content') }} {% endfor %} {% endblock %} ``` OpenDXP uses by default Symfony Twig engine, so you have the full power of Symfony templates with all Symfony functionalities available. In addition to that, there are some OpenDXP specific additions like the so called *editables*, which add editable parts (placeholders) to the layout and some custom templating helpers. For details concerning editables (like `opendxp_input`, `opendxp_block`, ...) see [Editables](../03_Documents/01_Editables/README.md). #### Add a Layout We can use Symfony's [template inheritance and layout](https://symfony.com/doc/current/templates.html#template-inheritance-and-layouts) functionality to wrap our content page with another template which contains the main navigation, a sidebar, … using the following code: ```twig {% extends 'layout.html.twig' %} ``` We tell the engine that we want to use the layout `layout.html.twig`. Now create a new Twig template in the folder `/templates` and name it `layout.html.twig`. Then we can also put some HTML and template code into it: ```twig Example
{{ block('content') }}
``` The code `{{ block('content') }}` is the placeholder where the content of the page will be inserted. #### Putting It All Together With OpenDXP Documents Now we need to connect the action to a page in the OpenDXP backend, so that the page knows which action (and therefore also which template) needs to be executed/processed. First, click right on *Home* in the *Documents* panel and Select *Add Page* > *Blank* to add a new page. ![Create page](../img/OpenDxp_Elements_check_homepage.png) Now select the tab *Settings* in the newly opened tab. Select the Controller::Action and template (if different from controller action naming). You can test the new controller and action, after saving the document (press *Save & Publish*). Select the tab *Edit*, to see your page with all the editable placeholders. ## Introduction to Assets In assets, all binary files like images, videos, office files and PDFs, ... can be uploaded, stored and managed. You can organize them in a directory structure and assign them additional meta data. Once uploaded, an asset can be used and linked in multiple places - e.g. documents or objects. In terms of images or videos, always upload only one high quality version (best quality available). [Thumbnails](../04_Assets/03_Working_with_Thumbnails/01_Image_Thumbnails.md) for different output channels are created directly [within OpenDXP](../04_Assets/03_Working_with_Thumbnails/01_Image_Thumbnails.md) using custom configurations. For this tutorial, at least add one file which you will use in an object later. There are many ways to upload files: 1. Drag & drop files from your file explorer into the browser on the desired asset folder 2. Right click on *Home* and choose the most suitable method for you ![Upload assets](../img/asset-upload.png) ## Introduction to Objects We've already made a controller, action and a view so we're able to add text from within the admin panel to our pages. In this chapter we will create a simple product database and use them in our CMS pages. Objects are used to store any structured data independently from the output-channel and can be used anywhere in your project. ### Create the Class Model/Definition Go to: *Settings -> Object -> Classes* and click the button *Add Class*. ![Add product class](../img/OpenDxp_Elements_class_add.png) Now, there is a new product class/model which is a representation of your entity including the underlying database scheme as well as a generated PHP class you can use to create, update, list and delete your entities. More specific backgrounds and insights can be found in the [Objects section](../05_Objects/README.md) The product should have the following attributes: **SKU**, **picture**, **name** and **description**. Follow these steps to add them: * Go to the edit page of the class product * Click right on *Base* and select *Add Layout Component -> Panel* - This is the main panel/container for the following product attributes * To add attributes: * Click right on *Panel*, then *Add data component -> Text -> Input*, then change the name of the input component to **sku** (in the edit panel on the right side) * Just the same way you add the new data field for **name** * Now we're going to add a WYSIWYG attribute for the **description**. Again, click right, select *Add data component -> Text -> WYSIWYG*. We name it *description*. * The last attribute is for the picture. We can use on of the specialized image components in *Other -> Image*. Name the attribute **picture**. **Important:** Every generated class in the OpenDXP admin panel has an associated PHP class with getters and setters. You can find the PHP class representation of our newly created class definition above in `var/classes/DataObject/Product.php` ### Add a new Object We've just prepared a simple class for new products. Now we can use it to create objects in OpenDXP. * Open the objects section on the left and click on the right button after *Home* (Note that you can also create directory structures for objects). * Choose *Add object -> product* and fill the input with a name, for example: *tshirt* * Add values for sku, name and description attributes. * Click *Save & Publish* The last step to finish the product object is adding a photo. One way to upload a photo is using this button: ![Upload image to an object](../img/OpenDxp_Elements_upload_button.png) or just drag a file that you uploaded from the Assets section. Click *Save & Publish* button. That's it. ![Complete object](../img/OpenDxp_Elements_complete_object.png) ## Putting the Pieces Together Let's put the pieces together and connect the products to the CMS. ### Update Controller and Template Therefore create another action in the controller (ContentController) called `productAction`. ```php render('content/product.html.twig'); } } ``` Then we also need a new template for our product action: `templates/content/product.html.twig` ```twig {% extends 'layout.html.twig' %} {% block content %}

{{ opendxp_input("headline", {"width": 540}) }}

{% if editmode %} {{ opendxp_relation("product") }} {% else %} {% endif %}
{% endblock %} ``` `{{ editmode }}` is a standard variable (it's always set), that checks if the view is called from the OpenDXP admin backend and gives you the possibility to do different stuff in editmode and in the frontend. `{{ opendxp_relation("product") }}` is one of the possible editable placeholders. It can be used to make 1 to 1 relations. A cool alternative for that would be the [Renderlet](../03_Documents/01_Editables/28_Renderlet.md) editable. Click [here](../03_Documents/01_Editables/README.md) for a full list of available editables in OpenDXP. ### Add the Product Object to a Document The last thing is to show the product in the body of the document you created. Let's go back to the documents section. Right click on *Home* then *Add Page* > *Empty Page*. In the settings label, choose the `product` action and the `Content` controller, click save and go back to the edit tab. Now you can see the new editable element (`relation`) which we added in the product template above. Drag the product object to that editable and press *Save & Publish*. Let's see what happened on the frontend... Go to the product page. In my case, let's say `http://opendxp.local/tshirt` where *tshirt* is the identifier of the product (the name visible the documents tree). We haven't implemented frontend features yet, therefore the page doesn't contain any product information. Add a few lines in the template file (`templates/content/product.html.twig`): ```twig {% extends 'layout.html.twig' %} {% block content %}

{{ opendxp_input("headline", {"width": 540}) }}

{% if editmode %} {{ opendxp_relation("product") }} {% else %} {% set product = opendxp_relation("product").element %} {% if product %}

{{ product.name }}

{{ product.description|raw }}
{% endif %} {% endif %}
{% endblock %} ``` You are now able to access the linked object above by using the method `getElement()`. Now you have access to the entire data from the linked object (name, description, ...). ### Add a Thumbnail Configuration To show the product image in the view, we need to add a thumbnail configuration first. Using [thumbnail configurations](../04_Assets/03_Working_with_Thumbnails/01_Image_Thumbnails.md), OpenDXP automatically renders optimized images for certain output channels (including high-res @2x versions). Adding a thumbnail configuration can be achieved by adding a configuration as depicted below. For now, simply add a configuration named `content`. ### Showing the Image in the View Last but not least, we would like to show the product picture: ```twig
{% if product.picture %} {{ product.picture.thumbnail("content").html|raw }} {% endif %} {{ product.description|raw }}
``` As you can see, Image is an additional class with useful attributes and functions. To print out the image in the right size just use the method `thumbnail.html` which returns the `` or `` (when using media queries in your config) tag with the correct image path and also sets alt attributes to values based on the asset meta data. --- ## Getting Started With OpenDXP This section provides a quick getting-started tutorial for OpenDXP and covers the following topics: 1. Installation of OpenDXP: - via [Docker](../01_Getting_Started/00_Installation/00_Docker_Based_Installation.md) - via [Webserver](../01_Getting_Started/00_Installation/01_Webserver_Installation.md) 2. [Advanced Installation Topics](./02_Advanced_Installation_Topics/README.md): - [Symfony Messenger and How to Handle Failed Jobs](./02_Advanced_Installation_Topics/01_Symfony_Messenger.md) 3. [Directory Structure of OpenDXP](./03_Directory_Structure.md) 4. [Configuration](./04_Configuration.md) 5. [Architecture Overview](./05_Architecture_Overview.md) 6. [Creating your First Project](./06_Create_a_First_Project.md) --- ## OpenDXP Controller ### Introduction OpenDXP controllers play the designated role in the MVC pattern. They bind the design patterns together and contain or delegate the functionality of the application. It is good practise to keep the controllers as lean as possible and encapsulate the business logic into models or services/libraries. OpenDXP offers an abstract class (`OpenDxp\Controller\FrontendController`), which can be implemented by your controllers. This abstract class adds some OpenDXP specific dispatching features - especially in combination with OpenDXP Documents, multi-language support etc. The naming of the file and the class is just the same as in Symfony. ### OpenDXP Specialities and Examples | Controller Name | File Name | Class Name | Default View Directory | |-----------------|----------------------------------------|------------------------------------|------------------------| | Content | `src/Controller/ContentController.php` | `App\Controller\ContentController` | `/templates/content` | | News | `src/Controller/NewsController.php` | `App\Controller\NewsController` | `/templates/news` | In controllers, for every action there exists a separate method ending with the `Action` suffix. The `DefaultController` comes with OpenDXP. When you create an empty page in OpenDXP it will call the `defaultAction` in the `DefaultController` which uses the view `/templates/default/default.html.twig`. You can render templates just the [standard Symfony way](https://symfony.com/doc/current/templates.html#rendering-a-template-in-emails), by either using `$this->render('foo.html.twig')` or using the `#Template[]` [attribute](https://symfony.com/doc/current/templates.html#rendering-a-template-in-controllers). #### Examples ```php >render() and passing the parameter 'foo' */ public function myAction(): Response { return $this->render('content/default.html.twig', ["foo" => "bar"]); } /** * Example using the #[Template] attribute to resolve the view. * The frontend controller also provides methods to add response headers or via attributes without having * access to the final response object (as it is automatically created when rendering the view). * */ #[Template('/default/header.html.twig')] #[ResponseHeader(key: "X-Foo", values: ["123456", "98765"])] public function headerAction(Request $request): array { // schedule a response header via code $this->addResponseHeader('X-Foo', 'bar', false, $request); return ["foo" => "bar"]; } /** * This action returns a JSON response. */ public function jsonAction(Request $request): JsonResponse { return $this->json(array('key' => 'value')); } /** * This returns a standard symfony Response object */ public function customAction(Request $request): Response { return new Response("Just some text"); } } ``` ###### There are also some properties which can be useful: | Name | Type | Description | |-------------------|-------------|----------------------------------------------------------| | `$this->document` | Document | Reference to the current document, if any is available. | | `$this->editmode` | boolean | True if you are in editmode (admin) | --- ## Template Inheritance and Layouts ### Introduction Layouts define everything that repeats on one page to another, such as a header, footer, navigation. Layouts often contain the basic structure of a HTML document, such as ``, `` and the `` tag as well as scripts and stylesheets. In Symfony/OpenDXP, this problem is thought about differently: a template can be decorated by another one. This works exactly the same as PHP classes: template inheritance allows you to build a base "layout" template that contains all the common elements of your site defined as blocks (think "PHP class with base methods"). A child template can extend the base layout and override any of its blocks (think "PHP subclass that overrides certain methods of its parent class"). Layout scripts are just normal view scripts and are located together with normal view scripts in: `/templates` For more details about template inheritance and layouts, please have a look at the [Symfony documentation](https://symfony.com/doc/current/templating.html#template-inheritance-and-layouts). ### Usage of Layouts ###### A Simple Sample Layout Looks Like the Following: ```twig Example
{{ block('content') }}
``` Of course, editables and template helpers can be used within the layout file and therefore layouts can become much more complicated. The most important line though is `{{ block('content') }}`. It includes the actual rendered content of the view. ###### Use a Layout in a template Layouts are simply used by declaring a parent template with the following code. ```twig {% extends 'layout.html.twig' %} ``` In this example we extend from the template `layout.html.twig`, but we can use any other and as many as needed scripts instead. A complete example of a document page would look like the following: ```twig {% extends 'layout.html.twig' %} ... {% block content %}

{{ opendxp_input('headline', {'width': 540}) }}

{% endblock %} ``` --- ## Placeholder Templating Extension The `Placeholder` extension is used to persist content between view scripts and view instances. It also offers some useful features such as aggregating content, capturing view script content for later use, and adding pre- and post-text to content (and custom separators for aggregated content). #### Basic Usage Basic usage of placeholders is to persist view data. Each invocation of the Placeholder extension expects a placeholder `name`. The helper then returns a placeholder container object that you can either manipulate or simply echo out. ```twig {% do opendxp_placeholder('foo').set("Some text for later") %} {# outputs "Some text for later" #} {{ opendxp_placeholder('foo') }} ``` #### Aggregate Content Aggregating content via placeholders can be useful at times as well. For instance, your view script may have a variable array from which you wish to retrieve messages to display later. A later view script can then determine how those will be rendered. The Placeholder view helper uses containers that extend ArrayObject, providing a rich feature set for manipulating arrays. In addition, it offers a variety of methods for formatting the content stored in the container: - `setPrefix($prefix)` sets text with which to prefix the content. Use `getPrefix()` at any time to determine what the current setting is. - `setPostfix($postfix)` sets text with which to append the content. Use `getPostfix()` at any time to determine what the current setting is. - `setSeparator($seperator)` sets text with which to separate aggregated content. Use `getSeparator()` at any time to determine what the current setting is. - `setIndent($indent)` can be used to set an indentation value for content. If an integer is passed, that number of spaces will be used. If a string is passed, the string will be used. Use `getIndent()` at any time to determine what the current setting is. ```twig {% do opendxp_placeholder('foo').setPrefix("
    \n
  • ") .setSeparator("
  • \n") .setIndent(4) .setPostfix("
\n") %} {# outputs as unordered list with pretty indentation #} {{ opendxp_placeholder('foo') }} ``` #### Capture Content (deprecated) Occasionally you may have content for a placeholder in a view script that is easiest to template. The `Placeholder` extension allows you to capture arbitrary content for later rendering using the following API. - `captureStart($type, $key)` begins capturing content. - `$type` should be one of the Placeholder constants `APPEND` or `SET`. If `APPEND`, captured content is appended to the list of current content in the placeholder. If `SET`, captured content is used as the sole value of the placeholder (potentially replacing any previous content). By default, `$type` is `APPEND`. - `$key` can be used to specify a specific key in the placeholder container to which you want content captured. - `captureStart()` locks capturing until `captureEnd()` is called; you cannot nest capturing with the same placeholder container. Doing so will raise an exception. - `captureEnd()` stops capturing content, and places it in the container object according to how `captureStart()` was called. ```twig {# Default capture: append #} {% do opendxp_placeholder('foo').captureStart() %} {% for datum in data %}

{{ datum.title }}

{{ datum.content }}

{% endfor %} {% do opendxp_placeholder('foo').captureEnd() %} {{ opendxp_placeholder('foo') }} ``` ```twig {#Default capture: to key #} {% do opendxp_placeholder('foo').captureStart('SET', 'data') %} {% for datum in data %}

{{ datum.title }}

{{ datum.content }}

{% endfor %} {% do opendxp_placeholder('foo').captureEnd() %} {{ opendxp_placeholder('foo').data | raw }} ``` **Note:** The `captureStart()` and `captureEnd()` methods are deprecated as of OpenDXP 1.0. Use a combination of `set` and `opendxp_placeholder` to achieve the same result. ```twig {% set placeholderData %} {% for datum in data %}

{{ datum.title }}

{{ datum.content }}

{% endfor %} {% endset %} {% do opendxp_placeholder('foo').set(placeholderData) %} {{ opendxp_placeholder('foo') }} ``` ```twig {% set placeholderData %} Test to append some additional content {% endset %} {% do opendxp_placeholder('foo').append(placeholderData) %} {{ opendxp_placeholder('foo') }} ``` --- ## HeadLink Templating Extension > The HeadLink templating extension extends [Placeholder Templating Extension](./00_Placeholder.md) The HTML `` element is increasingly used for linking a variety of resources for your site: stylesheets, feeds, favicons, trackbacks, and more. The HeadLink helper provides a simple interface for creating and aggregating these elements for later retrieval and output in your layout script. The HeadLink helper has special methods for adding stylesheet links to its stack: - `appendStylesheet($href, $media, $conditionalStylesheet, $extras)` - `offsetSetStylesheet($index, $href, $media, $conditionalStylesheet, $extras)` - `prependStylesheet($href, $media, $conditionalStylesheet, $extras)` - `setStylesheet($href, $media, $conditionalStylesheet, $extras)` The `$media` value defaults to `screen`, but may be any valid media value. `$conditionalStylesheet` is a string or boolean `FALSE`, and will be used at rendering time to determine if special comments should be included to prevent loading of the stylesheet on certain platforms. `$extras` is an array of any extra values that you want to be added to the tag. Additionally, the HeadLink helper has special methods for adding 'alternate' links to its stack: - `appendAlternate($href, $type, $title, $extras)` - `offsetSetAlternate($index, $href, $type, $title, $extras)` - `prependAlternate($href, $type, $title, $extras)` - `setAlternate($href, $type, $title, $extras)` The `headLink()` helper method allows specifying all attributes necessary for a `` element, and allows you to also specify placement -- whether the new element replaces all others, prepends (top of stack), or appends (end of stack). ### Basic Usage You may specify a headLink at any time. Typically, you will specify global links in your layout script, and application specific links in your application view scripts. In your layout script, in the `` section, you will then echo the helper to output it. ```twig {# setting links in a view script: #} {% do opendxp_head_link().appendStylesheet('/styles/basic.css') %} {% do opendxp_head_link({rel: 'icon', href: '/img/favicon.ico'}, 'PREPEND').prependStylesheet('/styles/moz.css', 'screen', true, {id: 'my_stylesheet'}) %} {# rendering the links: #} {{ opendxp_head_link() }} ``` ### HTTP/2 Push Support The HeadLink and HeadScript helpers have internal support for the [WebLink Component](https://symfony.com/blog/new-in-symfony-3-3-weblink-component). While you can call `$this->webLink()->preload('/path/to/file.css', ['as' => 'style'])` directly in your templates, the HeadLink and HeadScript helpers take care of adding a cache buster aware link instead of the unprefixed file path. Push support is currently opt-in - to make the helpers automatically include links to the served assets either enable it globally on the helper level or individually for each item. ```twig {# enable web links for every item #} {% do opendxp_head_link().enableWebLinks() %} {# set web link attributes passed to every item #} {% do opendxp_head_link().setWebLinkAttributes({as: 'style'}) %} {# enable webLink on an item level #} {# the item will be added even if enableWebLinks() was not called #} {% do opendxp_head_link().setWebLinkAttributes({as: 'style'}) %} {# disable webLink on an item level #} {# the item won't be added even if enableWebLinks() was called #} {% do opendxp_head_link().appendStylesheet('/static/css/styles.css', 'screen', false, {webLink: {as: 'style'}}) %} {# override the used method (default is preload()) #} {% do opendxp_head_link().appendStylesheet('/static/css/styles.css', 'screen', false, {'webLink': {method: 'prefetch'}}) %} ``` Added links will be handled by the web link component and injected into the response. Make sure Symfony is properly configured (this setting is enabled by default from OpenDXP's core config): ```yaml # config.yaml framework: web_links: enabled: true ``` --- ## HeadMeta Templating Extension > The HeadMeta templating extension extends [Placeholder Templating Extension](./00_Placeholder.md) The HTML `` element is used to provide meta information about your HTML document -- typically keywords, document character set, caching pragmas, etc. Meta tags may be either of the `http-equiv` or `name` types, must contain a `content` attribute, and can also have either of the `lang` or `scheme` modifier attributes. The HeadMeta helper supports the following methods for setting and adding meta tags: - `appendName($keyValue, $content, $conditionalName)` - `offsetSetName($index, $keyValue, $content, $conditionalName)` - `prependName($keyValue, $content, $conditionalName)` - `setName($keyValue, $content, $modifiers)` - `appendHttpEquiv($keyValue, $content, $conditionalHttpEquiv)` - `offsetSetHttpEquiv($index, $keyValue, $content, $conditionalHttpEquiv)` - `prependHttpEquiv($keyValue, $content, $conditionalHttpEquiv)` - `setHttpEquiv($keyValue, $content, $modifiers)` - `appendProperty($property, $content, $modifiers)` - `offsetSetProperty($index, $property, $content, $modifiers)` - `prependProperty($property, $content, $modifiers)` - `setProperty($property, $content, $modifiers)` The `$keyValue` item is used to define a value for the `name` or `http-equiv` key; `$content` is the value for the `content` key, and `$modifiers` is an optional associative array that can contain keys for `lang` and/or `scheme`. You may also set meta tags using the `headMeta()` helper method, which has the following signature: `headMeta($content, $keyValue, $keyType = 'name', $modifiers = [], $placement = 'APPEND')`. `$keyValue` is the content for the key specified in `$keyType`, which should be either `name` or `http-equiv`. `$placement` can be `SET` (overwrites all previously stored values), `APPEND` (added to end of stack), or `PREPEND` (added to top of stack). HeadMeta overrides each of `append()`, `offsetSet()`, `prepend()`, and `set()` to enforce usage of the special methods as listed above. Internally, it stores each item as a `stdClass` token, which it later serializes using the `itemToString()` method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned. #### Basic Usage You may specify a new meta tag at any time. Typically, you will specify client-side caching rules or SEO keywords. For instance, if you wish to specify SEO description, you'd be creating a meta name tag with the name 'keywords' and the content the keywords you wish to associate with your page: ```twig {# setting meta description #} {% do opendxp_head_meta().appendName('description', 'My SEO description for my awesome page') %} {# setting open graph tags #} {% do opendxp_head_meta().setProperty('og:title', 'my article title') %} {% do opendxp_head_meta().setProperty('og:type', 'article') %} {# setting content type and character set #} {% do opendxp_head_meta().appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8').appendHttpEquiv('Content-Language', 'en-US') %} ``` When you're ready to place your meta tags in the layout, simply echo the helper: ```twig {{ opendxp_head_meta() }} ``` --- ## HeadScript Templating Extension > The HeadScript templating extension extends [Placeholder Templating Extension](./00_Placeholder.md) The HTML ` ``` Read more about [Video Thumbnails](../../04_Assets/03_Working_with_Thumbnails/03_Video_Thumbnails.md). --- ## WYSIWYG Editable ### General Similar to Textarea and Input you can use the WYSIWYG editable in the templates to provide rich-text editing. Quill is installed by default in our demo. Another editor can be installed via the wysiwyg-events you find in `events.js` ### Configuration | Name | Type | Description | |----------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------| | `height` | integer | Height of the WYSIWYG editable in pixel | | `width` | integer | Width of the WYSIWYG editable in pixel | | `class` | string | A CSS class that is added to the surrounding container of this element in editmode | | `placeholder` | string | A text shown in the field when it is empty to guide the user about the expected type of input. | | `defaultValue` | string | A default value for the available options. Note: This value needs to be saved before calling getData() or use setDataFromResource(). | | `required` | boolean | (default: false) set to true to make field value required for publish | ### Example ```twig {{ opendxp_wysiwyg("myWYSIWYG", { "height": 600, "width": 1100, "placeholder": "Enter your content" }) }} ``` ### Add a Custom Editor Make sure that you add the Editor to `opendxp.wysiwyg.editors`. This array can be used to have different editors for different use cases (documents, objects ...): ```javascript if(!parent.opendxp.wysiwyg) { parent.opendxp.wysiwyg = {}; parent.opendxp.wysiwyg.editors = []; } parent.opendxp.wysiwyg.editors.push("Custom_Editor"); ``` The Editor als needs to dispatch the `opendxp.events.changeWysiwyg` to set the value from the WYSIWYG-Field in the core. ```javascript document.dispatchEvent(new CustomEvent(opendxp.events.changeWysiwyg, { detail: { e: {target:{id: textareaId}}, data: this.activeEditor.getSemanticHTML(), //text of the editor-field context: e.detail.context //the context in which the editor is registered (object, document ...) } })); ``` Please use the events from `event.js` to bind your Editor on the field and to configure it. For more details please take a look at the `QuillBundle`. ### Extending symfony HTML sanitizer configuration Wysiwyg editables are using symfony HTML sanitizer in order to clean the HTML content from unwanted tags and parameters. Default configuration is defined like this: ``` framework: html_sanitizer: sanitizers: opendxp.wysiwyg_sanitizer: max_input_length: -1 allow_attributes: opendxp_type: '*' opendxp_id: '*' allow_relative_links: true allow_relative_medias: true allow_elements: span: [ 'class', 'style', 'id' ] div: [ 'class', 'style', 'id' ] p: [ 'class', 'style', 'id', 'dir', 'data-cell' ] strong: 'class' em: 'class' h1: [ 'class', 'style', 'id' ] h2: [ 'class', 'style', 'id' ] h3: [ 'class', 'style', 'id' ] h4: [ 'class', 'style', 'id' ] h5: [ 'class', 'style', 'id' ] h6: [ 'class', 'style', 'id' ] a: [ 'class', 'id', 'href', 'target', 'title', 'rel', 'style' ] table: [ 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'width', 'height', 'id' ] colgroup: 'class' col: [ 'class', 'style', 'id' ] thead: [ 'class', 'id', 'style' ] tbody: [ 'class', 'id', 'style' ] tr: [ 'class', 'id', 'style', 'colspan', 'rowspan' ] td: [ 'class', 'id', 'style', 'colspan', 'rowspan', 'data-row', 'width', 'height' ] th: [ 'class', 'id', 'scope', 'style', 'colspan', 'rowspan', 'width', 'height' ] ul: [ 'class', 'style', 'id' ] li: [ 'class', 'style', 'id' ] ol: [ 'class', 'style', 'id' ] u: [ 'class', 'id' ] i: [ 'class', 'id' ] b: [ 'class', 'id' ] caption: [ 'class', 'id' ] sub: [ 'class', 'id' ] sup: [ 'class', 'id' ] blockquote: [ 'class', 'id' ] s: [ 'class', 'id' ] iframe: [ 'frameborder', 'height', 'longdesc', 'name', 'sandbox', 'scrolling', 'src', 'title', 'width' ] br: '' img: [ 'class', 'id', 'alt', 'style', 'src', 'width', 'height' ] hr: '' ``` If you want to adapt this configuration please have a look at the [symfony documentation](https://symfony.com/doc/current/html_sanitizer.html). Add your custom configuration to your project, e.g. to `config/packages/html_sanitizer.yaml`. > Note: When using API to set WYSIWYG data, please pass encoded characters for html entities e.g. `<`,`>`, `&` etc. > The data is encoded by the sanitizer before persisting into db and the same encoded data will be returned by the API. --- ## Scheduled Block Editable ### General The scheduled block element allows to manage scheduled content within an editable. Basically the scheduled block is very similar to the standard [block](./06_Block.md) editable. You can configure one or multiple sub editables that are repeated multiple times as block items. The difference is, that within the scheduled block each block item has a specific timestamp and in the frontend only one block item - the one with the corresponding timestamp - is displayed at a time (not all within a loop). In editmode, additional block items can be added and their timestamp can be configured. ### Configuration | Name | Type | Description | |-------------|-----------|------------------------------------------------------------------------------------------------------------------------------| | `class` | string | A CSS class that is added to the surrounding container of this element in editmode | ### Methods | Name | Return | Description | |-----------------|-----------|---------------------------------------------------------------| | `isEmpty()` | bool | Whether the editable is empty or not. | | `getCount()` | int | Get the total amount of iterations. | | `getCurrent()` | int | Get the current index while looping. | | `getElements()` | array | Return a array for every loop to access the defined children. | ### The Block Controls | Control | Operation | |-------------------------------------------------------------------|------------------------------------------| | ![Date Picker](../../img/scheduled_block_date.jpg) | Select a day for the block item timestamp.| | ![Slider](../../img/scheduled_block_slider.jpg) | Select the time for the block item with the slider.| | ![+](../../img/scheduled_block_plus.jpg) | Add new block item. | | ![Block item menu](../../img/scheduled_block_item_menu.png) | List of all block items with jump to function. | | ![Delete entries](../../img/scheduled_block_item_menu_delete.png) | Delete all block items or all block items of the past. | ### Basic Usage ```twig {% for i in opendxp_scheduledblock("block").iterator %}

{{ opendxp_input("blockinput") }}

{{ opendxp_image("myimage") }} {% endfor %} ``` The result in editmode should looks like to following: ![Scheduled Block in editmode](../../img/scheduledblock_editmode.jpg) And in the frontend of the application: ![Scheduled Block in the frontend](../../img/scheduledblock_preview.jpg) In document preview, OpenDXP provides a time slider to get the preview for a certain time as soon as the document has at least one scheduled block editable. For details on how to create custom functionality using the time slider see [Preview Scheduled Content](../../19_Development_Tools_and_Details/39_Preview_Scheduled_Content.md). --- ## Editables The editables are placeholders in the templates, which are displayed as input widgets in the admin interface (so called editmode) and output the content in frontend mode. They are the essential part of managing content in documents. ### Example Usage The following code makes the `

` headline editable in a document: ```twig

{{ opendxp_input("headline") }}

``` In some cases, especially with areablocks, editables could throw exceptions. Since OpenDXP internally uses the `__toString` method to render the editables, OpenDXP can't throw exceptions there. Therefore OpenDXP catches the exception, and puts it out as string if DEBUG Mode is enabled. To prevent that and to have OpenDXP throw the Exception, you can call editables like: ```twig

{{ opendxp_input("headline").render()|raw }}

``` OpenDXP automatically displays an input widget in the edit mode and renders the content when accessing the document via the frontend. ### List of Editables | Name | Description | |--------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| | [Areablock](./02_Areablock/README.md) | Areablock is the content construction kit which allows you to insert predefined **mini applications** / **content blocks** called bricks into an areablock.. | | [Area](./04_Area.md) | Area allows you to use area bricks of a certain type (just like the Areablock). | | [Block](./06_Block.md) | Block is a loop component which can contain other editables. | | [Checkbox](./08_Checkbox.md) | Checkbox / bool implementation for documents. | | [Date](./10_Date.md) | Datepicker, showing the date in a specified format. | | [Relation](./12_Relation_Many-To-One.md) | Provides possibility to create a reference to any other element in OpenDXP (document, asset, object). | | [Relations (Many-To-Many Relation)](./13_Relations_Many-To-Many.md) | Provides possibility to edit multiple references to other elements in OpenDXP (documents, assets, objects). | | [Image](./14_Image.md) | A place where you can assign an image (from the assets module). | | [Input](./16_Input.md) | A single-line text-input. | | [Link](./18_Link.md) | An editable link component. | | [Multiselect](./22_Multiselect.md) | Multiselect implementation for documents. | | [Numeric](./24_Numeric.md) | The numeric editable is like the input editable but with special options for numbers (like minimum value, decimal precision...). | | [PDF](./26_PDF.md) | This editable allows you to embed asset documents (pdf, doc, xls, ...) into documents (like video, image, ...). | | [Renderlet](./28_Renderlet.md) | The renderlet is a special container which is able to handle every object in OpenDXP (Documents, Assets, Objects). | | [Select](./30_Select.md) | Select box as an editable. | | [Snippet (embed)](./32_Snippet.md) | Use the snippet editable to embed a reusable document, for example to create teasers, boxes, etc. | | [Table](./34_Table.md) | This editable allows you to add a fully editable table. | | [Textarea](./36_Textarea.md) | Textarea implementation for documents. | | [Video](./38_Video.md) | Use the Video editable to insert asset movies in pages content. | | [WYSIWYG](./40_WYSIWYG.md) | WYSIWYG editor. | | [Scheduled Block](./42_Scheduled_Block.md) | Scheduled Blocks allow to schedule content for certain timestamps | --- ## Navigation ### Basics OpenDXP comes with a standard navigation implementation in the form of a Twig extension. It builds a navigation container based on the existing document structure. The process of rendering is divided into 2 steps: 1. Build the navigation: `{% set nav = opendxp_build_nav({active: activeDocument, root: navigationRootDocument}) %}` 2. Render the navigation: `opendxp_render_nav(nav)` or `opendxp_nav_renderer('menu').render(nav)` > The building step does not necessarily need to happen in the view script. In fact the view helper just forwards the `build()` call to the `OpenDxp\Navigation\Builder` service. You can also build the navigation in your controller or a service and pass the navigation object to the view. **Only documents are included** in this structure, Folders are ignored, regardless of their navigation properties. ```twig {# get root node if there is no document defined (for pages which are routed directly through static route) #} {% if not document is defined or not document %} {% set document = opendxp_document(1) %} {% endif %} {# get the document which should be used to start in navigation | default home #} {% set navStartNode = document.getProperty('navigationRoot') %} {% if not navStartNode is instanceof('\\OpenDxp\\Model\\Document\\Page') %} {% set navStartNode = opendxp_document(1) %} {% endif %} {% set mainNavigation = opendxp_build_nav({ active: document, root: navStartNode }) %} {# later you can render the navigation #} {{ opendxp_render_nav(mainNavigation) }} ``` Having set up the navigation container as shown above, you can easily use it to render a navigation tree, menus, or breadcrumbs. #### Meta Navigation - Only the 1st Level ```twig {{ opendxp_nav_renderer('menu').renderMenu(mainNavigation,{ maxDepth: 1, ulClass: 'nav navbar-nav' }) | raw }} {#alternatively, you can use the render function to use the given renderer and render method#}
{# the menu() shortcut is not available in twig #} {{ opendxp_render_nav(mainNavigation, 'menu', 'renderMenu', { maxDepth: 1, ulClass: 'nav navbar-nav' }) }}
``` #### Meta Navigation - Multilevel ```twig
{# you can use array for ulClass to provide depth level classes #} {{ opendxp_render_nav(mainNavigation, 'menu', 'renderMenu', { maxDepth: 2, ulClass: { 0: 'nav navbar-nav', 1: 'nav navbar-nav-second', 2: 'nav navbar-nav-third' } }) }} {# alternatively, you can use 'default' key to apply class on all depth levels #} {{ opendxp_render_nav(mainNavigation, 'menu', 'renderMenu', { maxDepth: 2, ulClass: { default: 'nav navbar-nav' } }) }}
``` #### Breadcrumbs ```twig
{{ 'Home'|trans }} > {{ opendxp_render_nav(mainNavigation, 'breadcrumbs') }}
``` #### Sidebar Navigation ```twig
{{ opendxp_nav_renderer('menu').renderMenu(mainNavigation) }}
``` #### Sidebar Navigation with a Different HTML Prefix ```twig
{% set sideNav = opendxp_build_nav({active: document, root: navStartNode, htmlMenuPrefix: 'my-nav-'}) %} {{ opendxp_render_nav(sideNav, 'menu', 'renderMenu', { ulClass: 'nav my-sidenav', expandSiblingNodesOfActiveBranch: true }) }}
``` The renderMenu() method renders the menu to the deepest available level. Levels trees which are not within the active tree, and levels below the latest active page must be hidden using CSS. The example CSS below shows how to do that (includes 3 Levels): ```css #navigation ul li ul { display:none; } #navigation ul li.active ul { display:block; } #navigation ul li.active ul li ul { display:none; } #navigation ul li.active ul li.active ul { display:block; } #navigation ul li.active ul li.active ul li ul { display:none; } #navigation ul li.active ul li.active ul li.active ul{ display:block; } ``` ### Setting a Document's Navigation Property Pages and links have **Navigation Settings** in their system properties as shown in the screen above. These navigation settings include the following properties: * **Name:** Document's name used in the navigation (label). * **Title:** Document's title used in the navigation - the HTML Attribute title. * **Target:** Link target (`_blank`, `_self`, `_top`, `_parent`) * **Exclude from Navigation:** Property to quickly exclude a page from the navigation. In your view template you can use: ```twig {% do document.getProperty('navigation_exclude') %} ``` * **Class:** HTML class of the navigation element * **Anchor:** Anchor appended to the document's URL * **Parameters:** Parameters appended to the document's URL * **Relation:** Only available in custom navigation script. Supposedly the HTML rel attribute to open the link in a sort of Lightbox / Clearbox * **Accesskey:** Only available in custom navigation script * **Tab-Index:** Only available in custom navigation script ### Individual (Partial) Navigation View Script If the standard HTML output of the render() method is not suitable for a project, there is the possibility to provide a custom script for the menu HTML. For example, inside your view: ```twig {# \OpenDxp\Navigation\Renderer\Menu #} {% set menuRenderer = opendxp_nav_renderer('menu') %} {# either use the renderPartial method to use a partial once #} {{ menuRenderer.renderPartial(mainNavigation, 'includes/navigation.html.twig') | raw }} {# or set the partial on the renderer (will be valid for all subsequent render calls) #} {% do menuRenderer.setPartial('includes/navigation.html.twig') %} {{ menuRenderer.render(mainNavigation) | raw }} ``` `templates/includes/navigation.html.twig` ```twig {% for page in pages %}
{{ opendxp_nav_renderer('menu').htmlify(page) | raw }}
{% endfor %} ``` ### Using the Navigation Helper with Sites. For example: ```twig {% set navStartNode = document.getProperty('navigation_root') %} {% if not navStartNode is instanceof('\\OpenDxp\\Model\\Document\\Page') %} {% if opendxp_site_is_request() %} {% set site = opendxp_site_current() %} {% set navStartNode = site.getRootDocument() %} {% else %} {% set navStartNode = opendxp_document(1) %} {% endif %} {% endif %} {% set navigation = opendxp_build_nav({active: document, root: navStartNode}) %} {{ opendxp_render_nav(navigation, 'menu', 'renderMenu', { maxDepth: 1, ulClass: { 'default': 'nav navbar-nav' } }) }} ``` ### Using Partials Generating a Customized Navigation For example, generate bootstrap 4.0 style navigation: ```twig {% set navStartNode = document.getProperty('navigation_root') %} {% if not navStartNode is instanceof('\\OpenDxp\\Model\\Document\\Page') %} {% if opendxp_site_is_request() %} {% set site = opendxp_site_current() %} {% set navStartNode = site.getRootDocument() %} {% else %} {% set navStartNode = opendxp_document(1) %} {% endif %} {% endif %} {% set mainNavigation = opendxp_build_nav({active: document, root: navStartNode}) %} {% set menuRenderer = opendxp_nav_renderer('menu') %} ``` ### Adding Custom Items to the Navigation In the following example we're adding - news items (objects) to an existing navigation with the "pageCallback" attribute - category items (objects) to the root Navigation with the "rootCallback" attribute using Twig Extension. ```php navigationHelper->build([ 'active' => $document, 'root' => $startNode, 'pageCallback' => function($page, $document) { /** @var \OpenDxp\Model\Document $document */ /** @var \OpenDxp\Navigation\Page\Document $page */ if ($document->getProperty('templateType') === 'news') { $list = new \OpenDxp\Model\DataObject\News\Listing; $list->load(); foreach ($list as $news) { $detailLink = $this->newsLinkGenerator->generate($news, ['document' => $document]); $page->addPage(new \OpenDxp\Navigation\Page\Document([ 'label' => $news->getTitle(), 'id' => 'object-' . $news->getId(), 'uri' => $detailLink, ])); } } }, 'rootCallback' => function(Container $navigation) { $list = new \OpenDxp\Model\DataObject\Category\Listing; $list->load(); foreach ($list as $category) { $detailLink = $this->categoryLinkGenerator->generate($category); $navigation->addPage(new \OpenDxp\Navigation\Page\Document([ 'label' => $category->getName(), 'id' => 'object-' . $category->getId(), 'uri' => $detailLink, ])); } }, ]); } } ``` ```twig {% set navigation = app_navigation_links(document, navStartNode) %}
{{ opendxp_render_nav(navigation, 'menu', 'renderMenu', { expandSiblingNodesOfActiveBranch: true, ulClass: { default: 'nav my-sidenav' } }) }}
``` ### Caching / High-Performance Navigation The navigation tree / container (`\OpenDxp\Navigation\Container`) is automatically cached by OpenDXP and improves significantly the performance of the navigation. To benefit from the cache it's absolutely necessary to don't use `OpenDxp\Model\Document` objects directly in the navigation templates / partial scripts, because this would result in loading all the documents again in the navigation and bypasses the caching mechanism of the navigation container. But sometimes it's necessary to get some properties or other data out of the documents in the navigation to build the navigation as it should be. For that we've introduced a new parameter for the navigation extension, which acts as a callback and allows to map custom data onto the navigation page item. ```php navigationHelper->build([ 'active' => $document, 'root' => $startNode, 'pageCallback' => function ($page, $document) { $page->setCustomSetting('myCustomProperty', $document->getProperty('myCustomProperty')); $page->setCustomSetting('subListClass', $document->getProperty('subListClass')); $page->setCustomSetting('title', $document->getTitle()); $page->setCustomSetting('headline', $document->getEditable('headline')->getData()); }, ]); } } ``` ```twig {% set mainNavigation = app_navigation_custom(document, navStartNode) %} {% set menuRenderer = opendxp_nav_renderer('menu') %} {% do menuRenderer.setPartial("navigation/partials/navigation.html.twig") %} {{ menuRenderer.render(mainNavigation) | raw }} ``` Later in the template of the navigation (`navigation/partials/navigation.html.twig`) you can use the mapped data directly on the page item object. ```twig {% for page in pages %} {% if page.isVisible() %} {% set activeClass = page.getActive(true) ? 'active' : '' %}
  • {{ page.getLabel() }}
  • {% endif %} {% endfor %} ``` Using this method will dramatically improve the performance of your navigation. #### Dynamic Key for the Navigation Cache Sometimes it's necessary to manually set the key for the navigation cache. ```twig {% set nav = opendxp_build_nav({active: document, root: navStartNode, cache: 'yourindividualkey'}) %} ``` #### Disabling the Navigation Cache You can disable the navigation cache by setting the `cache` argument to `false`. ```twig {% set nav = opendxp_build_nav({active: document, root: navStartNode, cache: false}) %} ``` ### FAQ **A document does not show up in the navigation. Why?** Please make sure that the documents and its parent documents are published and that the document itself as well as all its parents have a navigation name set. Neither the document itself nor one of its parent documents may have activated **Exclude From Navigation** in their properties. (`Document properties -> System properties`) **Why is the navigation not appearing?** See the above question. If none of the documents have a navigation title set the render function will simply return nothing. **Why is the homepage not appearing in the navigation?** The homepage will not appear in the navigation by default. You can add the homepage (and any other page) manually: ```twig {% do navigation.addPage({ order: -1, uri: '/', label: 'Home'|trans, title: 'Home'|trans, }) %} ``` If you retrieve the **home** document (which always has the ID 1) you can also retrieve its navigation properties so that they can be edited from the OpenDXP admin interface like all the other documents. ```twig {% set home = opendxp_document(1) %} {# order: put it in front of all the others uri: path to homepage label: visible label title: tooltip text active: active state (boolean) #} {% do navigation.addPage({ order: -1, uri: '/', label: home.getProperty('navigation_name'), title: home.getProperty('navigation_title'), active: document.id == home.id }) %} ``` --- ## Predefined Document-Types ### General OpenDXP provides the ability to define preconfigurations for documents, which makes it easier for editors to work with many different controller/action and templates. By using this feature the editors don't have to have any knowledge of which controller/action/template should be used in a specific document because they can choose out of a predefined set of configurations with a friendly name. ### Example To define document-type go to *Settings* > *Document-Types*. Let's suppose that you've created controller, action and template for a books listing. Reference to the action: `App\Controller\BookController::listAction` Reference to the template: `templates/book/list.html.twig` To add a new document-type which renders the book listing template, you have to click on the *Add* button first and then fill out the newly created configuration row accordingly. ![New document type](../img/documenttypes_new_row.png) The type can be either a `page`, `snippet`, `email`. `printcontainer` or `printpage` are only available if the OpenDxpWebToPrintBundle is enabled and installed. `newsletter` is only available if the OpenDxpNewsletterBundle is enabled and installed. After you have defined a type you can access it in the context menu or in the document settings: ###### Document Settings Preview ![Document type - settings preview](../img/documenttypes_predefined_document_types.png) ###### Context Menu Preview ![Document type - context menu preview](../img/documenttypes_context_menu.png) --- ## Working With Documents via PHP API OpenDXP provides the object orientated PHP API to work with Documents. ### CRUD Operations #### Create a New Document To create a new document, you need to specify two mandatory attributes: * A unique key * A parent ID - ID of the parent document (document, folder and every other type) You can set also every other value available in documents structure (settings, properties, children etc.). > Type of the document (page, folder, link, email, snippet etc.) The complete list can be obtained using: `\OpenDxp\Model\Document::getTypes()` > Every type has its own model, for example: a link document could be created by `new \OpenDxp\Model\Document\Link`. The example below, shows how to create simple page document via the PHP API. ```php //CREATE A PAGE DOCUMENT $page = new \OpenDxp\Model\Document\Page(); $page->setKey('document8'); $page->setParentId(82); // id of a document or folder // the optional parameter allows you to provide additional info // currently supported: // * versionNote: note added to the version (see version tab) $page->save(["versionNote" => "my new version"]); ``` Now you can refresh the parent node of the newly created document in the admin interface (ID `82` in this case) and you'll see the newly created document. ![Create document by API](../img/documents_api_create.png) #### Edit an Existing Document If you'd like to get a document you can use the `getById()` or `getByPath()` method from the `\OpenDxp\Model\Document` class. Find below, the list of available methods for loading documents. | Reference | Arguments | |------------------------------------|--------------| | \OpenDxp\Model\Document::getById | int $id | | \OpenDxp\Model\Document::getByPath | string $path | The following code presents how to get the wysiwyg editable value of the document. ```php //LOAD A DOCUMENT $document = \OpenDxp\Model\Document::getById(4); if($document) { //the logic when the type of the document is page /** @var \OpenDxp\Model\Document\Page $document */ /** @var \OpenDxp\Model\Document\Editable\Wysiwyg $wysiwygElement */ $wysiwygElement = $document->getEditable('content'); var_dump($wysiwygElement->getData()); } ``` You've probably guessed that if you want to change value of a chosen editable or any other value, you can just set the value (by an available method) and after, save the document. ```php //... /** @var \OpenDxp\Model\Document\Editable\Wysiwyg $wysiwygElement */ $wysiwygElement = $document->getEditable('content'); $wysiwygElement->setDataFromResource('

    Lorem Ipsum is simply dummy text of the printing and typesetting.

    '); $document->save(); //save changes in the document ``` #### Delete a Document As simple or even simpler is deletion. Just load the document and use `delete` method available in `\OpenDxp\Model\Document`. ```php $document = \OpenDxp\Model\Document::getById(110); if ($document) { $document->delete(); } ```   ### Document Listings #### Examples Let's assume that we have the following document tree structure: ![Apitests children - preview](../img/documents_apitests_children_preview.png) The code below retrieves all published documents with parentId = 82: ```php $listing = new \OpenDxp\Model\Document\Listing(); $listing->setCondition("parentId = 82"); foreach($listing as $doc) { // do whatever you like } ``` If you'd like to get also all the unpublished documents, set the following flag: `$listing->setUnpublished(true);`. #### Configurations | Method | Arguments | Description | |------------------|---------------------|-----------------------------------------------------------------------------------| | `setOrder()` | string (asc,desc) | Set ascending or descending order type. | | `setOrderKey()` | string | Chosen column name / names for as a order key. You can choose many order keys. | | `setLimit()` | int | amount of collection results limit | | `setOffset()` | int | a distance from beginning of the collection items | | `setCondition()` | string | Your own SQL condition like in the example above. | #### Methods | Method | Arguments | Description | |-------------------------|-------------------------------------|---------------------------------------------------------------------------------------------| | `getCount()` | | Returns total number of selected rows. | | `getTotalCount()` | | Returns total number of selected rows (excluding offset and limit). | | `getPaginatorAdapter()` | | List implements `\Iterator`, you could use the list as a paginator. | | `getItems()` | int $offset, int $itemsCountPerPage | as arguments you have to specify the limit of rows and the offset. | | `loadIdList()` | | Returns complete array with id as a row. | If you want to know more about the paginator usage with lists, you should visit [Working with Objects via PHP API part](../05_Objects/03_Working_with_PHP_API.md#working-with-knpcomponentpagerpaginator). #### Advanced Example ```php $listing = new \OpenDxp\Model\Document\Listing(); $listing->setUnpublished(1); $listing->setCondition("`parentId` = 82") ->setOrderKey(['key', 'published']) ->setOrder('desc') ->setOffset(2) ->setLimit(2); $listing->getTotalCount(); $listing->loadIdList(); foreach($listing as $item) { // ... } ``` Alternatively, you can use the following static method to get a listing of documents: ```php //list all published children from the folder /** @var \OpenDxp\Model\Document\Listing $listing */ $listing = \OpenDxp\Model\Document::getList([ 'unpublished' => true, 'condition' => "`parentId` = 82", 'orderKey' => ['key', 'published'], 'order' => 'desc', 'offset' => 2, 'limit' => 2 ]); ``` --- ## Document Inheritance The *Content Main Document* setting, allows a document to inherit all of its contents from any other document which can then be overwritten individually on field level. Notice: Properties are not inherited via Content Main Documents. If this setting is selected and *Apply new main document* is clicked, all contents will be erased from the current document and inherited from the main document. ## How-To 1. Drag a main document to the document where you'd like to inherit the contents (*Content-Main Document* in settings tab). 2. Press the *Apply new main document* button 3. Confirm the warning dialog ![Confirm main document changes](../img/main_document_2step.png) 4. Now you can see grey spaces in the document. If you want to overwrite any value, just click the right button on it. ![Main document - the editmode preview](../img/main_document_3step.png) ### Content Main Document in the Code Using a main document doesn't change anything in the PHP API. If you load a document which has related a main document, then values returned by it will be replaced by values from the main document (unless values are overwritten). You can get Main document object by `getContentMainDocument` method available in `\OpenDxp\Model\Document\Page`. ```php $document = \OpenDxp\Model\Document\Page::getById(130); dump([ 'main_document' => $document->getContentMainDocument()->getKey(), 'document' => $document->getKey() ]); ``` --- ## Documents(Documents) Documents are the CMS part of OpenDXP and are the way to go for managing unstructured contents using pages, content snippets and navigations. ### Document Types OpenDXP offers different types of documents and each of them offers functionality specific for the intended use-case. | Type | Description | |----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | Page | Represents a typical web-page, the path in the tree is equal to the address in the browser. | | Snippet | Makes it easier to extract often used contents into reusable containers. Can be embedded in pages or nested into other snippets. | | Link | A simple web-link to be used in navigation. | | Email | A document like the page, but with special functionality for transactional emails. | | Hardlink | Create links to other document structures and reuse them within a different structure / context. (see [Hard link](https://en.wikipedia.org/wiki/Hard_link)) | | Folder | Just like the folders you know from your local filesystem. | ### Document Configuration Many documents types are tight to the [MVC](../02_MVC/README.md) and therefore they need a underlying controller/action and a template. They are directly specified in the document settings in the admin interface: ![Documents: controller and view settings](../img/documents_controller_and_view_settings.png) Not all of them are necessary, the table below shows which configurations are possible: | Type | Controller | Template | Description | |------|------------ |----------|----------------------------------------------------------------------------------------------------------------------------------------| | 1 | X | | The specified controller/action is executed. If the action returns a response object, it is used for rendering. | | 2 | X | X | Same as above but the template specified is rendered and not the auto-discovered template (only if action does not return a response). | | 3 | | X | Renders the template with the default controller/action, this is practical if there is only templating stuff. | OpenDXP is shipped with a default controller containing a default action, which is called when only a template is given to the document. You can set a default module/bundle, controller and action in the symfony configuration: ```yaml opendxp: documents: default_controller:App\Controller\DefaultController::defaultAction ``` ### Properties [Properties](../18_Tools_and_Features/07_Properties.md) are very powerful in combination with documents. Below, you can find some examples where properties can be very useful for the use with documents. 1. **Navigation** - If you build the navigation based on the document-tree, sometimes you need special settings for the frontend, like separators or highlightings. 2. **Header Images** - Often there are header images on a website, if you don't want to define it for every page, you can use properties with inheritance. Then you can define a default one at the root document, and overrule this on a deeper level in the tree structure. 3. **Sidebars** - You can easily manage visibility of sidebars in specific documents. 4. **SEO** - It's also possible to use properties for SEO. It's very painful to define a nice title and description for every page on your site, with properties this is not necessary (inheritance). 5. **Protected Areas** - Closed user groups 6. Change the appearance of the website depending on the properties (eg. micro-sites, nested sites) 7. Mark them for some automated exports (PDF, RPC's, …) As you can see there are really useful cases for properties, feel free to use them for whatever they seem to be useful. ### A Few Facts * Documents follow the MVC pattern; therefore, OpenDXP requires that there is at least one controller with an action and a template file. * OpenDXP comes with a DefaultController containing a defaultAction and a template file. * Because of the MVC architecture, there is a clear separation between your data, the functionality and the templates. * Templates for OpenDXP are created with [Twig](https://twig.symfony.com/). * As the templates are written in Twig, there is a clear separation of logic (controllers) and design (view / template). ### Create Your First Document Working with documents is described in detail in our [Create a First Project](../01_Getting_Started/06_Create_a_First_Project.md) manual. ### Cleanup Documents Types Uninstalling bundles may not always clean up data or database tables in the process to avoid data loss. Running the following command removes type specific tables and enum types from the documents table. The following types are protected and cannot be cleaned up via this command: `page, link, snippet, folder, hardlink, email` You can clean up multiple types at once. ```bash bin/console opendxp:documents:cleanup ``` ### Document Topics - [Creating editable templates](./01_Editables/README.md) - [Navigation](./03_Navigation.md) - [Inheritance](./11_Inheritance.md) - [Working with the PHP API](./09_Working_with_PHP_API.md) - [Predefined Document Types](./07_Predefined_Document_Types.md) --- ## Working With Assets via PHP API OpenDXP provides an object orientated PHP API to work with Assets. ### CRUD Operations Following lines of code show simple CRUD operations for Assets. ```php //creating and saving new asset $newAsset = new \OpenDxp\Model\Asset(); $newAsset->setFilename("myAsset.png"); $newAsset->setData(file_get_contents("some-file.png")); $newAsset->setParent(\OpenDxp\Model\Asset::getByPath("/")); // the optional parameter allows you to provide additional info // currently supported: // * versionNote: note added to the version (see version tab) $newAsset->save(["versionNote" => "my new version"]); //getting assets $asset1 = \OpenDxp\Model\Asset::getById(3456); $asset2 = \OpenDxp\Model\Asset::getByPath("/my-assets/sample.png"); //updating assets $asset1->setData(file_get_contents("some-updated-file.png")); $asset1->save(); //deleting assets $asset2->delete(); ``` ### Asset Listings With `Asset\Listing` lists of assets can be retrieved and filtered. The most important methods are `setCondition`, `setOffset`, `setLimit`, `setOrderKey`, `setOrder`. ```php $list = new \OpenDxp\Model\Asset\Listing(); $list->setCondition("..."); $list->setOrderKey("filename"); $list->setOrder("DESC"); $list->load(); ``` Please also have a look at [object listings](../05_Objects/03_Working_with_PHP_API.md#object-listings) and [document listings](../03_Documents/09_Working_with_PHP_API.md#document-listings). ### Custom Settings Custom Settings/Properties can be added programmatically to every asset. This is mostly used for plugins or something similar. ```php $asset = Asset::getById(2345); $settings = $asset->getCustomSettings(); $settings["mySetting"] = "this is my value this can be everythin also an array or an object not only a string"; $asset->setCustomSettings($settings); $asset->save(); ``` ### Using (localized) Asset Metadata Asset Metadata allow you to attach localized metadata to assets within OpenDXP. These Medata can be accessed via API and therefore used on all output channels. #### Examples ###### Getting Data Metadata for an asset can be fetched using `getMetadata` method of Asset class. It can take the following optional parameters: 1. `$name` (string) when passed it returns the metadata with the given name, otherwise it lists all. 2. `$language` (string) with this parameter you can filter out the metadata of a specific language. 3. `$strictMatchLanguage` (boolean) if true tries to get only the metadata which exactly matches the requested language without considering the fallback. 4. `$raw` (boolean) if true, it will also return extra information like name, data, language and input type of the metadata. To know the expected return values, you can look into the tests inside `tests/Model/Asset/Metadata/NormalizerTest::testLocalizedMetaData` ```php $asset = Asset::getById(123); // get the title for the current language (request attribute `_locale`) $asset->getMetadata("title"); // get the English title $asset->getMetadata("title", "en"); // if there's no title for "en" but one without a language this will be returned (fallback mechanism). // get all available metadata $asset->getMetadata(); // get all available metadata for a specific language along with metadata which have no language assigned $asset->getMetadata(null, 'en'); // get exclusively all the metadata that have a specific language $asset->getMetadata(null, 'en', true); // get metadata in raw format. ie: including metadata input type, language, value and name $asset->getMetadata('title', null, true, true); ``` ###### Setting Data ```php // Set the English title $asset->addMetadata("title", "input", "the new title", "en"); ``` ###### Removing Data ```php // Remove the English title $asset->removeMetadata("title", "en"); // Remove the title in all languages $asset->removeMetadata("title", "*"); ``` #### Predefined System Metadata There may be predefined and default fields on an Asset. That means that these fields have a special meaning and will be used somewhere else. ###### Image asset There are 3 default fields, namely `title`, `alt` and `copyright`. The contents of this fields will be used as default `alt` and `title` attribute on any `` tag generated by OpenDXP for the corresponding image. This includes for example: ```twig // image editable on documents {{ opendxp_image("myImage", {"thumbnail": "xyz"}) }} ``` ```twig {# thumbnail html generator #} {{ asset.getThumbnail("xyz").getHtml()|raw }} {{ object.getMyImage().getThumbnail("xyz").getHtml()|raw }} ``` The `copyright` field will be appended to every `title` and `alt` attribute separated by |. --- --- ## Image Thumbnails(Working_with_Thumbnails) For images, OpenDXP offers an advanced thumbnail-service also called 'image-pipeline'. It allows you to transform images in unlimited steps to the expected result. You can configure them in _Settings_ > _Thumbnails_. With this service every image which is stored as an asset can be transformed. OpenDXP doesn't support to modify images which are not stored as an asset inside OpenDXP. > **IMPORTANT** > Use Imagick PECL extension for best results, GDlib is just a fallback with limited functionality > (only PNG, JPG, GIF) and less quality! If Imagick is available it will be the default, otherwise falling back to GD. > Using ImageMagick OpenDXP can support hundreds of formats including: AI, EPS, TIFF, PNG, JPG, GIF, PSD, etc. > Not all formats are allowed out of the box. To extend the list [see](./README.md#allowed-formats). To use the thumbnailing service of OpenDXP, you have to create a transformation pipeline first. To do so, open _Settings_ > _Thumbnails_ and click on _Add Thumbnail_ to create a new configuration. The fields name, description, format and quality should be self-explanatory, the interesting part are now the transformations. Click on _+_ to add a new transformation, so that it look like that for example: ![Thumbnails](../../img/thumbnail_transformations.png) **Important**: The transformations are performed in the order from the top to the bottom. This is for example important in the configuration above. If you first round the corners this would be performed on the original image, and then the image will get resized, so the rounded corners are also resized which is not intended. To retrieve a thumbnail from an asset simply call `$asset->getThumbnail("thumbnail-name")` on the asset object, which will return an `\OpenDxp\Model\Asset\Image\Thumbnail` object. The thumbnail object's `__toString()` method returns the path to the thumbnail file, for example: `/Car%20Images/ac%20cars/68/image-thumb__68__content/automotive-car-classic-149813.jpg` **Important**: The function `getThumbnail()` does not generate the Thumbnail itself. It just returns the path were the thumbnail file will be stored. If you want to generate the Thumbnail directly have a look at [Deferred Rendering of Thumbnails](#deferred-rendering-of-thumbnails) This path can then be directly used to display the image in a `` or ` tag. For example: ```php $image = Asset::getById(1234); // get path to thumbnail, e.g. `/foo/bar/362/image-thumb__362__content/foo.webp $pathToThumbnail = $image->getThumbnail("myThumbnailName"); // preferred alternative - let OpenDXP create the whole image tag // including high-res alternatives (srcset) or media queries, if configured $htmlCode = $image->getThumbnail("myThumbnail")->getHtml(); ``` Same in Twig: ```twig {% set image = opendxp_asset(1234) %} {# get path to thumbnail, e.g. `/foo/bar/362/image-thumb__362__content/foo.webp #} {# preferred alternative - let OpenDXP create the whole image tag #} {# including high-res alternatives (srcset) or media queries, if configured #} {{ image.thumbnail('myThumbnailName').html|raw }} ``` ### Explanation of the Transformations | Transformation | Description | Configuration | Result | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | | ORIGINAL IMAGE | This is the image which is used in the following transformations | NONE ;-) | ![Sample Original](../../img/thumbnails-sample-original.png) | | RESIZE | The image is exactly resized to the given dimensions without respecting the ratio. | ![Config Resize](../../img/thumbnails-config-resize.png) | ![Sample Resize](../../img/thumbnails-sample-resize.png) | | SCALE BY HEIGHT | The image is scaled respecting the ratio to the given height, the width is variable depending on the original ratio of the image (portrait, landscape). | ![Config Height](../../img/thumbnails-config-height.png) | ![Sample Height](../../img/thumbnails-sample-height.png) | | SCALE BY WIDTH | The image is scaled respecting the ratio to the given width, the height is variable depending on the original ratio of the image (portrait, landscape). | ![Config Width](../../img/thumbnails-config-width.png) | ![Sample Width](../../img/thumbnails-sample-width.png) | | CONTAIN | The image is scaled to either the given height or the width, depending on the ratio of the original image. That means that the image is scaled to fit into a "virtual" box with the dimensions given in the configuration. | ![Config Contain](../../img/thumbnails-config-contain.png) | ![Sample Contain](../../img/thumbnails-sample-contain.png) | | CROP | Cuts out a box of the image starting at the given X,Y coordinates and using the width and height. | ![Config Crop](../../img/thumbnails-config-crop.png) | ![Sample Crop](../../img/thumbnails-sample-crop.png) | | COVER | The image is resized so that it completely covers the given dimensions. Then the overlapping pieces are cropped depending on the given positioning or based on the focal point set on the source image. This is useful if you need a fixed size for a thumbnail but the source images have different ratios. | ![Config Cover](../../img/thumbnails-config-cover.png) | ![Sample Cover](../../img/thumbnails-sample-cover.png) | | FRAME | The transformation is the same as CONTAIN the difference is, that the image gets exactly the entered dimensions by adding transparent borders left / right or top / bottom. | ![Config Frame](../../img/thumbnails-config-frame.png) | ![Sample Frame](../../img/thumbnails-sample-frame.png) | | ROTATE | Rotates the image with the given angle. The background is transparent by default. | ![Config Rotate](../../img/thumbnails-config-rotate.png) | ![Sample Rotate](../../img/thumbnails-sample-rotate.png) | | BACKGROUND COLOR | Background color is especially useful if you have transparent PNG as source data or if you're using the FRAME or the ROTATE transformations where you get transparencies. It allows you to give transparencies a color, and gives you the possibility to use them for examples JPEG's which doesn't support transparency. | ![Config Background](../../img/thumbnails-config-background.png) | ![Sample Background](../../img/thumbnails-sample-background.png) | | ROUNDED CORNERS | Rounds the corners to the given width/height. | ![Config Corner](../../img/thumbnails-config-corner.png) | ![Sample Corner](../../img/thumbnails-sample-corner.png) | ### Generating HTML for Thumbnails OpenDXP offers the method `getHTML(array $options)` to get a ready to use `` tag for your thumbnail. When a `` element is not needed or desired an `` element can used by calling `getImageTag(array $options)` instead. You can configure the generated markup with the following options: | Name | Type | Description | |--------------------------------| -------- |------------------------------------------------------------------------------------------------------------------------------------| | `disableWidthHeightAttributes` | bool | Width & height attributes are set automatically by OpenDXP, to avoid this set this option (eg. to true => isset check) | | `disableAutoTitle` | bool | Set to true, to disable the automatically generated title attribute (containing title and copyright from the origin image) | | `disableAutoAlt` | bool | Set to true, to disable the automatically generated alt attribute | | `disableAutoCopyright` | bool | Set to true, to disable the automatically appended copyright info (alt & title attribute) | | `disableAutoCopyright` | bool | Set to true, to disable the automatically appended copyright info (alt & title attribute) | | `pictureAttributes` | array | An key-value array of custom attributes which should be applied to the generated `` tag | | `imgAttributes` | array | An key-value array of custom attributes which should be applied to the generated `` tag | | `lowQualityPlaceholder` | bool | Put's a small SVG/JPEG placeholder image into the `src` (data-uri), the real image path is placed in `data-src` and `data-srcset`. | | `pictureCallback` | callable | A callable to modify the attributes for the generated `` tag. There 1 argument passed, the array of attributes. | | `sourceCallback` | callable | A callable to modify the attributes for any of the generated `` tag. There 1 argument passed, the array of attributes. | | `imgCallback` | callable | A callable to modify the attributes for the generated `` tag. There 1 argument passed, the array of attributes. | | `disableImgTag` | bool | Set to `true` to not include the `` fallback tag in the generated `` tag. | | `useDataSrc` | bool | Set to `true` to use `data-src(set)` attributes instead of `src(set)`. | | `useFrontendPath` | bool | Set to `true` to use the full url (including the frontend_prefix). | **Info:** The Auto Alt functionality will try to automatically fall back to any available `alt` value by also checking the metadata entries (with name as `alt`, `defaultalt`). Ultimately, it would use the image `title` as `alt` value when nothing above is previously found. It is also possible to define an alternative metadata to be used as `alt`, `copyright`, `title` values (eg. by defining `opendxp.assets.metadata.alt` in the configuration) that would have used when the inline options are not passed. ```yaml ## Usage Examples ```twig /* Use directly on the asset object */ {{ opendxp_asset_by_path('/path/to/image.jpg').thumbnail('myThumbnail').html|raw }} /* ... with some additional options */ {{ opendxp_asset_by_path('/path/to/image.jpg').thumbnail('myThumbnail').html({ pictureAttributes: { data-test: "my value" }, disableImgTag: true })|raw }} /* Use with the image tag in documents */

    {{ opendxp_image('myImage', {'thumbnail': 'myThumbnail'}) }}

    /* Use without pre-configured thumbnail */ {{ opendxp_image('myImage', { 'thumbnail': { 'width': 500, 'aspectratio': true, 'interlace': true, 'quality': 85, 'format': 'png' } }) }} /* Use from an object-field */ /* where "myThumbnail" is the name of the thumbnail configuration in settings -> thumbnails */ {% if myObject.myImage %} {{ myObject.myImage.thumbnail('myThumbnail').html|raw }} {% endif %} /* Use from an object-field with dynamic configuration */ /* Use directly on the asset object using dynamic configuration */ {{ opendxp_asset_by_path('/path/to/image.jpg').thumbnail({'width': 500, 'format': 'png'}).html|raw}} ``` ### Advanced Examples OpenDXP returns an `\OpenDxp\Model\Asset\Image\Thumbnail` object when calling `$asset->getThumbnail("thumb-name")` which gives you even more flexibility when working with thumbnails. ```php $thumbnail = $asset->getThumbnail("myThumbnail"); // get the final dimensions of the thumbnail (especially useful when working with dynamic configurations) $width = $thumbnail->getWidth(); $height = $thumbnail->getHeight(); // get the html "" tag for the thumbnail incl. custom class on the containing `` tag: echo $thumbnail->getHtml(['imgAttributes' => ["class" => "custom-class"]]); // get the path to the thumbnail $path = $thumbnail->getPath(); // get path and disable deferred thumbnails $path = $thumbnail->getPath(["deferredAllowed" => false]); // possible options: ["deferredAllowed" => true, "cacheBuster" => false, "frontend" => false] // getting the full url to a thumbnail (including the frontend_prefix) - also works in console commands $path = $thumbnail->getFrontendPath(); //or $path = $this->getPath(['deferredAllowed' => false, 'frontend' => true]); // Asset\Image\Thumbnail implements __toString(), so you can still print the path by echo $thumbnail; // prints something like /Car%20Images/....png // examples for callbacks, etc. for the generated tag $thumbnail->getHtml([ 'useDataSrc' => true, 'pictureAttributes' => [ 'data-bar' => uniqid(), ], 'imgAttributes' => [ 'data-foo' => uniqid(), ], 'imgCallback' => function ($attributes) { // modify tag attributes $attributes['data-foo'] = 'new value'; return $attributes; }, 'sourceCallback' => function ($attributes) { // modify tag attributes $attributes['data-custom-source-attr'] = uniqid(); return $attributes; }, 'pictureCallback' => function ($attributes) { // modify tag attributes $attributes['data-custom-picture-attr'] = uniqid(); return $attributes; }, 'disableImgTag' => true, 'lowQualityPlaceholder' => true, ]); // get thumbnail instance in a specific file format $webpThumbnail = $thumbnail->getAsFormat('webp'); $webpThumbnail->getHtml(); ``` ### More Examples ```twig /* adding custom html attributes to the generated or tag, using a dynamic thumbnail */ {{ image.thumbnail({ 'width': 180, 'height': 180, 'cover': true, }).html({ 'imgAttributes': { 'class': 'thumbnail-class', }, 'data-my-name': 'my value', 'attributes': { 'non-standard': 'HTML attributes', 'another': 'one' } })|raw }} /* same with a thumbnail definition */ {{ image.thumbnail('exampleScaleWidth').html({ 'pictureAttributes': { 'class': 'thumbnail-class', }, 'data-my-name': 'my value', })|raw }} /* disable the automatically added width & height attributes */ {{ image.thumbnail('exampleScaleWidth').html({}, ['width', 'height'])|raw }} /* add alt text */ {{ image.thumbnail('exampleScaleWidth').html({'alt': 'top priority alt text'})|raw }} /* OR */ {{ image.thumbnail('exampleScaleWidth').html({'defaultalt': 'default alt, if not set in image'})|raw }} /* Output only element wihout and around it */ {{ image.thumbnail('exampleScaleWidth').imageTag({'alt': 'top priority alt text'}) }} ``` Additionally, there are some special parameters to [customize generated image HTML code](../../03_Documents/01_Editables/14_Image.md#configuration). ### Lazy Loading By default, the images are lazy loading. This can be changed by setting the value to "eager" in the imgAttribute: ```twig {{ image.thumbnail('example').html({ 'imgAttributes': { 'loading': 'eager', } })|raw }} ``` ### Using ICC Color Profiles for CMYK -> RGB OpenDXP supports ICC color profiles to get better results when converting CMYK images (without embedded color profile) to RGB. Due licensing issues OpenDXP doesn't include the color profiles (\*.icc files) in the download package, but you can download them for free here: [Adobe ICC Profiles](https://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html) or here: [ICC (color.org)](http://www.color.org/profiles.xalter). After downloading the profiles put them into your project folder or anywhere else on your sever (eg. `/usr/share/color/icc`). Then configure the path in the OpenDXP config file: ```yaml opendxp: assets: # Absolute path to default ICC RGB profile (if no embedded profile is given) icc_rgb_profile: null # Absolute path to default ICC CMYK profile (if no embedded profile is given) icc_cmyk_profile: null ``` ### Dynamic Generation on Request OpenDXP auto-generates a thumbnail if requested but doesn't exist on the file system and is directly called via it's file path (not using any of the `getThumbnail()` methods). For example: Call `https://example.com/examples/panama/6644/image-thumb__6644__contentimages/img_0037.jpeg` (`/examples/panama/` is the path to the source asset, `6644` is the ID of the source asset, `contentimages` is the name of the thumbnail configuration, `img_0037.jpeg` the filename of the source asset) directly in your browser. Now OpenDXP checks if the asset with the ID 6644 and the thumbnail with the key "contentimages" exists, if yes the thumbnail is generated on-the-fly and delivered to the client. When requesting the images again the image is directly served by the webserver (Apache, Nginx), because the file already exists (just the same way it works with the getThumbnail() methods). The structure of the path is identically with the one generated by the `getThumbnail()` methods, so it doesn't matter whether the thumbnail is generated by `getThumbnail()` (inside a PHP process) or on-the-fly (in a separate process). Of course this works only with predefined (named) thumbnail configurations and not with dynamic configurations. > **WARNING** > This feature is delivered through PublicServicesController and may not work if the controller is unreachable (e.g. during Maintenance mode). > When requesting an image without providing a hash, the content cannot be Browser cached like regular Nginx-served files, as the file without hash doesn’t exist physically. ### Deferred Rendering of Thumbnails For performance reasons, OpenDXP doesn't generate the thumbnail image directly when calling `getThumbnail()` on an asset, instead it generates them when they are actually needed (on request). But sometimes it's necessary to have the actual image already generated, in this case you can pass a 2nd parameter to `getThumbnail()` to force the processing of the image. ```php $asset = Asset\Image::getById(123); $asset->getThumbnail("myConfig", false); // set the 2nd parameter to false ``` The processing is also forced when calling the method `getPathReference()` or `getPath(["deferredAllowed" => false])` on the returning thumbnail object: ```php $asset->getThumbnail("myConfig")->getPathReference(); // or $asset->getThumbnail("myConfig")->getPath(['deferredAllowed' => false]); ``` ### High-Resolution Support This is a special functionality to allow embedding high resolution (ppi/dpi) images. The following is only necessary in special use-cases like Web-to-Print, in typical web-based cases, OpenDXP automatically adds the `srcset` attribute to `` and `` tags automatically, so no manual work is necessary. The high resolution scaling factor is limited to `5.0` eg. `@5x`. Float values are supported. If you need to scale an image more than that, you can use the `max_scaling_factor` option in the configuration. ```yaml opendxp: assets: thumbnails: max_scaling_factor: 6.0 ``` #### Use in the Thumbnail Configuration: ![High Resolution](../../img/thumbnail_high_resolution.png) The above configuration will generate a thumbnail with 500px width. When using this configuration in combination with the [image editable](../../03_Documents/01_Editables/14_Image.md) using the following code ```twig {{ opendxp_image('myImage', {'thumbnail': 'contentimages'}) }} ``` this will create the following output: ```php ``` It's also possible to add the high-res dynamically: ```twig {{ opendxp_image('myImage', {thumbnail: { width: 250, contain: true, highResolution: 2 }}) }} ``` This will create an image `width = 500px` ##### Combining "Dynamic Generation on Request" with High Resolution Images This is especially useful in the case you want to serve thumbnails depending on the ppi of the device screen or in combination with Web2Print documents (browser preview with normal size, tripled in size for PDF ouptut). OpenDXP also utilizes this functionality internally to provide the automatically added high.res support on `` and `` tags. So again, this feature is only useful in some edge-cases. ###### Example ```twig {{ image.thumbnail('testThumbnailDefinitionName').path }} ``` this generates the followinig ouput: ```sh /Car%20Images/ac%20cars/68/image-thumb__68__testThumbnailDefinitionName/automotive-car-classic-149813.jpg ``` To get an high-res version of the thumbnail, you can just add `@2x` before the file extension: ```sh /Car%20Images/ac%20cars/68/image-thumb__68__content/automotive-car-classic-149813@2x.png /Car%20Images/ac%20cars/68/image-thumb__68__content/automotive-car-classic-149813@5x.png ``` Using float is possible too: ```sh /Car%20Images/ac%20cars/68/image-thumb__68__content/automotive-car-classic-149813@3.2x.png ``` OpenDXP will then dynamically generate the thumbnails accordingly. ### Media Queries in Thumbnail Configuration If your're using media queries in your thumbnail configuration OpenDXP automatically generates a `` tag when calling `$asset->getThumbnail("example")->getHtml()`. But in some cases it is necessary to get single thumbnails for certain media queries out of the thumbnail object, which is described in the examples below. ```php $a = Asset::getById(71); // list all available medias in "galleryCarousel" thumbnail configuration p_r(array_keys(Asset\Image\Thumbnail\Config::getByName("galleryCarousel")->getMedias())); // get the element for "galleryCarousel" => default behavior $a->getThumbnail("galleryCarousel")->getHtml(); // get path of thumbnail for media query min-width: 940px $a->getThumbnail("galleryCarousel")->getMedia("(min-width: 940px)"); // get tag for media query min-width: 320px including @srcset 2x $a->getThumbnail("galleryCarousel")->getMedia("(min-width: 320px)")->getHtml(); // get 2x thumbnail path for media query min-width: 320px $a->getThumbnail("galleryCarousel")->getMedia("(min-width: 320px)", 2); ``` ### Focal Point OpenDXP supports focal points on images, which are considered when images are automatically cropped. At the moment this makes only sense if the transformation `COVER` is used. If a focal point is set on the source image, it is automatically considered and the thumbnail is cropped accordingly to ensure the focus of the image is on the focal point. ![Defining a focal point on image assets](../../img/asset_focal_point.png) ![Focal point context menu entry on document image editable](../../img/document_image_editable_focal_point.png) ![Image thumbnails cover transformation considering focal point](../../img/image_thumbnails_cover_focal_point.png) ### Clipping Support Images with an embedded clipping path (8BIM / Adobe profile meta data) are automatically clipped when generating thumbnails of them. If you do not want to use thumbnail auto clipping, you can disable the support by adding the following config option: ```yml opendxp: assets: image: thumbnails: clip_auto_support: false ``` #### Note on using WebP with Imagick using delegates Please ensure that your delegate definition for WebP encoding includes the `-q` flag, otherwise the quality setting on thumbnails will not be considered and the default value of `75` is being used by `cwebp`. Working example of a WebP encode delegate (defined in `/etc/ImageMagick-6/delegates.xml`): ```xml ``` ### Downloading Asset Thumbnails Besides embedding thumbnails into CMS pages and distributing them via other channels, backend users can download a thumbnail of an asset. In order to make a thumbnail downloadable, mark "List as option in download section on image detail view" option in Image Thumbnail Advanced settings. All thumbnails with this option enabled are listed in the "Download Thumbnail" dropdown on the detail view of an Asset. To download the thumbnail of the asset choose the thumbnail from the list and hit the "Download" button. The same thumbnails are offered by "Download as ZIP" > "Thumbnails" on a folder, which downloads the thumbnails of its images, or of the selected ones, as one ZIP file. ### Customize Auto (Web-Optimized) Format For most web-based applications it's recommended to use the auto configuration, which does multiple things: - automatically select the target image format (`jpeg`, `png`) based on image characteristics (such as alpha channel) - multiple additional optimized image formats (`webp`, `avif`) using progressive enhancement (in ` in the tag avif: quality: 15 webp: quality: null enabled: true ``` #### Config for disabling all auto-formats ```yaml opendxp: assets: image: thumbnails: auto_formats: null ``` ### Manually specify the used image processing adapter (Imagick or GD) It is possible to manually specify the used image processing adapter by OpenDXP. You can choose from `Imagick` or `GD`, the default is auto-detected, based on the availability of `imagick` PECL extension. It is also possible to implement your own adapter, by implementing `OpenDxp\Image\AdapterInterface`. To specify the used image adapter, please use the following service configuration: ```yaml services: OpenDxp\Image\AdapterInterface: alias: OpenDxp\Image\Adapter\GD public: true ``` Please be aware that the adapter service needs to be public. --- ## Video Thumbnails OpenDXP can transcode uploaded videos into web-ready formats and extract still images at any point in time. Transcoding runs asynchronously via the message queue — the result is not immediately available after the first request. > [!NOTE] > **Requires ffmpeg** > All transcoding features depend on ffmpeg being installed on the server. > See [Additional Tools Installation](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md) for setup instructions. --- ### Transformations A video thumbnail configuration is a named pipeline of transformations applied in sequence. Each transformation maps to an ffmpeg filter or option. | Transformation | Description | Option / Filter | |---------------------|-------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------| | Resize | Scale to exact dimensions, ignoring aspect ratio | [`-s WxH`](https://ffmpeg.org/ffmpeg.html#Video-Options) | | Scale by Width | Scale proportionally to a target width. Optionally skip if the video is already smaller. | [`-vf scale`](https://ffmpeg.org/ffmpeg-filters.html#scale-1) | | Scale by Height | Scale proportionally to a target height. Optionally skip if the video is already smaller. | [`-vf scale`](https://ffmpeg.org/ffmpeg-filters.html#scale-1) | | Cut | Trim the video to a start time and duration | [`-ss` and `-t`](https://ffmpeg.org/ffmpeg.html#Main-options) | | Set Framerate | Convert to a constant frame rate by duplicating or dropping frames | [`-vf fps`](https://ffmpeg.org/ffmpeg-filters.html#fps-1) | | Color Channel Mixer | Adjust color channels — useful for effects like grayscale or sepia | [`-vf colorchannelmixer`](https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer) | | Mute | Remove the audio stream entirely | [`-an`](https://ffmpeg.org/ffmpeg.html#Audio-Options) | #### Force Resize The **Scale by Width** and **Scale by Height** transformations include a **Force Resize** option (enabled by default). When **Force Resize is on**, the video is always scaled to the configured dimension — even if the source is smaller, which causes upscaling. When **Force Resize is off**, the transformation is skipped if the source video is already smaller than the target. This prevents quality loss from upscaling, which is especially relevant for vertical or low-resolution uploads. --- ### Working with Video Thumbnails in Code #### Image Snapshots You can extract a still image from any video, optionally combined with an image thumbnail configuration for resizing. ```php $asset = Asset::getById(123); if ($asset instanceof Asset\Video) { // Preview image using a named image thumbnail config echo $asset->getImageThumbnail('myThumbnail'); // Snapshot at a specific time offset (in seconds) echo $asset->getImageThumbnail(['width' => 250], 10); } ``` #### Video Transcoding Transcoding is asynchronous. The first call to `getThumbnail()` dispatches a conversion job to the message queue. Subsequent calls return the current status until the job is complete. ```php $asset = Asset::getById(123); if ($asset instanceof Asset\Video) { $thumbnail = $asset->getThumbnail('myVideoThumbnail'); echo match ($thumbnail['status']) { 'finished' => 'Ready: ' . $thumbnail['formats']['mp4'], 'inprogress' => 'Transcoding in progress — check back shortly.', 'error' => 'Transcoding failed. Check the logs for details.', default => 'Queued.', }; } ``` The `formats` array contains storage paths for each generated format, for example: ```php [ 'mp4' => '/videos/123/video-thumb__123__myVideoThumbnail/clip.mp4', 'webm' => '/videos/123/video-thumb__123__myVideoThumbnail/clip.webm', ] ``` --- ### Adaptive Bitrate Streaming (MPEG-DASH) When a thumbnail configuration contains **media segments** (multiple bitrate variants), OpenDXP generates an additional `.mpd` manifest file alongside the regular formats. This enables adaptive bitrate streaming via MPEG-DASH — the player automatically selects the appropriate quality level based on the viewer's available bandwidth. To play `.mpd` streams in all browsers, include a DASH player such as [dash.js](https://github.com/Dash-Industry-Forum/dash.js). The `opendxp_video` Twig tag handles source selection automatically: ```twig {{ opendxp_video(asset, { thumbnail: 'myVideoThumbnail' }) }} ``` Rendered output (example): ```html ``` When a `.mpd` source is present, a DASH-capable player will prefer it and adapt quality dynamically. Browsers without DASH support fall back to the `mp4` source. --- ### Output Formats Each video thumbnail configuration generates the following formats by default: | Format | Container | Video Codec | Audio Codec | Notes | |--------|-----------|-------------|----------------------|-----------------------------------------------------------------------------------------------------------------------------| | `mp4` | MP4 | H.264 | AAC | Always generated. Optimized for streaming with `faststart`. | | `webm` | WebM | VP9 | Opus (48 kHz) | VP8 fallback if ffmpeg has no VP9 support. | | `mpd` | MPEG-DASH | H.264 | AAC (via libfdk_aac) | Only generated when media segments are configured. See [Adaptive Bitrate Streaming](#adaptive-bitrate-streaming-mpeg-dash). | The `mp4` format is always included. Additional formats (`webm`, `mpd`) are generated based on the thumbnail configuration. --- ### Related - [Video Editable](../../03_Documents/01_Editables/38_Video.md) - [Additional Tools Installation](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md) --- ## Asset Document Thumbnails (PDF, DOCX, ODF, ...) This feature allows you to create an image thumbnail of nearly any document format, like doc(x), ppt(x), pdf, xls(x), odt, ods, odp and many others. You can of course use existing image-thumbnail configurations to create a thumbnail of your choice. > **Important** > Please be aware that the processing of thumbnails for documents is done asynchronously as part of the [maintenance job](../../01_Getting_Started/00_Installation/01_Webserver_Installation.md#5-maintenance-cron-job), under the `opendxp_asset_update` messenger queue ###### Examples ```php $asset = Asset::getById(123); if($asset instanceof Asset\Document) { // get a thumbnail of the first page, resized to the configuration of "myThumbnail" echo $asset->getImageThumbnail("myThumbnail"); // get the thumbnail for the third (see second parameter) page using a dynamic configuration echo $asset->getImageThumbnail(["width" => 230, "contain" => true], 2); // get the thumbnail URL for all pages, but do not generate them immediately (see third parameter) - the thumbnails are then generated on request $thumbnailUrls = []; for($i=1; $i<=$asset->getPageCount(); $i++) { $thumbnailUrls[] = $asset->getImageThumbnail("myThumbnail", $i, true); } } ``` This feature requires Ghostscript and at least [Gotenberg](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md#gotenberg) or [LibreOffice](../../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/06_Additional_Tools_Installation.md#libreoffice-pdftotext-inkscape-) to be installed on the server. ###### To build the function generating thumbnail for List of assets: > It is recommended to use named thumbnails for caching purpose. ```php $list = new Asset\Listing(); $assets = $list->getAssets(); foreach ($assets as $asset) { echo match (true) { $asset instanceof Asset\Image => $asset->getThumbnail('myThumbnail')?->getPath(), $asset instanceof Asset\Document => $asset->getImageThumbnail('myThumbnail')?->getPath(), default => '', }; } ``` ### Disable generating thumbnails for asset documents If you want to completely disable the thumbnail generation for asset documents, this can be done with following config: ```yaml opendxp: assets: document: thumbnails: enabled: false ``` --- ## Working With Thumbnails OpenDXP provides a sophisticated thumbnail processing engine for calculating thumbnails based on source assets. So for different output channels OpenDXP can calculate and provide optimized images in terms of dimensions, file sizes, formats and much more. This functionality allows true single source publishing with OpenDXP. #### Allowed formats OpenDXP allows the following formats for thumbnails out of the box: `'avif', 'eps', 'gif', 'jpeg', 'jpg', 'pjpeg', 'png', 'svg', 'tiff', 'webm', 'webp', 'print'`. If you want to use a different format, you can easily extend the list of supported formats. Keep in mind that you must copy the whole list of formats and add your desired format to it. ```yaml opendxp: assets: thumbnails: allowed_formats: - 'avif' - 'eps' - 'gif' - 'jpeg' - 'jpg' - 'pjpeg' - 'png' - 'svg' - 'tiff' - 'webm' - 'webp' - 'pdf' - 'print' # Add your desired format here ``` ###### Thumbnails are available for following file types: * [Image Thumbnails](./01_Image_Thumbnails.md) * [Video Thumbnails](./03_Video_Thumbnails.md) * [Asset Document Thumbnails](./05_Document_Thumbnails.md) --- ## Accessing OpenDXP Assets via WebDAV OpenDXP provides the option to access all assets via [WebDAV](https://en.wikipedia.org/wiki/WebDAV). To do so, just open following URL via your browser or WebDAV client: https://YOUR-DOMAIN/asset/webdav As user credentials use any OpenDXP Backend user. Permissions for asset access are based on the users permissions. #### Nginx configuration Please make sure to have the following changes in your project [Nginx configuration](../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/02_Nginx_Configuration.md): ``` location ~* ^(?!/admin|/asset/webdav)(.+?).... ``` --- ## Restricting Public Asset Access OpenDXP has following default behavior in terms of asset delivery: > All Data that is stored as OpenDXP Assets can be accessed via its URL (e.g. https://mydomain.com/my-assetfolder/my-asset.jpg) > and therefore is public available without login or other access restriction! > > As a consequence confidential data **must not** be stored as OpenDXP Assets without additional protection measures. The reason for this wanted behavior is performance. Delivering an asset directly via the web server needs significantly less resources than starting a php process for every asset request (especially when it comes to delivering thumbnails). If further restriction is needed, OpenDXP provides two options for doing so: #### Option 1 - Restricting access to certain assets completely All confidential assets need to be stored within one (or a few) folder(s), e.g. within `/protected` (to set up OpenDXP backend permissions this is necessary anyway). ![Protected Folder](../img/asset-access-restriction.png) **Apache** In the `.htaccess` of the project, the access to this folder has to be restricted with an additional rewrite rule. It is important, that this rule is placed **in front of** the rewrite rule for asset delivery. ```apache ... RewriteRule ^protected/.* - [F,L] RewriteRule ^var/.*/protected(.*) - [F,L] RewriteRule ^cache-buster\-[\d]+/protected(.*) - [F,L] # ASSETS: check if request method is GET (because of WebDAV) and if the requested file (asset) exists on the filesystem, if both match, deliver the asset directly ... ``` **Nginx** Add the following parts to your Nginx configuration directly after the index directive. ```nginx location ~ ^/protected/.* { return 403; } location ~ ^/var/.*/protected(.*) { return 403; } location ~ ^/cache-buster\-[\d]+/protected(.*) { return 403; } ``` A full configuration example can be found [on this page](../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/02_Nginx_Configuration.md). Because of this rule, all assets located within `/protected` (also all their thumbnails) are not delivered via the web server anymore. As a consequence also using the direct link for downloading or using the OpenDXP generated img tags for thumbnails cannot be used anymore. All delivery of these assets has to be done manually via a custom controller action. #### Option 2 - Checking permissions before delivery This option does not restrict the delivery in general, but routes the asset request to a controller action that can check access permissions with custom business logic and then deliver the asset or not. Again all confidential assets need to be stored within one (or a few) folders, e.g. within `/protected`. ![Protected Folder](../img/asset-access-restriction.png) **Apache** In the `.htaccess` of the project, requests to assets of this folder need to be routed to `index.php`. Again, it is important, that this rule is placed **in front of** the rewrite rule for asset delivery. ```apache ... RewriteRule ^protected/(.*) %{ENV:BASE}/index.php [L] RewriteRule ^var/.*/protected(.*) - [F,L] RewriteRule ^cache-buster\-[\d]+/protected(.*) - [F,L] # ASSETS: check if request method is GET (because of WebDAV) and if the requested file (asset) exists on the filesystem, if both match, deliver the asset directly ... ``` **Nginx** Add the following parts to your Nginx configuration directly after the index directive. ```nginx rewrite ^(/protected/.*) /index.php$is_args$args last; location ~ ^/var/.*/protected(.*) { return 403; } rewrite ^(/cache-buster-(?:\d+)/protected(?:.*)) /index.php$is_args$args last; location ~ ^/cache-buster\-[\d]+/protected(.*) { return 403; } ``` A full configuration example can be found [on this page](../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/02_Nginx_Configuration.md). In the application, there has to be a route in (config/routes.yaml) and a controller action that handles the request, e.g. like the following: ```yaml # config/routes.yaml # important these have to be the top routes in the file! asset_protect: path: /protected/{path} defaults: { _controller: App\Controller\MyAssetController::protectedAssetAction } requirements: path: '.*' cache_buster_asset_protect: path: /cache-buster-{id}/protected/{path} defaults: { _controller: App\Controller\MyAssetController:protectedAssetAction } requirements: id: '\d+' path: '.*' ``` ```php getPathInfo(); $asset = Asset::getByPath($pathInfo); if ($asset){ $stream = $asset->getStream(); return new StreamedResponse(function () use ($stream) { fpassthru($stream); }, 200, [ 'Content-Type' => $asset->getMimeType(), ]); } else { return Asset\Service::getStreamedResponseByUri($pathInfo); } throw new AccessDeniedHttpException('Access denied.'); } } ``` Of course this option has significant impact on server load and delivery performance of assets (and thumbnails). Therefore it is **not** suggested to deliver all assets that way but only the confidential ones! --- ## Assets Assets are files that can be managed within the OpenDXP system which you can organize in folders. The most common assets are images. Other kinds of common assets are PDF or MS Word documents which people can download from the website. OpenDXP is able to render preview images for most file types. ###### Following file types are supported for preview: * Images: All common formats such as .jpg, .png, .eps, .psd, .tif, .svg, ... (See [Imagemagick website](https://imagemagick.org/script/formats.php) for a full list of supported formats) * Videos: All common formats such as .avi, .mp4, .mkv, .mov, ... (See [FFmpeg website](https://www.ffmpeg.org/general.html#File-Formats) for a full list of supported formats) * Documents: All Microsoft Office formats such as .docx, .docm, .pptx, .xlsx and formats such as .pdf, .rtf, ... (See [LibreOffice documentation](https://wiki.documentfoundation.org/images/1/13/1_-_File_Formats.odt) for a full list of supported formats) > Please note: The asset preview tab for documents uses Google services, if the client browser has no PDF > displaying capabilities and Ghostscript or LibreOffice are not available on the server. Some file types, like images, can be edited directly in OpenDXP and can be used to create thumbnails for different output channels. Note that the image editor does use the [miniPaint image editor](https://github.com/viliusle/miniPaint) under the hood. As Asset documents depend on background processes to generate thumbnails and search text, these processes require page count processing. Occasionally, this results in the consumption of unnecessary processing resources, even when the feature is not extensively used. In such situations, it is possible to disable the background processing as follows: ```yaml opendxp: assets: document: thumbnails: enabled: false #disable generating thumbnail for asset documents process_page_count: false #disable processing page count process_text: false #disable processing text extraction scan_pdf: false #disable scanning PDF documents for unsafe JavaScript. open_pdf_in_new_tab: all-pdfs #show only thumbnail for every pdf #open_pdf_in_new_tab: only-unsafe #show only thumbnail for pdf with JavaScript #open_pdf_in_new_tab: none #show every pdf (not recommended) ``` The sub chapters of this chapter provide insight into details for * [Working with Assets via PHP API](./01_Working_with_PHP_API.md) * [Working with Thumbnails](./03_Working_with_Thumbnails/README.md) * [Accessing Assets via WebDAV](./05_Accessing_Assets_via_WebDAV.md) * [Restricting Public Asset Access](./07_Restricting_Public_Asset_Access.md) --- ## Blocks The block data type acts as a simple container for other data fields. Similar to a field collection, an unlimited number of block elements can be created. A block element can be placed into a localized field but can also contain a localized field itself. Nesting is not possible. ![Block data type](../../../img/ObjectsBlocks_data_container.png) ![Block, edit peview](../../../img/ObjectsBlocks_edit_preview.png) > The block data basically just gets serialized into a single database column. > As a consequence, this container type is not suitable, if you are planning to query the data. #### API Usage Let us consider the following class definition ![Class Definition](../../../img/block-classdefinition.png) and object data ![Class Definition](../../../img/block-values.png) The value of the second input field can be retrieved as follows: ```php $object = DataObject\BlockClass::getById(48); $blockItems = $object->getBlockElement1(); $firstBlockItem = $blockItems[0]; echo($firstBlockItem["input2"]->getData()); ``` The output will be "value2". The value can be updated in a similar way. ```php // ... same as above ... $firstBlockItem["input2"]->setData(time()); $object->save(); ``` Get Values of Localized Block Entries: ```php $object = DataObject\BlockClass::getById(48); $blockItems = $object->getBlockElement1(); $firstBlockItem = $blockItems[0]; $localizedfields = $firstBlockItem["localizedfields"]->getData(); // after that use it as you would to it with `OpenDxp\Model\DataObject\LocalizedField::getLocalizedValue` ``` Create a Block: ```php /** * @var DataObject\Data\BlockElement $blockElement * * BlockElement( name, type, data ) */ $object = DataObject::getById(4); $data = [ "input1" => new BlockElement('input1', 'input', 'NewValue1'), "input2" => new BlockElement('input2', 'input', 'NewValue2'), "myhref" => new BlockElement('myhref', 'manyToManyRelation', [$object]) ]; $blockElement = new BlockClass(); $blockElement->setBlockElement1([$data]); ``` Create a Block with localized fields: ```php $object = DataObject::getById(4); $data = [ "input1" => new BlockElement('input1', 'input', 'NewValue1'), "input2" => new BlockElement('input2', 'input', 'NewValue2'), "myhref" => new BlockElement('myhref', 'manyToManyRelation', [$object]), "localizedfields" => new BlockElement('localizedfields', 'localizedfields', new Localizedfield([ "de" => [ "localizedInput" => "Mein deutscher Text" ], "en" => [ "localizedInput" => "My English text" ] ])) ]; $object->setMyBlockField([$data]); ``` --- ## Calculated Value Datatype ### General The calculated-value datatype allows you to calculate attributes based on the value of various other attributes. The value is always calculated on the fly when calling the corresponding getter, no caching applied. The only data stored is the one in the object's query tables for being able to query (e.g. grid filtering) for calculated values. > Values in the query table are only updated when the data object is saved. So be careful, the values in the query > table might not be up-to-date depending on the caluclation parameters. As display type in object editor three types are available: - Input: Single line, displayed as read-only input field. - TextArea: Multi line, displayed as read-only text area. - HTML: Multi line HTML content, displayed as display field. ### Calculation For defining the calculation two options are available: #### Expression The simplest way for defining the calculation is providing an expression. The expression language is based on the [symfony expression language component](https://symfony.com/doc/current/components/expression_language.html). Please see [syntax docs](https://symfony.com/doc/current/components/expression_language/syntax.html) for details concerning possibilities. ###### Available variables - DataObject itself as `object`. - Context information as `data` (details see Context Information for Calculation below). ###### Simple examples ``` # print ID of data object object.getId() # print firstname and lastname of data object object.getFirstname() ~ ' ' ~ object.getLastname() # check if field is empty object.getText() != '' ? 'yes' : 'no' # get fieldname of current field data.getFieldname() ``` #### Calculator Class The second option for defining the calculation is providing a php calculator class. This is especially useful for more complex calculations and reusing the calculators. The calculator class is a standard symfony service (or simple php class) that implements the `CalculatorClassInterface`. ##### Setup in Class Definition The calculator class can be defined in two ways: - **Symfony service** (prefered way): Provide service name prefixed with `@` (e.g. `@service_name`), service needs to be public. - **Standard PHP class**: Provide fully qualified namespace name of class, OpenDXP will instanciate it with `new`. ![Calculated Value Configuration](../../../img/classes-datatypes-calculated-definition.png) ##### Calculator Class Implementation Let's suppose we have a very simple class with 2 number fields called xValue and yValue and a calculated-value field called `sum` placed inside a localizedfields container. The PHP calculator class needs to implement the `CalculatorClassInterface` interface. The `compute` method needs to be implemented which computes the result for the `sum` field. The arguments passed into this method is the OpenDXP object and the contextual information with details about calculated-value field is affected and where it is located at (details see Context Information for Calculation below). ```php namespace App; use OpenDxp\Logger; use OpenDxp\Model\DataObject\Concrete; use OpenDxp\Model\DataObject\ClassDefinition\CalculatorClassInterface; use OpenDxp\Model\DataObject\Data\CalculatedValue; class Calculator implements CalculatorClassInterface { public function compute(Concrete $object, CalculatedValue $context): string { if ($context->getFieldname() == "sum") { $language = $context->getPosition(); return $object->getXValue($language) + $object->getYValue($language); } else { Logger::error("unknown field"); return ''; } } } ``` As we see here, the calculator class sums up the x and y values from the corresponding language tab. In addition to the `compute` method you need to implement the `getCalculatedValueForEditMode` method. This method is used to display the value in object edit mode: ```php public function getCalculatedValueForEditMode(Concrete $object, CalculatedValue $context): string { $language = $context->getPosition(); $result = $object->getXValue($language) . " + " . $object->getYValue($language) . " = " . $this->compute($object, $context); return $result; } ``` ##### Result The visual outcome would be as follows: ![Calculated Value Field](../../../img/classes-datatypes-calculated-field.png) ### Context Information for Calculation The content of the context information depends on the location of the calculated-value field in the data model. ##### Object (top-level) | Name | Description | | --- | ---- | | ownerType | `"object"` | | fieldName | the name of the calcuated-value field (e.g. `sum`) | ##### Localizedfields | Name | Description | | --- | ---- | | position | the language ("en", "de", ...) | | ownerType | `"localizedfield"` | | ownerName | the name of the localized field ("localizedfields") | ##### Objectbricks | Name | Description | | --- | ---- | | ownerType | `"objectbrick"` | | ownerName | the name of the objectbrick field inside the object | | fieldName | the name of the attribute inside the brick | | index | the name of the brick | | keyDefinition | the calculated-value field definition | | position | the language ("en", "de", ...) if calculated field is localized | ##### Fieldcollections | Name | Description | | --- | ---- | | ownerType | `"fieldcollection"` | | ownerName | the name of the fieldcollection attribute | | fieldName | the name of the attribute inside the fieldcollection | | index | the index of the fieldcollection item | | keyDefinition | the calculated-value field definition | ##### Classification Store | Name | Description | | --- | ---- | | ownerType | `"classificationstore"` | | ownerName | the name of the fieldcollection attribute | | fieldName | the name of the attribute inside the fieldcollection | | position | the language | | groupId | group id | | keyId | key id | | keyDefinition | the fielddefinition of the classificationstore attribute | ### Working with PHP API Getter methods on the object class are generated as usual. The code to retrieve the values would then be: ```php $object = DataObject::getByPath("/demoobject"); $valueDe = $object->getSum("de"); // => 38 $valueEn = $object->getSum("en"); // => 11 ``` --- ## Classification Store(Data_Types) ### Overview The classification store has quite some similarities to a key/value-like datatype. A key/value data type allows to add an arbitrary number of key/value pairs to objects with the restriction that each key can only be added once to that object. ##### The most important facts: * There can be multiple store with completely isolated feature sets. * Inheritance is supported. * An object can have more than one classification store. * Localization is supported (optionally, can be configured in the class definition). * The classification store introduces the concept of a fallback language. * All simple data types (e.g. textarea, date, etc are supported). The store can be extended with custom data types. * Takes advantage of the built-in mechanism for the field definition + data editing (validation, etc). * Keys can be organized in groups. * A key can belong to several groups. * Individual keys currently cannot be added to the object. Instead, the corresponding groups added. * The allowed groups can be restricted via the class definition. ### Configuration of Classification Stores Before using the classification store, at least one classification store with collections, groups and keys has to be defined. #### Key definition * Go to classification store in Objects menu: ![Classification store menu](../../../img/Objects_ClassificationStore_menu.png) * Add a new store if necessary * Add a key * Select type ![choose Classification Store type](../../../img/Objects_ClassificationStore_type.png) * Click on the configuration button on the right for detailed settings * Note that not all settings are respected (e.g. `indexed`) ![Classification Store detailed config](../../../img/Objects_ClassificationStore_detailed_config.png) #### Group definition and key assignment * Use the group editor to define and organize keys into groups * Similar to keys a sort order can be specified * Groups with lower sort order are displayed first * A key can belong to more than one group * It is not necessary for the group name to be unique * Use the grid on the right side to manage the keys belonging to the selected group * Configure sort order for the object editor, keys with lower values are listed first * Configure which keys should be mandatory in this group ![Classification store groups management](../../../img/Objects_ClassificationStore_groups_grid.png) #### Collection definition * Groups can optionally be organized into collections * A collection is simply a container which allows to add several groups at once, there is no actual logic behind it ![Classification store - group collections](../../../img/Objects_ClassificationStore_group_collections_grid.png) ### Class definition * Localization can be enabled, by default only the `default` language is available * Allowed groups can be restricted by providing a comma-separated list of group ids * There can be more than one classification store field * Configure the group sort order for the object editor, groups with lower values are listed first * Optionally you can decide whether you want to see all keys or just the non-empty ones. * Optionally you can disable add/remove of groups in object editor (in this case, groups can only added and removed via API) * Optionally you can define a limit of how many groups can be used ![Class definitaion with Classification Store](../../../img/Objects_ClassificationStore_classes.png) ### Object editor * Groups can be added/removed via the add/remove buttons (see screenshot below) * Keys are displayed in the specified sort order. If the order is equal then the keys are sorted by creation date ![Edit classification store in object](../../../img/Objects_ClassificationStore_edit_object.png) ### Inheritance In contrast to localized fields fallback and inherited values are first resolved in a horizontal way. If no value can be found on the same level, the parent level is scanned in the same language order. As mentioned before, there is the concept of a `default` language which is just an additional pseudo language which acts as the last resort. Consider the following example and let’s assume that English is the fallback language for German. We request the German value for the object at level 3. Since the only value can be found on level 1 for the default language the tree is traversed as depicted. ![Language value levels in Classification store](../../../img/Objects_ClassificationStore_levels.png) ### Using Classification Store via PHP API ```php // setter, group id = 1, key id id = 2, language = de // the value is of type "quantity value" where 1 is the unit ID in this example $heightValue = new \OpenDxp\Model\DataObject\Data\QuantityValue(13, 1); $object->getClassificationStore2()->setLocalizedKeyValue(1, 2, $heightValue, "de"); // 1 = group id $object->getClassificationStore2()->setActiveGroups([1 => true]); // provide additional information about which collection the group belongs to // group 1 belongs to collection with ID 2 $object->getClassificationStore2()->setGroupCollectionMapping(1, 2); // retrieve the mapping // this will return 2 => collection with ID 2 $object->getClassificationStore2()->getGroupCollectionMapping(1); // getter, group id = 1, key id id = 2, language = de $value = $object->getClassificationStore2()->getLocalizedKeyValue(1, 2, "de"); // get the list of active groups $store = $object->getClassificationStore2(); $groups = $store->getActiveGroups(); // get all values as associative array [groupId][keyid][language] => value $allValues = $store->getItems(); ``` #### Retrieving group and key data The `ClassificationStore::getGroups()` method returns an array of `Group` objects. In turn, the `Group::getKeys()` method returns an array of `Key` objects for that group. ```php /** @var \OpenDxp\Model\DataObject\Classificationstore $classificationStore */ $classificationStore = $dataObject->get(); foreach ($classificationStore->getGroups() as $group) { var_dump($group->getConfiguration()->getName()); foreach ($group->getKeys() as $key) { $keyConfiguration = $key->getConfiguration(); $value = $key->getValue(); if ($value instanceof \OpenDxp\Model\DataObject\Data\QuantityValue) { $value = (string)$value; } var_dump([ $keyConfiguration->getId(), $keyConfiguration->getType(), $keyConfiguration->getName(), $keyConfiguration->getTitle(), $value, ($key->getFieldDefinition() instanceof QuantityValue), ]); } } ``` The `Key::getValue()` method supports the `language`, `ignoreFallbackLanguage` and `ignoreDefaultLanguage` arguments. ```php /** @var \OpenDxp\Model\DataObject\Classificationstore\Key $key */ $key->getValue('en_GB', true, true); ``` #### Adding new items to Classification Store through code ```php // KeyConfig // first of all, define the datatype which is quantity value in this example $definition = new \OpenDxp\Model\DataObject\ClassDefinition\Data\QuantityValue(); $definition->setName("height"); $definition->setTitle("Height"); $keyConfig = new \OpenDxp\Model\DataObject\Classificationstore\KeyConfig(); $keyConfig->setStoreId($storeId); $keyConfig->setName($name); $keyConfig->setDescription($description); $keyConfig->setEnabled(true); $keyConfig->setType($definition->getFieldtype()); $keyConfig->setDefinition(json_encode($definition)); // The definition is used in object editor to render fields $keyConfig->save(); // Group $groupConfig = new \OpenDxp\Model\DataObject\Classificationstore\GroupConfig(); $groupConfig->setStoreId($storeId); $groupConfig->setName($name); $groupConfig->setDescription($description); $groupConfig->save(); // Collection $collectionConfig = new \OpenDxp\Model\DataObject\Classificationstore\CollectionConfig(); $collectionConfig->setStoreId($storeId); $collectionConfig->setName($name); $collectionConfig->setDescription($description); $collectionConfig->save(); // Add a key to group $keyRel = new \OpenDxp\Model\DataObject\Classificationstore\KeyGroupRelation(); $keyRel->setGroupId($groupConfig->getId()); $keyRel->setKeyId($keyConfig->getId()); $keyRel->save(); // Add a group to a collection $groupRel = new \OpenDxp\Model\DataObject\Classificationstore\CollectionGroupRelation(); $groupRel->setGroupId($groupConfig->getId()); $groupRel->setColId($collectionConfig->getId()); $groupRel->save(); ``` --- ## Consent This data type can be used to store consent of users for something like permission for sending direct mailings. Consent itself is stored as checkbox in data object, additional meta information (like timestamp and all other things) are stored as a note on the corresponding object. This note is created for both actions - when a consent is given and when a consent is revoked. ![Data Type Consent](../../../img/classes-datatypes-consent.png) #### Usage in OpenDXP Admin Backend The consent value can be changed directly in object editor. Every time the value changes, a note with default values is added automatically. #### Usage in PHP API When setting consent in custom controllers or in other places, use the service `OpenDxp\DataObject\Consent\Service` and its methods `giveConsent` and `revokeConsent`. Please make sure that your DataObject was saved before using the Consent Service. If your DataObject doesent have an Id the note cannot be saved! ```php $request->getClientIp() ]; /** * @var OpenDxp\DataObject\Consent\Service $consentService **/ $consentService->giveConsent($customer, "directMailing", $consentMessage, $metaInfo); ``` --- ## Date Datatypes ### Date, Date & Time The `date` and `date & time` object fields are represented by a calender widget in the OpenDXP GUI. ![Date Field](../../../img/classes-datatypes-date1.jpg) In the database its data is saved either as `date`/`datetime` field type or as unix timestamp (`bigint(20)`) depending on the configured column type. Programmatically these data types are represented by a [DateTime/Carbon](https://github.com/briannesbitt/Carbon) Object. #### Behaviour regarding user timezones The `date` and `date & time` object fields can be configured to respect the user's timezone. If timezone support is enabled the OpenDXP admin UI will display the date and time in the user's timezone. Without timezone support the date and time will be shown exactly as it was entered independent of the user's timezone. For the `date` object field timezones are taken into account when the `bigint` column type is chosen whereas for the `date` column type the timezone is ignored. For the `date & time` object field timezones are taken into account when the "respect timezone" option in the class editor is enabled. Disabling the timezone support will only work in combination with the `datetime` column type. ### Time The `time` data field is the same drop down list of day times as in the `date & time` field. ![Time Field](../../../img/classes-datatypes-date2.jpg) It's stored as a string in a VARCHAR(5) column in the database and can be set programmatically by simply passing a string like for example "11:00" to the field's setter. ### Date Range The `dateRange` object field consists of two `date` fields (start and end date) and can be filled with the usual calendar widget in the OpenDXP GUI or programmatically via the OpenDXP API. ![Date Range Field](../../../img/classes-datatypes-date3.jpg) The two dates are stored as unix timestamps in two separate INT columns in the database. Programmatically the date range is represented by a [CarbonPeriod](https://carbon.nesbot.com/docs/#api-period) Object. --- ## Select Types With Dynamic Options For the select & multiselect datatype you can specify a dynamic options provider class. This allows you to generate a list of valid options on-the-fly instead of using a static list. The select datatype also allows you to define the default option at runtime. You can also add some additional static data which will be passed to the data provider. Note that there are two ways to define an options provider. Either simply specify the class name ... ![Select Field](../../../img/dynamic_select_class.png) ... or the name of a Symfony service (notice the prefix). ![Select Field](../../../img/dynamic_select_service.png) The services.yaml would then look like this: ```yaml services: website.optionsprovider: class: Website\OptionsProvider public: true ``` You have to implement the `OpenDxp\Model\DataObject\ClassDefinition\DynamicOptionsProvider\SelectOptionsProviderInterface` Implement the following methods: * `getOptions` should return a list of valid options in the format indicated below * `getDefaultValue` returning the default value * `hasStaticOptions` should return whether your options are depending on the object context (i.e. different options for different objects) or not. This is especially important for the object grid. For object-context depending option there will be no batch assignment mode. Also, filtering can only be done through a text field instead of the options list. ```php getId() : "unknown") . " - " .$context["fieldname"]; $result = array( array("key" => $fieldname .' == A', "value" => 2), array("key" => $fieldname .' == C', "value" => 4), array("key" => $fieldname .' == F', "value" => 5) ); return $result; } /** * Returns the value which is defined in the 'Default value' field */ public function getDefaultValue(array $context, Data $fieldDefinition): ?string { if (method_exists($fieldDefinition, 'getDefaultValue')) { return $fieldDefinition->getDefaultValue(); } return null; } public function hasStaticOptions(array $context, Data $fieldDefinition): bool { return true; } } ``` This will generate the following options. ![Select Field](../../../img/dynselect2.png) ### Context Information for the Provider Class Note that depending the use case not all of the infos will be available. Especially the existence of the object paramater cannot be guaranteed because the provider class will also be called when a class is saved or if you programmatically call $class->getFieldDefinitions(). Layout definition calls can be distinguished from other ones by checking if the `purpose` parameter is set to `layout` The `purpose` parameter can take the following values: | Value | Description | | --- | ---- | | null | unknown | | layout | edit mode layout | | gridconfig | grid configuration - usually no need to specify dynamic options| | gridview | grid view | ##### Object (top-level) | Name | Description | | --- | ---- | | object | the `"object"` | | fieldname | the name of the select field (e.g. `dynSelect`) | ##### Localizedfields | Name | Description | | --- | ---- | | ownerType | `"localizedfield"` | | ownerName | the name of the localized field ("localizedfields") | | object | the `"object"` | | fieldname | the name of the select field (e.g. `dynSelect`) | ##### Objectbricks | Name | Description | | --- | ---- | | containerType | `"objectbrick"` | | containerKey | the type of the object brick | | outerFieldname | the object's object brick attribute | | object | the `"object"` | | fieldName | the name of the attribute inside the object brick | ##### Fieldcollections | Name | Description | | --- | ---- | | containerType | `"fieldcollection"` | | containerKey | the type of the fieldcollection | | subContainerType | sub container type (e.g. localized field inside a field collection) | | outerFieldname | the object's field collection attribute | | object | the `"object"` | | fieldName | the name of the attribute inside the fieldcollection | ##### Classification Store | Name | Description | | --- | ---- | | ownerType | `"classificationstore"` | | ownerName | the name of the classificationstore attribute | | fieldname | the name of the attribute inside the fieldcollection | | groupId | group id | | keyId | key id | | keyDefinition | the fielddefinition of the classificationstore attribute | --- ## Fieldcollection ### General Usage Object field collections are predefined sets of data and layout fields, that can be added to objects at an arbitrary amount. An object field collection is very similar to an object itself. It has a *class* or in this case **field definition** which needs to be made first, and then different field collection definitions can be used to add sets of fields to an object. So with some restrictions you could say, a field collection is an object within an object. When adding a field collection field to an object's class definition, the developer needs to specify the allowed field definition types for this field. ![Fieldcollection Configuration](../../../img/classes-datatypes-fieldcollection2.png) The user can then decide which and how many of the available field definitions shall be added to the object. ![Fieldcollection Field](../../../img/classes-datatypes-fieldcollection3.png) ### Data Storage Field definition data is stored in a separate table for each field definition and object class. The naming convention for these tables is: `object_collection_COLLECTION-NAME_OBJECT-ID`. Such a table contains all the field data, the concrete object's id, field name and index of the field collection within the field collection data field. In order to fully understand the data structure of objects and field collections, it is best to enter some example data and have a look at the tables created by OpenDXP. ### Working with PHP API Of course, field collection data can be set programmatically as well. The following code snippet illustrates how this can be achieved. Let's say there is an object class **collectiontest** and a fieldcollection called **MyCollection*. There is an object field called **collectionitems** which is of the type field collection. ```php $object = new DataObject\Collectiontest(); $object->setParentId(1); $object->setUserOwner(1); $object->setUserModification(1); $object->setCreationDate(time()); $object->setKey(uniqid() . rand(10, 99)); $items = new DataObject\Fieldcollection(); for ($i = 0; $i < 5; $i++) { $item = new DataObject\Fieldcollection\Data\MyCollection(); $item->setMyinput("This is a test " . $i); $items->add($item); } $object->setCollectionitems($items); $object->save(); ``` If you want to use localized fields inside field collections you have to set the object before calling any localized field - related methods. ```php $item = new DataObject\Fieldcollection\Data\MyCollection(); $item->setObject($object); ``` ### Inheritance Field collections do not support inheritance out of the box because currently field collection data does not get saved to a query table (so you would not be able to query for inherited data). Nevertheless, you can use inheritance for field collections for data maintenance by [overriding the class](../../../20_Extending_OpenDxp/03_Overriding_Models.md) which contains the field collection field and adding a custom getter method to this overriding class: ```php // custom getter for field collection field named 'fieldCollection' public function getFieldCollection(): mixed { $data = parent::getFieldCollection(); $inheritedData = DataObject\Service::useInheritedValues(true, function() use ($data) { if (\OpenDxp\Model\DataObject::doGetInheritedValues($this) && $this->getClass()->getFieldDefinition("fieldCollection")->isEmpty($data)) { try { return $this->getValueFromParent("fieldCollection"); } catch (\OpenDxp\Model\DataObject\Exception\InheritanceParentNotFoundException $e) { // no data from parent available, continue ... return null; } } return null; }); return $inheritedData ?? $data; } ``` Beware that only complete field collection containers can be inherited. As soon as you change the order of the field collection items or any field value in a child object, the whole field collection will get assigned to that child object. There could also be some UI quirks in the OpenDXP backend. --- ## Geographic Datatypes There are different geographic data types available in opendxp: `Geopoint`, `Geobounds`, `Geopolygon` and `Geopolyline`. The country select box also belongs to the context of geo widgets, but it is rather a select input widget and therefore it is listed with the other select widgets. ### Geopoint ![GeoPoint Field](../../../img/classes-datatypes-geo1.jpg) The geopoint consists of two coordinates: latitude and longitude. In the OpenDXP GUI there is the same geopoint selector widget as shown above. It allows to find coordinates for a geographic point easily. In the database the values are stored in two columns which are called latitude and longitude. Programmatically the data for this field is represented by `OpenDxp\Model\DataObject\Data\Geopoint`. To set a geopoint programmatically, a new `OpenDxp\Model\DataObject\Data\GeoCoordinates` has to be instantiated: ```php $longitude = 107.6191228; $latitude = -6.9174639; $point = new \OpenDxp\Model\DataObject\Data\GeoCoordinates($latitude, $longitude); $object->setPoint($point); $object->save(); ``` ### Geobounds ![GeoBounds Field](../../../img/classes-datatypes-geo2.jpg) Geobounds represent a geographic area defined by a north eastern point and a south western point. In the OpenDXP GUI the input widget as shown above is available. In the database there are 4 columns with coordinates to hold the data of geobounds. Programmatically both points are `OpenDxp\Model\DataObject\Data\GeoCoordinates` and they are wrapped by the `OpenDxp\Model\DataObject\Data\GeoCoordinates` Object. The following code snippet shows how to set Geobounds: ```php use OpenDxp\Model\DataObject\Data\Geobounds; use OpenDxp\Model\DataObject\Data\GeoCoordinates; $northEast = new GeoCoordinates(150.96588134765625, -33.704920213014425); $southWest = new GeoCoordinates(150.60333251953125, -33.893217379440884); $object->setBounds(new Geobounds($northEast,$southWest)); $object->save(); ``` ### Geopolygon ![GeoPolygon Field](../../../img/classes-datatypes-geo3.jpg) The geopolygon is the third in the row of geo widgets. It allows to define a geographic area by setting an arbitrary amount of geo points. In the database these points are stored in a single column of the data type LONGTEXT in the form of a serialized array of `OpenDxp\Model\DataObject\Data\GeoCoordinates`. To set geopolygon data programmatically, an array of Geopoints has to be passed to the setter: ```php use OpenDxp\Model\DataObject\Data\GeoCoordinates; $data = [ new GeoCoordinates(-33.464671118242684, 150.54428100585938), new GeoCoordinates(-33.913733814316245, 150.73654174804688), new GeoCoordinates(-33.9946115848146, 151.2542724609375) ]; $object->setPolygon($data); $object->save(); ``` ### Geopolyline ![GeoPolyline Field](../../../img/classes-datatypes-geo4.jpg) It allows to define a geographic path by setting an arbitrary amount of geo points. In the database these points are stored in a single column of the data type LONGTEXT in the form of a serialized array of `OpenDxp\Model\DataObject\Data\GeoCoordinates`. To set geopolygon data programmatically, an array of Geopoints has to be passed to the setter: ```php use OpenDxp\Model\DataObject\Data\GeoCoordinates; $data = [ new GeoCoordinates(-33.464671118242684, 150.54428100585938), new GeoCoordinates(-33.913733814316245, 150.73654174804688), new GeoCoordinates(-33.9946115848146, 151.2542724609375) ]; $object->setPolyline($data); $object->save(); ``` --- ## Image Datatypes ### Image ![Image Field](../../../img/classes-datatypes-image1.jpg) An image field is stored in an INT column in the database. It holds the ID of the referenced `\OpenDxp\Model\Asset\Image`. Unlike other object relation types, an image relation is not stored in the relations table (this has historic reasons), but it creates a dependency in the dependencies table. To set an object's image field programmatically, an `\OpenDxp\Model\Asset\Image` must be passed to the according setter. ```php $image = Asset\Image::getByPath("/examples/example1.jpg"); $object->setImage($image); $object->save(); ``` The image field is represented in the UI by an image drop area. The image drop area's width and height can be configured in the class settings as follows: ![Image Configuration](../../../img/classes-datatypes-image2.jpg) ##### Working with images in frontend The get a thumbnail of an image field, just call `getThumbnail()` on the returned asset object. ```twig {% if object.myImage is instanceof('OpenDxp\Model\Asset\Image') %} {{ object.myImage.thumbnail('myThumbnailDefinitionName').html }} {% endif %} ``` Since `$object->getImage()` just returns an asset object, you can of course use all other thumbnail features of `OpenDxp\Model\Asset\Image`. ### External Image This one allows you to enter an external image URL which is then shown as a preview. ![External Image Field](../../../img/classes-datatypes-image3.jpg) ```twig {% if object.getExternalImage() is instanceof('\\OpenDxp\\Model\\DataObject\\Data\\ExternalImage') %} {% endif %} ``` ### Image Gallery Is a collection of `Advanced Images` (see below). The sort order can be changed via drag & drop. ![Image Gallery](../../../img/image_gallery.png) Populate an ImageGallery ```php setImage($img); $items[] = $advancedImage; } $news->setGallery(new \OpenDxp\Model\DataObject\Data\ImageGallery($items)); ?> ``` ### Image Advanced (supporting Hotspots/Markers/Cropping) This data type is an advanced extension to the image data type which allows defining hotspots, markers and cropping on the assigned image. ![Image Advanced Field](../../../img/classes-datatypes-image4.png) The hotspots are defined by a name and are stored as an array with the attributes name, top, left, width and height whereas the values top, left, width, height are stored as percentages of the image dimensions. ##### Get Hotspots To access the hotspots programmatically, following code snipped can be used. ```php $hotspotImage = $object->getHotspot1(); // name of the field in OpenDXP is "hotspot1" in this case (class definition) //get the assigned Asset\Image $image = $hotspotImage->getImage(); //get an array of all defined hotspots $hotspots = $hotspotImage->getHotspots(); ``` The content of `$hotspots` could look like: ``` Array ( [0] => Array ( [name] => hotspot1 [top] => 3.8922155688623 [left] => 48.076923076923 [width] => 8.3333333333333 [height] => 48.802395209581 ) [1] => Array ( [name] => hotspot2 [top] => 8.9820359281437 [left] => 70.897435897436 [width] => 14.230769230769 [height] => 44.011976047904 ) ) ``` This information can be used in the frontend to visualize the hotspots. ##### Get Markers For markers this is completely the same procedure: ```php $hotspotImage = $object->getHotspot1(); // name of the field in OpenDXP is "hotspot1" in this case (class definition) //get an array of all defined marker $marker = $hotspotImage->getMarker(); ``` The content of $marker could look like: ``` Array ( [0] => Array ( [top] => 3.8922155688623 [left] => 48.076923076923 ) [1] => Array ( [top] => 8.9820359281437 [left] => 70.897435897436 ) ) ``` ##### Get the cropped image To get the cropped image you have to use the `getThumbnail()` method: ```php $hotspotImage = $object->getHotspot1(); // name of the field in OpenDXP is "hotspot1" in this case (class definition) echo $hotspotImage->getThumbnail(); // this example returns the image cropped with the original dimensions echo $hotspotImage->getThumbnail("myCustomThumbnail"); // this example returns the cropped thumbnail according to the configuration (similar to document's $this->image()) ``` ##### Thumbnail of image Of course you can use the above code regardless if the image is cropped or not: ```php $hotspotImage->getThumbnail("myCustomThumbnail"); // $hotspotImage contains no cropping information, the thumbnail is returned as usual (see $assetImage->getThumbnail("..."); ) ``` ##### Populate the advanced image type ```php $image = Asset::getById(123); $advancedImage = new DataObject\Data\Hotspotimage(); $advancedImage->setImage($image); // ... $object->setMyAdvancedImage($advancedImage); ``` ##### Predefined Data Templates In addition to the empty standard data template you can provide a JSON config in the classdefinition describing additional custom templates. These will show up as split button entries in the "add marker/add hotspot" menu. ```json { "marker": [{ "menuName": "marker config 1", "name": "hotspot name", "data": [{ "name": "my asset href", "type": "asset", "value": "/screenshots/glossary.png" }, { "name": "my textfield", "type": "textfield" }] }], "hotspot": [{ "menuName": "hotspot config 1" }] } ``` --- ## Localized Fields Localized fields allow the definition of attributes, that should be translated into multiple languages within an object. They can be filled with selected data types and layouts - due to technical and data storage reasons not all data types are available. The advantage of this, is to make it very easy to translate fields to the configured languages. ### Definition of localized fields First of all, you have to configure your localized fields and layouts within your class. This can be easily done in the class editor. ![Add localized fields to a class](../../../img/Objects_LocalizedFields_add_data_component.png) Then add attributes, that need to be translated, into this container. ![Add data component to localized fields](../../../img/Objects_LocalizedFields_add_inputs_to_lf.png) OpenDXP generated the input widgets for every configured language. The result in your object editor will look like below: ![Localized page preview](../../../img/Objects_LocalizedFields_page_preview.png) By default, tabs are used if the number of languages does not exceed 15. This limit can be changed via the field settings in the class configurator. ![Change tabs limit in Localized Fields](../../../img/Objects_LocalizedFields_change_tabs_limit.png) ### Definition of available Languages If it's not already configured, please specify the valid languages for your website. You can do this in `Settings` -> `System Settings` -> `Localization & Internationalization` ![Add languages](../../../img/Objects_LocalizedFields_add_language.png) ### Definition of required Languages If you want to have mandatory fields in the localized fields but they are not mandatory for all languages, you can define which languages are required in `Settings` -> `System Settings` -> `Localization & Internationalization` with the `Mandatory language` checkbox on each language. ### Inheritance Fallback and inherited values are evaluated in a vertical way first. This is contrary to the [Classification Store](15_Classification_Store.md) where the evaluation is done in a horizontal way. If no value for the current language is found, the parent level is checked. If walking up the inheritance levels yields no result, the fallback language of the lowermost level will be checked in the same way. (Also walking up the inheritance levels for this language). Consider the following example and let’s assume that English is the fallback language for German. We request the German value for the object at level 3. Since the only value can be found on level 1 for the default language the tree is traversed as depicted. ![Language value levels in Localized Fields](../../../img/Objects_LocalizedFields_levels.png) ### Working with PHP API #### Getting available languages ### The following code will create an array containing the available languages for the front end (the user facing website). ```php $languages = \OpenDxp\Tool::getValidLanguages(); ``` #### Disable Fallback languages ### You can disable the Fallback languages ```php \OpenDxp\Model\DataObject\Localizedfield::setGetFallbackValues(false); ``` #### Accessing the data Accessing the data is simple as below: ```php // with global registered locale $object = DataObject::getById(234); $object->getInput1(); // will return the en_US data for the field "input1" // get specific localized data, regardless which locale is globally registered $object->getInput1("de"); // will return the German value for the field "input1" ``` #### Setting data It works in the similar way as getting the data. ```php $object = DataObject::getById(234); $object->setInput1("My Name", "fr"); // set the French value for the field "input1" ``` **Warning:** Please note that moving a field from outside (normal object field) into the localizedfield container means the loss of data from the field in all objects using this class. --- ## Number Datatypes Both numeric data types (`number` and `slider`) are stored as a number in a DOUBLE column in the database. To set numeric data, a number must be passed to the according setter. The two fields merely differ in their GUI input widgets and the fact that the slider has a min/max value and step size, which the numeric field does not have. ### Numeric ![Numeric Field](../../../img/classes-datatypes-number2.jpg) The numeric data field can be configured with a default value. In the GUI it is represented by a spinner field. ![Numeric Configuration](../../../img/classes-datatypes-number1.jpg) ### Numeric Range ![Numeric Range Field](../../../img/classes-datatypes-number7.jpg) The `numericRange` object field consists of two `numeric` fields (minimum and maximum) and so can be configured the same way. Programmatically the values are represented by a [NumericRange](https://github.com/open-dxp/opendxp/tree/11.x/models/DataObject/Data/NumericRange.php) Object. ### Slider In the GUI a slider can be used as a horizontal or vertical widget. It needs to be configured with a min and max value, the increment step and decimal precision. ![Slider Configuration](../../../img/classes-datatypes-number3.jpg) ### Quantity Value This is a numeric datatype that also allows to specify a unit. Start off with defining a global list of known units. ![Quantity Value Configuration](../../../img/classes-datatypes-number4.png) This can also be achieved programmatically. ```php $unit = new OpenDxp\Model\DataObject\QuantityValue\Unit(); $unit->setAbbreviation("km"); // mandatory $unit->setLongname("kilometers"); $unit->setGroup("dimension"); $unit->save(); ``` In the class editor, it is possible to restrict the list of valid units on a field-level. It is also possible to import and export the units as json file. For importing there is also a command: `opendxp:definition:import:units` ![Quantity Value Configuration](../../../img/classes-datatypes-number5.png) Only those units will be available then. ![Quantity Value Field](../../../img/classes-datatypes-number6.png) The following code snippet shows how to set a value. ```php use OpenDxp\Model\DataObject; $parent = DataObject::getByPath("/"); $object = new DataObject\Test(); $unit = DataObject\QuantityValue\Unit::getByAbbreviation("km"); $object->setKey("test2"); $object->setParent($parent); $object->setHeight(new DataObject\Data\QuantityValue(27, $unit->getId())); $object->save(); ``` ### Quantity Value Range ![Quantity Value Range Field](../../../img/classes-datatypes-number8.jpg) The `quantityValueRange` object field is basically the same as the `quantityValue` field, except that is has two input fields (minimum and maximum). Programmatically the values are represented by a [QuantityValueRange](https://github.com/open-dxp/opendxp/tree/11.x/models/DataObject/Data/QuantityValueRange.php) Object. #### Quantity Value Unit Conversion ##### Static unit conversion You can also convert values between units. Therefore you have to define base units, conversion factors and offsets. All units with the same base unit can be converted to each other. Factor and offset define how to convert the current unit to the base unit. Example: You have physical length units meter (m), millimeters (mm) and inches ("). Then your quantity value unit configuration could look like: | Name | Abbreviation | Baseunit | Factor | |------------|--------------|----------|--------| | Meter | m | | | | Millimeter | mm | m | 0.001 | | Inch | " | m | 0.0254 | When you now have a quantity value field in your data objects and change the unit to a unit which has the same base unit as the unit before the value gets automatically converted. For example when you have 2 m and change the unit to "mm" then the value will automatically change to 2000. You can also trigger conversion programmatically: ```php $originalValue = new QuantityValue(3, Unit::getByAbbreviation('m')->getId()); $converter = $this->container->get(\OpenDxp\Model\DataObject\QuantityValue\UnitConversionService::class); $convertedValue = $converter->convert($originalValue, Unit::getByAbbreviation('mm')); // $convertedValue is a QuantityValue with value 3000 and unit mm ``` Alternatively you can use ```php $originalValue = new QuantityValue(3, Unit::getByAbbreviation('m')->getId()); $convertedValue = $originalValue->convertTo(Unit::getByAbbreviation('mm')); // $convertedValue is a QuantityValue with value 3000 and unit mm ``` or ```php $originalValue = new QuantityValue(3, Unit::getByAbbreviation('m')->getId()); $convertedValue = $originalValue->convertTo('mm'); // $convertedValue is a QuantityValue with value 3000 and unit mm ``` Units without base unit are expected to be a base unit itself. That is why in above example configuration meter has no base unit - but of course you can set it to meter to be more explicit. In quantity value unit configuration there is also the column "offset". This is for unit conversions where addition / subtraction is needed. For example | Name | Abbreviation | Baseunit | Factor | Offset | |--------------------|--------------|----------|--------|--------| | Degrees Celcius | °C | | 1.8 | -32 | | Degrees Fahrenheit | °F | °C | | | These conversion parameters result from the formula `°F = °C * 1.8 + 32` The formula used for conversion is: `$convertedValue = ($quantityValue->getValue() * $fromUnit->getFactor() - $fromUnit->getConversionOffset()) / $toUnit->getFactor() + $toUnit->getConversionOffset();` ##### Dynamic unit conversion When conversion factors / offsets change over time (e.g. money currencies) or you want to use an external API you have two opportunities: 1. You could periodically update the factors / offsets in quantity value unit configuration 2. You can create a converter service class If you prefer the latter you have to create a class which implements `\OpenDxp\Model\DataObject\QuantityValue\QuantityValueConverterInterface` and define a service for this class in your `services.yaml`. The service name can then be entered in quantity value unit configuration's column "Converter service" for the base unit. ### Input Quantity Value [Input Quantity Value](95_Text_Types.md) is quite similar to Quantity Value except that text values are allowed instead of the strict restriction to numeric values. --- ## Objects Bricks ### General With Objectbricks, objects can be extended without changing the class definition. This is especially useful when storing product data. Often there is a base set of attributes, which all products have. But then there are lots of attributes, which only a subset of your products have. Take the example of a car accessories dealer. Brakes have different attributes than tires, rims or navigation systems. The old-fashioned way to deal with this use case is, to define a product class which contains all possible attributes from all product types. This would work fine, but most of the attributes will be empty and the object editor would be quite unmanageable. The new way is to use Objectbricks. The product class itself has only attributes all products have. This might be attributes like name, article number, manufacturer, price, etc. In addition to that, for each product group there is an object brick. The object brick for brakes has attributes like diameter, material. The object brick for tires has dimension, type, maximum speed and so on. By creating a tire product object, the tire object brick is added and so this tire product has all the tire attributes. ![Object bricks example](../../../img/ObjectsBricks_object_example.png) To one object a number of Objectbricks can be added, but just one instance per object brick type. This is the main difference to Fieldcollections. Because only one instance per object brick can be added to an object, Objectbricks fully support inheritance on field level. Each attribute of an object brick can be overwritten in child objects. ![Object bricks inheritance example](../../../img/ObjectsBricks_inheritance_example.png) Despite this flexibility, the database model in the background stays clean and well structured. This is because the attributes of an object brick have to be defined like these of Fieldcollections. ### Definition of an Objectbrick As mentioned before, Objectbricks themselves are defined the same way as objects and Fieldcollections are and support similar data types as Fieldcollections. ![Object bricks menu](../../../img/ObjectsBricks_menu.png) To allow adding an Objectbrick to an object, two things have to be done: * In data components list (when you're creating the class) is Objectbricks data type. This data type defines, where Objectbricks can be added. A field of this data type has to be added to the object class. ![Object data component](../../../img/ObjectsBricks_data_component.png) * In the Objectbrick definition, the object class and the desired field has to be added to the allowed classes. ![Object class definition](../../../img/ObjectsBricks_class_definition.png) In the object bricks definition, you can also specify a parent class - a way is the same like for classes (you can find more details in the [Parent Class for Objects section](../../../20_Extending_OpenDxp/07_Parent_Class_for_Objects.md)). ### Working with PHP API #### Retrieving Objectbricks By saving the object class, for each Objectbrick field of this class, the own data class is created with getters for each allowed Objectbrick. In our example, this data class would looks like this. The getter `$product->getBricks()` returns an instance of this class filled with the Objectbricks of the `$product`. By calling the getter, the Objectbrick class with its attribute getter is returned. ```php //receiving data of a Objectbrick $product = DataObject\Product::getById(4); $tiretype = $product->getBricks()->getTire()->getTiretype(); ``` Setting data works the same way as retrieving data. For all getters there are corresponding setters. By saving an object, all bricks are saved too. ```php //setting data of a Objectbrick $product = DataObject\Product::getById(4); $product->getBricks()->getTire()->setTiretype("Winter"); $product->save(); ``` ```php //adding a new Objectbrick to an object $product = new DataObject\Product(); $product->setKey("testproduct"); $product->setParent(DataObject\Product::getById(4)); $product->setName("testproduct"); $tireBrick = new DataObject\Objectbrick\Data\Tire($product); $tireBrick->setTiretype("allyear"); $product->getBricks()->setTire($tireBrick); $product->save(); ``` #### Deleting ObjectBricks via code ```php //remove all ObjectBricks from an ObjectBrick field $product->getBricks()->delete($product); $product->save(); ``` ```php $productBricks = $product->getBricks(); $tireBrick = $productBricks->getTire(); if ($tireBrick) { $tireBrick->setDoDelete(true); } $product->save(); ``` #### Querying for Objectbrick data Data of Objectbricks can be queried in the same way as data of fieldcollections. The Objectbricks have to be added to the `DataObject\Listing` object and then the Objectbrick data can be queried in the condition like in the sample below. ```php //querying for Objectbrick data $productList = DataObject\Product::getList([ /* add here all Objectbricks you need in the condition */ "objectbricks" => ["Tire","Brake"], /* in the condition access Objectbrick attributes with OBJECTBRICKNAME.ATTRIBUTENAME */ "condition" => "Tire.dimension > 200" ]); ``` If you want to obtain a list of objects which have a specific Objectbrick you can query for the `fieldname` value in the condition statement. ```php //return all Products that have the Objectbrick "Tire" $productList = DataObject\Product::getList([ /* add here all Objectbricks you need in the condition */ "objectbricks" => ["Tire"], /* in the condition access Objectbrick attributes with OBJECTBRICKNAME.ATTRIBUTENAME */ "condition" => "Tire.fieldname != ''" ]); ``` --- ## Other Datatypes ### Checkbox ![Checkbox](../../../img/classes-datatypes-checkbox.png) A checkbox field can be configured to be checked by default when a new object is created. It is stored in a TINYINT column in the database with the value 0 or 1. In order to set a checkbox value, a bool value needs to be passed to the according setter of the object: ```php $object->setCheckbox(true); ``` If inheritance is activated in the corresponding DataObject class, a trashcan icon is displayed next to the checkbox. This can be used to reset the value of the checkbox in order to guarantee inheritance from parents again. ### Boolean Select A `Boolean Select` is kind of a tri-state checkbox which is rendered as a select datatype in the admin UI. The background is that a checkbox can only have two states. This is especially important when it comes to inheritance. A checkbox treats an empty (never set) value just like the unchecked value. The consequence is then as soon as a parent sets it `checked` you can not reset it to `unchecked` in the child nodes anymore. The boolean select takes care of this problem by introducing a third state. The storage values are -1 (for unchecked), 1 (for checked and null for empty. For the admin UI you can specify the display values according to your needs. Default values are `yes`, `no` and `empty`. ![Boolean Select](../../../img/boolean_select.png) ### Link ![Link Field](../../../img/classes-datatypes-link1.jpg) In the UI a link is displayed as text. Its details can be edited by clicking on the button next to the link text. In the object class definition there are no special configurations available for an object field link. The link object field has its own data class which is `OpenDxp\Model\DataObject\Data\Link`. In order to set a link programmatically an `OpenDxp\Model\DataObject\Data\Link` object needs to be instantiated and passed to the setter: ```php $l = new DataObject\Data\Link(); $l->setPath("http://www.opendxp.io"); $l->setText("opendxp.io"); $l->setTitle("Visit opendxp.io"); $object->setLink($l); ``` In the database the link is stored in a TEXT column which holds the serialized data of an `OpenDxp\Model\DataObject\Data\Link`. In a template, `getHtml()` renders the link as an `` tag: ```twig
    • {{ object.myLink.html|raw }}
    ``` `getHtml()` escapes the URL and every attribute. The free attributes of a link keep every attribute except an event handler, such as `onclick`. A link without a URL renders nothing. So does a URL that runs a script, such as `javascript:`. ##### Link Generators Please also see the section about [Link Generators](../05_Class_Settings/30_Link_Generator.md) ### RGBA Color Allows to store RGBA Values. RGB and Alpha values are stored as hex values in two separate columns as hex values in the database. ![Color Picker](../../../img/rgba_color_picker.png) API Examples: ```php $o = \OpenDxp\Model\DataObject\User::getById(50); // get the color, can be null! $color = $o->getMyColor(); // get the RGB part as hex with leading # var_dump($color->getHex()); // get the RGBA value (with alpha component) has without leading hash var_dump($color->getHex(true, false)); // get the RGBA value as array (R,G,B 0-255, Alpha 0-1) var_dump($color->getCssRgba(true, true)); // set the RGBA value $color->setRgba(0, 0, 255, 64); ``` ### Encrypted Field Offers data encryption for certain data types. ![Encrypted Field](../../../img/encrypted_field.png) > Prerequisites: generate a secret key by calling vendor/bin/generate-defuse-key and add it to config/config.yaml Example: ``` opendxp: encryption: secret: def00000fc1e34a17a03e2ef85329325b0736a5941633f8062f6b0a1a20f416751af119256bea0abf83ac33ef656b3fff087e1ce71fa6b8810d7f854fe2781f3fe4507f6 ``` Key generation: ![Generate Key](../../../img/generate_defuse_key.png) ##### Strict Mode In strict mode (which is the default) an exception is thrown if existing data cannot be decrypted (e.g. because of a key change). You can switch this off by calling ```php OpenDxp\Model\DataObject\ClassDefinition\Data\EncryptedField::setStrictMode(false) ``` ### URL Slug A slug is the part of a URL which identifies a particular page on a website in an easy to read form. In other words, it’s the part of the URL that explains the page’s content. For example, if the URL is `https://opendxp.io/slug`, then the slug simply is `/slug`. ![URL Slug](../../../img/classes-datatypes-urlslug.png) > Note that currently URL slugs are not supported inside [Blocks](./05_Blocks.md) & [Classification Stores](./15_Classification_Store.md). This data-type can be used to manage custom URL slugs for data objects, you can add as many fields of this type to a class as you want. OpenDXP then cares automatically about the routing and calls the configured controller/action if a slug matches. You could use the [Symfony String component's slugger](https://symfony.com/doc/current/components/string.html#slugger) to generate the slugs. > Note that slugs can't contain the following chars: `? #` since they are reserved characters. > For more information check the [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-2.2). #### Example ```php $object ]; } } ``` #### Slug Generator A slug generator builds the prefix in front of a slug and formats what an editor types. Enter its class in the field setting "Slug Generator Service/Class". A public service is entered with an `@` in front of its name. The generator implements `OpenDxp\Model\DataObject\ClassDefinition\UrlSlugGeneratorInterface`: ```php language === 'de' ? '/de/produkte' : '/en/products'; } public function formatSlug(string $text, UrlSlugContext $context): string { return (new AsciiSlugger()) ->slug($text, '-', $context->language) ->lower() ->toString(); } public function getDefaultSlug(UrlSlugContext $context): ?string { return $context->object->getName($context->language); } } ``` The context holds the object, the field definition, the language and the site. The language is `null` outside of localized fields. The site is `null` for the fallback slug. The object editor shows the prefix in front of the input, and the editor only writes the part behind it. When the editor leaves the input, the generator formats the text. A prefix of `null` means that the slug has no prefix, and the editor writes the whole path. ![URL Slug with a slug generator](../../../img/classes-datatypes-urlslug-generator.png) The prefix is part of the stored slug. A slug keeps its path when the prefix changes later. The object editor then shows the whole stored path. Unlocking such a slug gives it the current prefix. A stored slug is locked in the object editor, because it is a public URL. The lock icon unlocks it, and a second click brings the stored slug back. When the generator throws an exception, the object editor still opens and shows the message at the slug field. ##### Fill an Empty Slug With this setting, an empty slug gets the text of `getDefaultSlug()`, formatted and behind the prefix. This holds for the fallback slug and for the slug of a site, which gets the prefix of its site. It happens on every save of the object, also in imports and through the PHP API. A slug with a value never changes. A site whose prefix differs from the prefix of the fallback slug needs a slug of its own. The object editor shows a row for such a site, and saving fills it. ##### Extend Duplicate Slugs A slug must be unique on its site. Without this setting, the object is not saved when another object uses the slug. With it, the slug gets `-1`, `-2` and so on appended. ##### Available Sites The field setting "Available Sites" limits the sites an editor can add a slug for. A listener of `UrlSlugEvents::AVAILABLE_SITES` narrows them further for each language, or takes a language out of the field. A language without a slug shows a note in the object editor, and its empty fallback slug is not filled. The router asks the same listener. A stored slug of a language that is not available on the requested site is not found. ```php use OpenDxp\Event\Model\DataObject\ClassDefinition\UrlSlugAvailableSitesEvent; public function onAvailableSites(UrlSlugAvailableSitesEvent $event): void { if ($event->getLanguage() === 'fr') { $event->setLanguageAvailable(false); } } ``` --- ## Relational Datatypes ### Many-To-One, Many-To-Many and Many-To-Many Object Relation Data Fields Many-To-One, Many-To-Many and Many-To-Many Objects are pure relation data types, which means they represent a relation to an other OpenDXP element (document, asset, object). The Many-To-One and Many-To-Many data types can store relations to any other OpenDXP element. In the object field definition there is the possibility to configure which types and subtypes of elements are allowed. The Many-To-Many Object field allows relations to one or more data objects, but no other elements. Therefore the restriction settings for objects are limited to object classes. The width and height of the input widget can be configured in the object class settings. For a Many-To-One relation only the width can be configured, since it is represented by a single drop area. Lazy Loading is explained further below in the section about relations and lazy loading. The input widgets for all three relation data types are represented by drop areas, which allow to drag and drop elements from the tree on the left to the drop target in the object layout. In addition to the drag and drop feature, elements can be searched and selected directly from the input widget. In case of objects it is even possible to create a new object and select it for the objects widget. ![Relation Fields](../../../img/classes-datatypes-relation2.png) ##### Filtering for relations via PHP API These pure relation types are stored in a separate database table called `object_relations_ID`. In the according `object_~ID~` database view, which is used for querying data, the relations fields are summarized as a comma separated list of IDs of related elements. Therefore, if one needs to create an object list with a filter condition on a relation column this can be achieved as follows: ```php $relationId = 162; $list = new \OpenDxp\Model\DataObject\Example\Listing(); $list->setCondition("mySingleRelation__id = ".$relationId); $objects=$list->load(); $relationId = 345; $list = new \OpenDxp\Model\DataObject\Example\Listing(); $list->setCondition("myManyToManyRelations like '%,object|".$relationId.",%'"); $objects=$list->load(); ``` ##### Assigning relations via PHP API In order to set a Many-To-One data field, a single OpenDXP element needs to be passed to the setter. With Many-To-Many and Many-To-Many Objects, an array of elements is passed to the setter: ```php use OpenDxp\Model\DataObject; use OpenDxp\Model\Document; use OpenDxp\Model\Asset; $object = DataObject::getById(12345); $object->setMyManyToOneField(Document::getById(23)); $object->setMyManyToManyField([ Asset::getById(350), DataObject::getByPath("/products/testproduct") ]); $object->setMyManyToManyObjectField([ DataObject\Product::getById(98), DataObject\Product::getById(99) ]); $object->save(); ``` ##### Deleting relations via PHP API In order to remove all elements from this object's Many-To-Many field, the setter can be called with null or an array: ```php $object->setMyManyToManyField([]); //that would have the same result $object->setMyManyToManyField(null); ``` Internally the setter sets the value to an empty array, regardless if an empty array or null is passed to it. ##### Unpublished relations Related items that are unpublished are normally not returned. You can disable this behavior like this: ```php //also include unpublished relations form now on DataObject::setHideUnpublished(false); //get a related object that is either published or unpublished $relationObject = $relation->getObject(); //return to normal behavior DataObject::setHideUnpublished(true); ``` ### Allow inline download of asset You can enable inline download of assets from relations if you check the "Allow inline download" checkbox. If the relation is an asset, it will be directly downloaded. If the relation is a folder, a zip file will be downloaded. ### Disable clear complete relation If you want to disable the possibility to clear the whole relation, you can uncheck the checkbox "Allow to clear all relations of this field" in the classdefinition. ### Advanced Many-To-One Object Relation This data type is an extension to the Many-To-One Object data type. To each assigned object additional metadata can be saved. The type of the metadata can be text, number, selection or a boolean value. A restriction of this data type is that only one allowed class is possible. As a result of this restriction, it is possible to show data fields of the assigned objects. Which metadata columns are available and which fields of the assigned objects are shown has to be defined during the class definition. ![Advanced Many-To-One Object Relation Configuration](../../../img/classes-datatypes-relation5.png) The shown class definition results in the following object list in the object editor. The first two columns contain `id` and `title` of the assigned object. The other four columns are metadata columns and can be edited within this list. ![Advanced Many-To-One Object Relation Field](../../../img/classes-datatypes-relation6.png) All the other functionality is the same as with the normal objects data type. ##### Access objects with metadata via PHP API ```php use OpenDxp\Model\DataObject; $object = DataObject::getById(73585); //getting list of assigned objects with metadata (array of DataObject\Data\ObjectMetadata) $objects = $object->getMetadata(); //get first object of list $relation = $objects[0]; //get relation object $relationObject = $relation->getObject(); //access meta data via getters (getter = key of metadata column) $metaText = $relation->getText(); $metaNumber = $relation->getNumber(); $metaSelect = $relation->getSelect(); $metaBool = $relation->getBool(); //setting data via setter $relation->setText("MetaText2"); $relation->setNumber(5512); $object->save(); ``` ##### Save objects with metadata ```php use OpenDxp\Model\DataObject; //load your object (in this object we save the metadata objects) $object = DataObject::getById(73585); //create a empty array for your metadata objects $objectArray = []; //loop throu the objectlist (or array ...) and create object metadata foreach ($yourObjectsList as $yourObject) { //create the objectmetadata Object, "yourObject" is the referenced object $objectMetadata = new DataObject\Data\ObjectMetadata('metadata', ['text', 'number'], $yourObject); //set into the metadata field (named text) the value "Metadata" $objectMetadata->setText('Metadata'); //set into the metadata field (named Number) the value 23 $objectMetadata->setNumber(23); //add to the empty "objectArray" array $objectArray[] = $objectMetadata; } //set the metadataArray to your object $object->setMetadata($objectArray); // now save all $object->save(); ``` ### Advanced Many-To-Many Relation This datatype is similar to the `Advanced Many-To-One Object Relation` data-type in the way that additional information can be added to the relation. The main difference is that all element types (documents, assets and objects) can be added to the relation list. The element types can also be mixed. Essentially, the same rules as for the standard Many-To-Many Relation apply. The API is nearly identical. However, instead of dealing with an `ObjectMetadata` class you have to do the same stuff with `ElementMetadata`. ```php use OpenDxp\Model\DataObject; use OpenDxp\Model\Document; $referencedElement = Document::getById(123); $references = []; $elementMetadata = new DataObject\Data\ElementMetadata('metadata', ['text', 'number'], $referencedElement); //set into the metadata field (named text) the value "my lovely text" $elementMetadata->setText('my lovely text'); //set into the metadata field (named Number) the value 23 $elementMetadata->setNumber(23); $references[] = $elementMetadata; //set the metadata array to your object $object->setMetadata($references); ``` ### Lazy Loading > Note that from 6.5.0 on relations are always lazy loaded. The configuration option has been removed. Whenever an object is loaded from database or cache, all these related objects are loaded with it. Especially with Many-To-Many relations it is easy to produce a huge amount of relations, which makes the object or an object list slow in loading. As a solution to this dilemma, Many-To-Many relational data types can be classified as `lazy loading` in the class definition. ![Lazy Loading](../../../img/classes-datatypes-relation3.png) Attributes which are lazy loaded, are only loaded from the `database/cache` when their getter is called. In the example above this would mean, that the Many-To-Many relational data is only loaded when calling `$object->getMyManyToManyField();`. ### Dependencies There are several object data types which represent a relation to an other OpenDXP element. The pure relation types are * Many-To-One Relation * Many-To-Many Relation * Advanced Many-To-Many Relation * Many-To-Many Object Relation * Advanced Many-To-One Object Relation Furthermore, the following data types represent a relation, but they are not reflected in the `object_relation_..` tables, since they are by some means special and not pure relations. (One could argue that the image is, but for now it is not classified as a pure relation type) * Image * Link * Wysiwyg All of these relations produce a dependency. In other words, the dependent element is shown in both element's dependencies tab and OpenDXP issues a warning when deleting an element which has dependencies. ![Dependencies](../../../img/classes-datatypes-relation4.png) --- ## Reverse Object Relation Datatype Reverse Object Relation are the counter part to the [Many-To-Many Object Relation & Many-To-One Object Relation fields](70_Relation_Types.md). They allow to display and edit relations which are owned by a remote object. This is best explained with an example: ![Reverse Object Relation Field](../../../img/classes-datatypes-nonownerobject1.png) Let's say there is a product, which has an Many-To-Many Object Relation field called `accessories`. The straight forward way of establishing a relation is to open a product and assign it it's accessories by dragging and dropping other products into the accessories field. If you now also want to be able to go to the accessory product and define which other products this is an accessory of, you'd have to set up a Reverse Object Relation field to do that. The reverse field needs to be configured with the remote class name and the field name of the objects field in the remote class. Having done that, you can not only assign accessories to a product, but you can also define of which other products the current one is an accessory of. ![Reverse Object Relation Configuration](../../../img/classes-datatypes-nonownerobject2.png) The Reverse Object Relation field do not have a database column or any data storage at all. They are stored in the remote object and merely represent a different way of establishing data relations from within the dependent object. When an object is added to a Reverse Object Relation field, this means the object owning the relation is modified implicitly. If the owning object is open in OpenDXP as well, OpenDXP will warn you that you are about to modify an object that is already open. If the owning object is already open in the UI, it will have to be reloaded, before the new relation established by a remote object, becomes visible. ### Working with PHP API Since Reverse Object Relation are owned by the remote object, they can only be set through the remote owner. ##### Get relations via PHP API In order to get the owner objects use the getter method: ```php $ownerRelations = $object->getMyReverseObjectRelationField(); ``` --- ## Select Options Select options are predefined sets of options which may be used for (multi)select fields. The 'Name' column is optional, unless the value can't be converted to a valid PHP enum case. This applies to values starting with a number or certain symbols. A name may contain alphanumeric characters and underscores. ### Field configuration Set the options source to 'Select Options' and select one of the select options sets. ![Fieldcollection Configuration](../../../img/classes-datatypes-selectoptions-selector.png) ### Working with PHP API The configuration in the first screenshot generates the [backed enum](https://www.php.net/manual/en/language.enumerations.backed.php) below. ```php '10', self::Twenty => 'Twenty', self::Check => '√', self::C => '©', self::Multiple_Word_Value => 'Multiple Word Value', }; } } ``` #### Retrieve available option values Provided by the `EnumGetValuesTrait`. ```php TestOptions::getValues(); ``` #### Map select value to enum Provided by the `EnumTryFromNullableTrait`. ```php $value = $product->getSelectField(); $testOption = TestOptions::tryFromNullable($value); if ($testOption !== null) { $label = $testOption->getLabel(); } ``` --- ## Select Datatypes There are 7 different select widgets available. Except the Multiselect widgets, all of them are portrayed by an input field with a drop-down list of options. The database column type is VARCHAR for all select data types, TEXT for all multiselection types. The configured value (not the display value!) is stored in the database. In the case of multiselect, values are stored as a comma separated list. ![Select Field](../../../img/classes-datatypes-select1.png) For select and multiselect the options can be defined with a value and display value in the class definition: ![Select Field](../../../img/classes-datatypes-select-configure.png) It's also possible to retrieve options from difference sources. * [Select Options](./77_Select_Options.md) * [Class / Service](./30_Dynamic_Select_Types.md) Country and language have fixed option values. For the language field the options can be limited to available system languages. The country and language select field are also available as multi select fields. The user field has fixed values as well. It allows to select a user from all available OpenDXP system users. Thereby a system user can be associated an object. For multiselect types there is extra configuration to set render type (list or tags) ![Select Field](../../../img/multiselect_rendertype.png) Object Editor view for List Render Type: ![Select Field](../../../img/multiselect_view_list.png) Object Editor view for Tags Render Type: ![Select Field](../../../img/multiselect_view_tags.png) #### Working with select data types via API In order to set a select field's value programmatically, the value is simply passed to the setter. To set the values of a multiselect field, an array of values is passed to the setter. ```php $object->setSelect("1"); $object->setMultiselect(["1","2"]); $object->setLanguage("en"); $object->setCountry("AU"); $object->setUser(1); $object->save(); ``` If one needs to find out what options are available for a select field. This can be done by getting the field definition as follows: ```php $fd = $object->getClass()->getFieldDefinition("multiselect"); $options = $fd->getOptions(); ``` If one needs to find out what options are available for a select field inside an ObjectBrick. This can also be done by getting the field definition of the brick as follows: ```php $fd = $brick->getDefinition()->getFieldDefinition("multiselect"); $options = $fd->getOptions(); ``` The display name values can be obtained as follows: ```php use OpenDxp\Model\DataObject; ... $o = DataObject::getById(49); // for a (single) select data field $valuesSingle = DataObject\Service::getOptionsForSelectField($o, "select"); $selectedValueSingle = $valuesSingle[$o->getSelect()]; // for a multiselect data field $multiSelectFieldValues = DataObject\Service::getOptionsForMultiSelectField($o, "multiSelectField"); $selectedValues = array_map( static fn($value) => $multiSelectFieldValues[$value], $o->getMultiSelectField() ); // For PHP >= 7.4 $selectedValues = array_map( static function($value) use ($multiSelectFieldValues) { return $multiSelectFieldValues[$value]; }, $o->getMultiSelectField() ); // For PHP <= 7.3 ``` To show the selected option's display name in a Twig template, first put the option values as a view variable inside the controller action: ```php use OpenDxp\Model\DataObject; ... $product = DataObject::getById(49); // for a select data field $colorOptions = DataObject\Service::getOptionsForSelectField($product, "color"); return $this->render('foo/bar.html.twig', ['colorOptions' => $colorOptions]); ``` Then you can use it in the Twig view: ```twig {{ colorOptions[product.color] }} ``` --- ## Structured Table ### Add Structured Table to the Class Similar to the table widget, the structured table can hold structured data. But there are a few fundamental differences: * The rows and columns are predefined and named. * The data type per column can be defined. Possible data types are text, number and boolean. * The data of a structured table can be accessed via getters and setters and is stored in a structured way in the database. You can add structured table component in a class definition: ![Add structured table component to the class](../../../img/Objects_Structured_Table_add_data_component.png) To define the table, you have to specify rows and columns headers which would be used to fill the structured table content. ![Structured table definition](../../../img/Objects_Structured_Table_definition.png) Now, you can use the table in your object, like below: ![Edit object with structured table](../../../img/Objects_Structured_Table_use.png) ### Storage of Structured tables For each row and column combination a new column in table of the structured table containing class will be stored. So it will be a clear restriction not to use this type of structuring data in case of a bigger number of data rows or columns. By using this design the maximum number of columns per table should be taken into consideration because it could be a technical restriction for it. ### Using structured table with PHP API In the code, the data of this field can be accessed as shown in the code snippets, below: ```php /** @var \OpenDxp\Model\DataObject\Data\StructuredTable $structuredData */ $structuredData = $object->getAdditionalinfo(); //Returns an associated array of row CommunityEdition with all columns $structuredData->getCommunityedition(); //Returns an associated array of row CommunityEdition with all columns $structuredData->getCommunityedition__support(); //Delivers an associated array of row CommunityEdition with all columns $structuredData->setCommunityedition__support("Forum"); //Alternative way of setting data to a structured table $data = []; $data['communityedition']['opensource'] = true; $structuredData->setData($data); ``` --- ## Table The table widget can hold structured data in the form of an array. The input widget for table data is a table with variable rows and columns as shown below. ![Table preview](../../../img/Objects_Table_preview.png) The data is stored in an array, which needs to be flattened for storage in the database. For this purpose columns are separated with a "|" and rows are distinguished with line breaks. The database field for a table is a TEXT column. For example, the data shown in the screen above would be stored as: ``` one|two|three four|five|six seven|eight|nine ``` ![Table settings](../../../img/Objects_Table_settings.png) The input widget can be preconfigured with default data or a fixed amount of rows and columns. The default amount of rows and columns, as well as the default data, can be changed later when the data is entered. It's possible to prevent adding/removing additional rows/columns by setting the "Rows fixed"/"Cols fixed" checkbox. If this is set to fixed the add and delete button for rows and columns will disappear. In order to set table data programmatically, an array needs to be passed to the setter as shown in the code snippet below: ```php $object->setTable([ ["one", "two", "three"], ["four", "five", "six"], ["seven", "eight", "nine"] ]); ``` ### Using copy and paste feature in an object using table data type A copy and paste feature is available to be able to fill easily the table in an object from an Excel sheet for instance: ![Copy and paste feature](../../../img/Objects_Table_copyandpaste.png) It is possible to copy directly data in the OS clipboard from Excel: ![Copy and paste feature](../../../img/Objects_Table_excel.png) And after pasting data will be formatted keeping Excel structure: ![Copy and paste feature](../../../img/Objects_Table_copyandpasteresult.png) You can paste any data (from text files, etc.), separator must be tabulation. --- ## Text Datatypes ### Input ![Input Field](../../../img/classes-datatypes-text1.jpg) The input field is a simple text input field. It's data is stored in a VARCHAR column in the database. The display width and database column length can be configured in the object class definition. ![Input Configuration](../../../img/classes-datatypes-text2.jpg) To set the value of an input field, the string value needs to be passed to the setter. ```php $object->setInput("Some Text"); $object->save(); ``` ### Password ![Password Field](../../../img/classes-datatypes-text3.jpg) The password field is basically the same as the input field with hidden input characters. It's column length can not be changed, since passwords are always hashed using the selected algorithm. If a string appears to already be hashed, either by detection by [password_get_info()](https://www.php.net/manual/en/function.password-get-info.php) or if it matches any common hash patterns below, then it will not be hashed again. - Hexadecimal string - with legth of 32, 40, 48, 56, 64, 96, or 128 characters These rules will detect the following hashes: - MD2, MD4, MD5, RIPEMD-128, Snefru 128, Tiger/128, HAVAL128 - SHA-1, HAS-160, RIPEMD-160, Tiger/160, HAVAL160 - Tiger/192, HAVAL192 - SHA-224, HAVAL224 - SHA-256, BLAKE-256, GOST, GOST CryptoPro, HAVAL256, RIPEMD-256, Snefru 256 - SHA-384 - SHA-512, BLAKE-512, SWIFFT We recommend using `password_hash` as algorithm, any other algorithm is deprecated since OpenDXP 1.2 and will be removed in OpenDXP 2.0. ![Password Configuration](../../../img/classes-datatypes-text4.jpg) ### Textarea ![Textarea Field](../../../img/classes-datatypes-text5.jpg) The textarea is an input widget for unformatted plain text. It is stored in a TEXT column in the database. Setting it's value works the same as for the input field. The width and height of the input widget can be configured in the object field definition. ### WYSIWYG The WYSIWYG (What You See Is What You Get) input field is identical with the textarea field except for the fact that it's input widget allows formatting of text and can even hold images and links (references to assets and documents). If images and documents are used in a WYSIWYG widget, they create a dependency for the current object. To insert an image, assets can be dragged to a WYSIWYG widget. In order to create a link, a document needs to be dragged and dropped on selected text in the WYSIWYG widget. The text is stored as HTML. ![WYSIWYG Field](../../../img/classes-datatypes-text6.jpg) ### Input Quantity Value Quite similar to [Quantity Value](55_Number_Types.md) except that text values are allowed instead of the strict restriction to numeric values. --- ## Video Datatype ![Video Field](../../../img/classes-datatypes-video.png) ### Working with PHP API ```php getMyVideo()); ?> ``` Will produce the following output depending on the content: ```php # ASSET VIDEO OpenDxp\Model\DataObject\Data\Video Object ( [type] => asset [data] => OpenDxp\Model\Asset\Video Object ( [type] => video [id] => 27 ... ) [poster] => OpenDxp\Model\Asset\Image Object ( [type] => image [id] => 284 ... ) [title] => My Title [description] => My Description ) # YouTube Video OpenDxp\Model\DataObject\Data\Video Object ( [type] => youtube [data] => pAE_ff8tV-g [poster] => [title] => My Title [description] => My Description ) # Vimeo Video OpenDxp\Model\DataObject\Data\Video Object ( [type] => vimeo [data] => 11696823 [poster] => [title] => My Title [description] => My Description ) ``` #### Display Video using document's video tag ```php getMyVideo(); $videoData = $v->getData(); if($videoData) { $video = new \OpenDxp\Model\Document\Editable\Video(); $video->setConfig([ "thumbnail" => "myVideoThumb", // specify your thumbnail here - IMPORTANT! "width" => "100%", "height" => 480, "attributes" => ["class" => "video-js custom-class", "preload" => "auto", "controls" => "", "data-custom-attr" => "my-test"] ]); $video->setType($v->getType()); $video->setTitle($v->getTitle()); $video->setDescription($v->getDescription()); $video->setId(($videoData instanceof Asset) ? $videoData->getId() : $videoData); if($v->getPoster()) { $video->setPoster($v->getPoster()->getId()); } echo $video->frontend(); } ``` #### Setting data to the video data type ```php setData($assetVideo); $videoData->setType("asset"); $videoData->setPoster($assetImage); $videoData->setTitle("My Title"); $videoData->setDescription("My Description"); $object->setMyVideo($videoData); $object->save(); ``` --- ## Object Data Types The entire list of data types is indicated below: #### [Text Datatypes](./95_Text_Types.md) | Name | Description | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | input | text input field | | textarea | textarea | | wysiwyg | text area with formatting options through a WYSIWYG editor | | password | password field | #### [Number Datatypes](./55_Number_Types.md) | Name | Description | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | numeric | spinner field for number input | | slider | number input with slider widget (min - max slider) | | quantity value | number input with an additional unit. available units can be configured centrally. | #### [Date Datatypes](./25_Date_Types.md) | Name | Description | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | date | calendar date selector | | date & time | calendar date selector + combo box for time | | time | combo box for time | #### [Select Datatypes](./80_Select_Types.md) | Name | Description | |--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | select | combo box | | user | combo box to select from all existing OpenDXP users (available since build 716) In the user settings the object dependencies of each user are shown in the second tab panel.All objects which reference the selected user are listed in a grid view.If one needs to find out which objects hold a reference to a specific user, the `OpenDxp\\Tool\\Admin::getObjectsReferencingUser($userId)` method can be used to find all referencing objects. | | country | combo box with predefined country list | | language | combo box with predefined language list | | multiselect | combo box with multiple select | | countries | combo box with multiple select and predefined country list | | languages | combo box with multiple select and combo box with multiple select and predefined language | #### [Select Options](./77_Select_Options.md) | Name | Description | |----------------|------------------------------------------------| | select options | Manage select options for (multi)select fields | #### [Dynamic Select Datatypes](./30_Dynamic_Select_Types.md) | Name | Description | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | dynamic select | combo box | #### [Relational Datatypes](./70_Relation_Types.md) | Name | Description | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Many-To-One Relation | reference to a OpenDXP document, object or asset | | Many-To-Many Relation | collection of references to OpenDXP documents, objects, assets | | Advanced Many-To-Many Relation | collection of references to OpenDXP documents, objects, assets with additional metadata on the relation | | Many-To-Many Object Relation | collection of OpenDXP object references | | Advanced Many-To-One Object Relation | collection of OpenDXP object references with additional metadata on the relation | | [Reverse Object Relation](75_Reverse_Object_Relation_Type.md) | collection of OpenDXP object references which are owned by a different object | #### Structured Datatypes | Name | Description | |-----------------------------------------------------|-------------------------------------------------------------------| | [block](./05_Blocks.md) | repeatable block of attributes within an object | | [classificationstore](./15_Classification_Store.md) | advanced store for classification systems like ETIM, ecl@ss, etc. | | [table](./90_Table.md) | table input | | [structuredtable](./85_Structured_Table.md) | table with predefined rows and columns | | [fieldcollections](./35_Fieldcollections.md) | A collection of fields that can be added to the object | | [objectbricks](./60_Object_Bricks.md) | Bricks of attributes, that can be added to objects | | [localizedfields](./50_Localized_Fields.md) | Set of attributes that can be translated | #### [Geographic Datatypes](./40_Geographic_Types.md) | Name | Description | |--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | geopoint | maps widget to find longitude/latitude | | geobounds | maps widget to define geographical bounds | | geopolygon | maps widget to define a geographical area | | geopolyline | maps widget to define a geographical path | #### Other Datatypes | Name | Description | |----------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------| | [image](./45_Image_Types.md) | drop area & preview for a OpenDXP image asset | | [externalimage](./45_Image_Types.md) | relation to an image that is not stored in OpenDXP | | [imageadvanced](./45_Image_Types.md#image-advanced-supporting-hotspotsmarkerscropping) | drop area & preview for a OpenDXP image asset with additional features for markers, hotspots, cropping | | [imagegallery](./45_Image_Types.md) | collection of `Image Advanced` images | | [video](./98_Video_Type.md) | drop area & preview for a OpenDXP video asset | | [checkbox](./65_Others.md#checkbox) | checkbox | | [link](./65_Others.md#link) | link selector with link target | | [calculatedvalue](./10_Calculated_Value_Type.md) | datatype for calculated values - calculation can be defined with a PHP class | #### CRM Datatypes | Name | Description | |---------------------------|---------------------------------------------------------------------------------------| | firstname | typed input field for firstname | | lastname | typed input field for lastname | | email | typed input field for email including validation | | gender | typed and prefilled select for gender | | persona | typed selectbox for personas defined within OpenDXP | | personas | typed selectbox with multiselect for personas defined within OpenDXP | | [consent](./20_Consent.md) | store consent of user for something, e.g. consent for direct marketing mailing | The following datatypes are only available if the OpenDxpNewsletterBundle is enabled and installed: | Name | Description | |---------------------------|---------------------------------------------------------------------------------------| | newsletteractive | typed checkbox if newsletter is active | | newsletterconfirmed | typed checkbox if newsletter is confirmed | #### General Aspects All data types are wrapped in an object derived from `OpenDxp\Model\DataObject\ClassDefinition\Data`. These data type objects provide getters and setters and they define the Description in the frontend. Data type objects are displayed in the first column of the table above. The second column indicates the underlying data type class and the third column outlines the Description used in OpenDXP to fill in, edit and display data objects. Besides the `name`, which is the name of the object's property and the `title`, which is shown in the GUI, an object field has the general configuration options listed below. The title can be translated for different system languages. Please see the article about Translations to find out how to add object field translations. * `mandatory`: Makes the field mandatory and does not allow saving the object when it is empty * `not editable`: Does not allow a change of this field's value in OpenDXP backend (data change can only be done programmatically) * `invisible`: The field is not visible in OpenDXP * `visible in grid view`: Determines if the field's data column is shown in the object grid view, or hidden (meaning it has to be activated manually) * `visible in search result`: Determines if the field's data column is shown in the search results grid, or hidden (meaning it has to be activated manually) * `indexed`: puts an index on this column in the database * `unique`: If checked, the value has to be unique across all objects of this class. Note that only works on top level attributes and not on nested stuff inside localized fields etc. Beware that this does not add a database index to the query table which `Listing` classes use. * Moreover, each data field can have a `tooltip`, which is shown when the mouse hovers over the input field. ![Data Field Settings](../../../img/classes-datatypes1.jpg) ![Data Field Settings](../../../img/classes-datatypes2.jpg) The `layout settings` allow to apply custom CSS to any object field. ![Data Field Settings](../../../img/classes-datatypes3.jpg) > **WARNING** > Please note that renaming a field means the loss of data from the field in all objects using this class. See sub-pages of this page for detail documentation of different data types. #### Default values For datatypes which support default values (currently these are Input, Date, Datetime, Numeric, Checkbox, Select and Quantity Value) you can either specify a fixed default value or you can specify a default value generator service or class which can generate a dynamic default value. The data is persisted according to the following rules. 1. ***No [inheritance](../05_Class_Settings/25_Inheritance.md)***: default value is persisted to store/query table on create 2. ***With inheritance and NO parent value***: default value is persisted to store/query table on create 3. ***With inheritance and existing parent value***: no value is persisted to store table, inherited value is persisted to query table, inheritance is active A default value generator is a class which implements `\OpenDxp\Model\DataObject\ClassDefinition\DefaultValueGeneratorInterface`. This class can generate a value based on the current data of an object. Have a look at [Calculated Value](./10_Calculated_Value_Type.md) for an overview of contextual information. If a default value generator is defined then it has a higher priority than a configured static default value. The decisions are made in the following order: 1. default value generator. if defined the process stops here 2. parent value if inheritance is enabled 3. fixed default value --- ## Dynamic Text Labels Similar to the [CalculatedValue](../../../05_Objects/01_Object_Classes/01_Data_Types/10_Calculated_Value_Type.md) data type, it is possible to generate the Layout Text dynamically based on the current object and the label's context. There are two options for defining dynamic content: - Providing a custom renderer class - Using twig in template This is an alternative to the static text defined in the class definition. For all ways, the preview tab shows a preview of the generated content. If you are using object context in your content, then just drag & drop object on "Drag Object for Preview" field before checking the output in preview tab. ### Custom Renderer Class Let's consider the following example. It states that we want to use a custom renderer service which implements `DynamicTextLabelInterface` and in turn returns dynamic text string from `renderLayoutText` method. We also want to pass some additional data (*some additional data :)* in this example) to the rendering method. ![Class Definition](../../../img/dynamic_textlabel_1.png) Here is an example for a rendering class. ```php Last reload: ' . date(DateFormat::ISO_8601) . '' . '

    Additional Data: ' . $data . '

    '; if ($object) { $text .= '

    BTW, my fullpath is: ' . $object->getFullPath() . ' and my ID is ' . $object->getId() . '

    '; } return $text; } } ``` *$data* will contain the additional data from the class definition. In *$params* you will find additional information about the current context. For example: If the text label lives inside a field collection, *$params* will contain the name of the field collection (and of course the name of the label itself). The result will be as follows: ![Editmode](../../../img/dynamic_textlabel_2.png) ### Twig & Preview It is possible to use Twig syntax inside htmleditor (Source Edit) and Renderer class. You can also check the generated output in preview tab. Following variables are available in twig context: - `object` - current data object - `data` - data provided to renderer defined in the class defintion Here is an example of Twig content in htmleditor source edit mode: ![Template Class Definition](../../../img/dynamic_textlabel_3.png) ![Template editmode](../../../img/dynamic_textlabel_4.png) #### Sandbox Restrictions Dynamic Text renders user controlled twig templates in a sandbox with a restrictive security policy. The policy allows the tag `set` and the filters `escape`, `trans` and `default`. It allows the functions `path`, `asset`, `opendxp_asset`, `opendxp_asset_by_path`, `opendxp_document`, `opendxp_document_by_path`, `opendxp_object`, `opendxp_object_by_path`, `opendxp_url` and `opendxp_website_config`. A function belongs on this list only if it reads and changes nothing. It returns a plain value or an object of a readable class. It does not depend on the current request. A template reads objects and does not change them. It may read an object of a readable class through its getters, its `is` and `has` methods, `__toString()` and its properties. Elements, their notes, the values of their fields, quantity value units, asset thumbnails and dates are readable. A date may also call `format()`. Every other method is refused. A template reads a field by its getter or its name, never through `get()` or `getValueForFieldName()`. The file of an asset and the value of a password field are never readable. So `{{ object.name }}`, `{{ object.getName() }}` and `{{ object.date.format("Y") }}` work, but `{{ object.save() }}` and `{{ container.get("database_connection") }}` do not. The text sees the object, the field name, the layout and the Twig globals. The globals `app` and `container` are objects of classes that are not readable. Please use the following configuration to allow more in template rendering: ```yaml opendxp: templating_engine: twig: sandbox_security_policy: tags: ['if'] filters: ['upper'] functions: ['include', 'path'] methods: App\Model\Price: ['format'] readable_classes: - App\Model\Cart ``` `methods` allows single methods of a class. `readable_classes` makes every object of a class readable. The configuration adds to the defaults and never replaces them. --- ## Preview / Iframe Panel Provide a URL and make use of the context paramater to render a response of your choice. ### Class Configuration ![Class Definition](../../../img/iframe_class_definition.png) Note that you can provide a freely selectable string that will be added to the context information. See the output of the example below. ### Sample Controller Code ```php query->getString("context"), true); $objectId = $context["objectId"]; $language = $context["language"]; // get the current editing data, not the saved one! $object = Service::getElementFromSession('object', $objectId); // If the object is opened the first time it is not in the session yet, // so we load the saved one if ($object === null) { $object = Service::getElementById('object', $objectId); } $response = '

    Title for language "' . $language . '": ' . $object->getTitle($language) . "

    "; $response .= '

    Context

    '; $response .= \OpenDxp\Helper\StringHelper::arrayToHtmlAttributeString($context); return new Response($response); } } ``` ### Object Editor ![Editor](../../../img/iframe_object_editor.png) --- ## Layout Elements To structure object data layout-wise, there are 3 panel types and 4 other layout elements available. Data fields are always contained in a panel. Panels can be nested and thereby a data input interface tailored to the users's needs can be designed. ![Layout Elements](../../../img/classes-layouts.png) The three available panel types are: * Panel - a plain panel holding fields * Region - a region panel able to hold nested panel's in its regions north, east, west and south * Tabpanel - a panel holding further nested panels as tabs Moreover, within a panel fields can be put into the following layout Components * Accordion * Fieldset * Field Container And last but not least there are two extra layout elements: * Text - to add minimally formatted text to an object layout. This can hold descriptions and hints which don't fit into a field's tooltip. Please note that since release 4.4.2 it is possible to generate this text dynamically. Please read this [page](./01_Dynamic_Text_Labels.md) for further details. * IFrame - provide a URL and make use of the context parameter to render the response of your choice. Please read this [page](./02_Preview_Iframe.md) for further details. OpenDXP uses Ext JS layout components for all object layout elements. For a deeper understanding of the layout elements, please have a look at the [Ext JS documentation pages](https://docs.sencha.com/extjs/7.0.0/classic/Ext.html) and [examples](http://www.sencha.com/products/js/). --- ## Composite Indices OpenDXP can create composite indices on `object_query_*`, `object_store_*`, `object_localized_data_*` and `object_localized_query_*` tables for you. Read [this](../../../19_Development_Tools_and_Details/05_Database_Model.md) for more information about the database model. ![Index settings](../../../img/composite_index1.png) ![Database](../../../img/composite_index2.png) --- ## Custom Icons for Objects OpenDXP allows you to define custom icons for objects. Either, icons can be the same for all objects of a class (via configuration in class) or objects depending on their data values can have different icons (see below). In addition to that, the tooltip of an object in object tree can be customized via admin style. ### Static Custom Icons for Classes Objects can be displayed in OpenDXP with custom icons. This makes objects distinguish themselves visually based on the class they are based on. In the object tree the user can see on the first sight what an object should represent. The example below shows how custom icons are assigned to a class and how they are displayed in the object tree. It is easy for the user to see immediately which objects are of the type "News". Icons that come along with OpenDXP by default can be found in `/admin/misc/icon-list` (backend session needed). ##### Icon Sizes As icons SVG graphics are recommended. If you use pixel graphics, the maximum size is 18x20 pixels. ### Dynamically define Custom Icons and Style in Object-Tree (AdminStyle) You can dynamically define custom icons based on the element. Read [Dynamic Icons](../../../18_Tools_and_Features/02_Custom_Icons.md) for details. --- ## Custom Layouts It is possible to create customized layouts based on the main definition and override the settings concerning the visual aspects of the layout and data components. It is also possible to make a field editable, although it is marked as non-editable in the main layout. Custom layouts are available for all admin users and can be made available to standard users through the workspace settings. > **Security Note** > Custom layouts are not intended to restrict access to sensitive data in high-security scenarios. To define a custom layout, open the `Custom Layout Editor` through the `Configure Custom Layouts` button in the `Classes` editor. You can define as many layouts as you want. In the left panel, you will see the main definition. In the middle is the custom layout you are currently editing. And on the right, the specific settings for the selected field. You can modify all visual aspects of the field. Other settings concerning the data aspects are locked. You can drag and drop elements from the main layout to the custom layout tree, or you can add layout components using the context menu. Note that there is no need to add all data elements from the main layout to the custom layout. You can choose just as many as you need. This does not have any impact on your data! ![Custom Layouts](../../../img/classes-custom-layouts1.png) In the `Data Objects` editor, the layout can then be chosen via the `reload` button. ![Custom Layouts](../../../img/classes-custom-layouts2.png) Admin users will notice an extra layout called `Main (Admin Mode)`, which is basically the same as the `Main` layout, except that invisible fields are shown, and non-editable fields are made editable again. This layout is available for admin users only. As mentioned above, custom layouts can be made available to standard users through the workspace settings in the user permissions. If no layout is selected for the given class, then the data will be presented using the main layout. Otherwise, the user will have the choice between the selected layouts. ![Custom Layouts](../../../img/classes-custom-layouts3.png) --- ## Custom Views A custom view is an additional custom tree representing a subset of elements of the corresponding original tree. Custom views can be configured for Documents, Assets and Objects. To create or edit perspectives and custom views within the OpenDXP backend UI use the [perspective editor](https://github.com/open-dxp/perspective-editor) bundle. > **Security Note** > Perspectives and Custom Views are not intended to be used to restrict access to data An unlimited number of custom views can be created. Specify the tree type, root node and layout settings. Note that the ID is mandatory and must be unique! For a sample configuration file have a look at the [sample configuration](21_Custom_View_Example.md). ### The Configuration File Format and location of the custom view configuration depends on your environment. Per default the symfony-config is used. If you want to change the default behaviour, have a look at the [environment](../../../21_Deployment/03_Configuration_Environments.md#configuration-storage-locations--fallbacks) configuration options. ### Advanced Features / Configurations ##### Additional object tree including condition filter The main idea for this configuration is to * add an additional object tree called `Events` having its root at `/Events` * not showing the parent folder as its root * only show events that have the "Salzburg" tag. > **Note** > Be aware: for tree pagination to work properly, there needs to be a parent node available. > If you have more than a certain amount of child nodes at your root level, you might need to set "showroot" to true because of that. ```yaml #var/config/custom-views/customviews.yaml opendxp: custom_views: definitions: 87705013-edb9-c9ec-0f5e-c3ee45ca4459: name: Events treetype: object position: right rootfolder: /Events showroot: false sort: 0 treeContextMenu: object: items: add: true addFolder: true importCsv: true cut: true copy: true paste: true delete: true rename: true reload: true publish: true unpublish: true searchAndMove: true lock: true unlock: true lockAndPropagate: true unlockAndPropagate: true changeChildrenSortBy: true classes: '' joins: [ { type: left, name: { ev: object_query_EV }, condition: 'objects.id = ev.oo_id', columns: { ev: tags } } ] id: 87705013-edb9-c9ec-0f5e-c3ee45ca4459 icon: /bundles/opendxpadmin/img/flat-color-icons/vip.svg where: '' having: 'ev.tags LIKE "%%Salzburg%%"' ``` ![Custom Views](../../../img/classes-custom-views2.png) ##### Additional asset tree hiding items based on a property * use the `/examples/panama` as the root folder * do not show the parent node * position it on the left * place it on the top and expand it * hide assets which have the "HIDE" property set to true ```yaml #var/config/custom-views/customviews.yaml opendxp: custom_views: definitions: 186632eb-5ad3-6ac6-61f8-7a75e64f2204: name: 'Panama Impressions' treetype: asset position: left rootfolder: /examples/panama showroot: false sort: -4 treeContextMenu: asset: items: add: hidden: false items: upload: true uploadCompatibility: true uploadZip: true addFolder: true rename: true copy: true cut: true paste: true pasteCut: true delete: true searchAndMove: true lock: true unlock: true lockAndPropagate: true unlockAndPropagate: true reload: true joins: [ { type: left, name: { meta: properties }, condition: "(meta.cid = assets.id AND meta.ctype = 'asset' AND name = 'HIDE')", columns: { hide: data } } ] icon: /bundles/opendxpadmin/img/flat-color-icons/camera_identification.svg where: '' having: 'type = "folder" OR hide is NULL or hide != 1' ``` ![Custom Views](../../../img/classes-custom-views3.png) ##### Document tree filtering using the where clause The intention is to * show the `/en/Magazine` (including the parent node on the right side) * apply a simple filter which allows us to only show * folders * links * pages which do not have the character 'g' in their key ```yaml #var/config/custom-views/customviews.yaml opendxp: custom_views: definitions: c3da6659-c8b3-f3ed-2eda-70b2d3756730: name: Magazine treetype: document position: right rootfolder: /en/Magazine showroot: true sort: -12 treeContextMenu: document: items: add: true addSnippet: true addLink: true addEmail: true addHardlink: true addFolder: true paste: true pasteCut: true copy: true cut: true rename: true unpublish: true publish: true delete: true open: true convert: true searchAndMove: true useAsSite: true editSite: true removeSite: true lock: true unlock: true lockAndPropagate: true unlockAndPropagate: true reload: true icon: /bundles/opendxpadmin/img/flat-color-icons/reading.svg where: "(type = 'folder' OR (type = 'page' and `key` NOT LIKE '%%g%%' OR type = 'link'))" ``` ### Customizing the Tree Context Menu Allows you to hide certain context menu items via the customview's treeContextMenu configuration option. ```yaml #var/config/custom-views/customviews.yaml opendxp: custom_views: definitions: 186632eb-5ad3-6ac6-61f8-7a75e64f2204: # ... treeContextMenu: asset: items: add: hidden: false items: upload: true uploadCompatibility: true uploadZip: true addFolder: false rename: true copy: false #deny copy cut: false #deny cut paste: true pasteCut: true delete: true searchAndMove: true lock: false #deny lock unlock: true lockAndPropagate: true unlockAndPropagate: true reload: true # ... ``` ![Custom Views](../../../img/classes-custom-views5.png) There are keys for most of the menu items, including sub menu items. The notion is like indicated in the example configuration. Let's assume that we want to hide the "copy" option. The short way is this one: ```yaml copy: false #the default is that all menu entries are visible ``` ```yaml copy: hidden: true ``` --- ## Custom View Example Configuration ```yaml #var/config/custom-views/87705013-edb9-c9ec-0f5e-c3ee45ca4459.yaml opendxp: custom_views: definitions: 87705013-edb9-c9ec-0f5e-c3ee45ca4459: name: Events treetype: object position: left rootfolder: /Events showroot: false sort: 0 treeContextMenu: object: items: add: true addFolder: true importCsv: true cut: true copy: true paste: true delete: true rename: true reload: true publish: true unpublish: true searchAndMove: true lock: true unlock: true lockAndPropagate: true unlockAndPropagate: true changeChildrenSortBy: true classes: '' joins: [ { type: left, name: { ev: object_query_EV }, condition: 'objects.id = ev.oo_id', columns: { ev: tags } } ] id: 87705013-edb9-c9ec-0f5e-c3ee45ca4459 icon: /bundles/opendxpadmin/img/flat-color-icons/vip.svg where: '' having: 'ev.tags LIKE "%%Salzburg%%"' ``` --- ## Data Inheritance and Parent Class OpenDXP provides two sorts of inheritance. While data inheritance allows the inheritance of object data along the tree hierarchy of objects, the developer can modify the PHP class hierarchy with the parent class setting of object classes. ### Data Inheritance A very important feature in connection with PIM is data inheritance. Data inheritance means, that objects of the same class can inherit data from their parent objects in the object tree. One use case is the storage of product data. Imagine, you have a group of products which have many attributes in common and differ in just a few attributes (for example size, color, ...). So you can create a parent product which stores all the common attributes. Then you add child products and specify attributes in which the products differ (size, color, ...). All other attributes they inherit from the common parent product. Data inheritance has to be enabled in the class definition like in the screen below: ![Data Inheritance](../../../img/classes-data-inheritance.png) If data inheritance is enabled and an attribute of an object is empty, OpenDXP tries to get this attribute from a parent object. This works only, if the parent object has the same class as the child object. Data inheritance between different classes is not supported. In the OpenDXP backend, inherited values are visualized as in the screen below: they are grey and a bit transparent, and have a green marker in the upper left corner. With a click on this corner, one can open the source object of this specific attribute. > **Important Note regarding changing the inheritance flag** > If you toggle the inheritance flag after creating objects, the *object_*_*\_query_* might contain > wrong values even after saving the object again. OpenDXP will disable the dirty detection > if the class is newer than the object which should fix this issue. > However, you can still call DataObject::disableDirtyDetection() before saving the object > if you want to explicitely fix that. > **Default Values > Make sure that you understand the impacts of defining a default value which is described > [here](../01_Data_Types/README.md) ![Data Inheritance](../../../img/classes-data-inheritance1.png) ![Data Inheritance](../../../img/classes-data-inheritance2.png) ![Data Inheritance](../../../img/classes-data-inheritance3.png) To get the inherited values in the backend via code, you have to use the getter-methods of the attributes. By accessing the attributes directly, you will not get the inherited values. > **Bear in mind** > The complex data type field collections does not support inheritance. Getting values from an object without inheritance ```php // Set the first argument to false so as not to inherit any values DataObject\Service::userInheritedValues(false, function() { // ... your code goes here // ... // ... }); ``` ### Parent Class - Class Inheritance OpenDXP data objects support inheritance, just as any PHP object does. In OpenDXP the class from which a specific data class inherits can be changed. By default, a data class inherits from `OpenDxp\Model\DataObject\Concrete`, but if required otherwise, a data class can extend a different parent class. If the parent class should be changed, this needs to be specified in the class definition as shown in the screen below: ![Parent Class](../../../img/classes-class-inheritance.png) > **Be Careful** > This is a very advanced feature and should only be used by very experienced developers who know what they are doing and > what consequences it might have when the parent class is changed from `OpenDxp\Model\DataObject\Concrete` to something else. In order to maintain all OpenDXP functionalities, it has to be ensured that the special class used in the example above extends `OpenDxp\Model\DataObject\Concrete` and that its methods don't override and clash in unexpected ways with existing methods of `OpenDxp\Model\DataObject\Concrete` or any magic functions of `OpenDxp\Model\DataObject\Concrete` or its parent classes. It is also possible to use class inheritance and traits for listing data object model. #### Hooks available when using class inheritance Currently there's only one hook available. For using a hook you need to implement a certain interface in your custom parent class. |Interface | Description | |--------------------------|--------------| |`PreGetValueHookInterface`| Makes it possible to modify data before returning it to the caller. Hook is called at the beginning of every getter of a field. | ###### Example: ```php namespace Website\DataObject; use \OpenDxp\Model\DataObject; class Special extends DataObject\Concrete implements DataObject\PreGetValueHookInterface { public function preGetValue(string $key): ?string { if ($key == "myCustomProperty") { return strtolower($this->myCustomProperty); } return null; } } ``` ### Overriding OpenDXP Models In addition to parent classes, it is also possible to override OpenDXP object classes with custom classes and tell OpenDXP to use the custom classes instead of the generated object classes. This can be done by using [model overrides](../../../20_Extending_OpenDxp/03_Overriding_Models.md). --- ## Using Interfaces and Traits In some cases it could be helpful to let the generated PHP class for data objects implement interfaces or add some additional functions using traits. ###### Example This example uses the demo project to show the usage of this features. We're extending the `Cars` class with methods to retrieve the transmission type as well as the amount of gears. This will be done by implementing an interface and a trait that adds the required methods. ###### Create the interface ```php *Data Objects* -> *Classes* -> *Product Data* -> *Car* Click on *General Settings* and paste your interface and trait path into `Implements interface(s)` and `Use (traits)` ![Example Screenshot](../../../img/interfaces-traits.png) Save your changes It will generate the `implements \App\Model\Product\TransmissionInterface` and the `use \App\Traits\TransmissionTrait;` lines within the DataObject Class. ```php // var/classes/DataObject/Car.php ... class Car extends \App\Model\Product\AbstractProduct implements \App\Model\Product\TransmissionInterface { use \App\Traits\TransmissionTrait; protected $classId = "CAR"; protected $className = "Car"; ... ``` --- ## Link Generator(Class_Settings) #### Summary Link Generators dynamically create web links for objects. They are automatically invoked when objects are linked in: - Document link editables - Link document types - Object link tags Additionally, Link Generators enable the preview tab for data objects. Link Generators are defined at the class level. There are two ways to specify them: - By providing the class name - By referencing a Symfony service (using a specific prefix) ![Link Generator Setup1](../../../img/linkgenerator_class.png) ```yaml services: # --------------------------------------------------------- # Link Generators for DataObjects # --------------------------------------------------------- App\Website\LinkGenerator\CategoryLinkGenerator: public: true App\Website\LinkGenerator\ProductLinkGenerator: public: true ``` #### Sample Link Generator Implementation ```php doGenerate($object, $params); } public function generateWithMockup(ProductInterface $object, array $params = []): string { return $this->doGenerate($object, $params); } protected function doGenerate(ProductInterface $object, array $params): string { return DataObject\Service::useInheritedValues(true, function () use ($object, $params) { return $this->OpenDxpUrl->__invoke( [ 'productname' => Text::toUrl($object->getOSName() ? $object->getOSName() : 'product'), 'product' => $object->getId(), 'path' => $this->getNavigationPath($object->getMainCategory(), $params['rootCategory'] ?? null), 'page' => null ], 'product-detail', true ); }); } } ``` Note: If you want to support mockups or arbitrary objects you can change the typehint to: ```php public function generate(object $object, array $params = []): string { //... } ``` The link generator will receive the referenced object and additional data depending on the context. This would be the document (if embedded in a document), the object if embedded in an object including the tag or field definition as context. Example: ```php public function generate(Concrete $object, array $params = []): string { if (isset($params['document']) && $params['document'] instanceof Document) { // param contains context information $documentPath = $params['document']->getFullPath(); } ... } ``` #### Example Document ![Link Generator Document](../../../img/linkgenerator_document.png) ```php $d = Document\Link::getById(203); echo($d->getHref()); ``` would produce the following output ``` /en/shop/Products/Cars/Sports-Cars/Jaguar-E-Type~p9 ``` #### Use in Views ##### path() / url() ```twig
    ``` ##### OpenDxpUrl ```twig ``` --- ## Locking Fields Sometimes it's useful that a field cannot be modified/deleted in the class editor. Especially if a class is created by a plugin. OpenDXP offers the possibility to lock a field programmatically, you can call the method `setLocked()` on every `OpenDxp\Model\DataObject\ClassDefinition\Data` object. #### Example The following example will lock every field inside the class with the ID 7. ```php $class = DataObject\ClassDefinition::getById(7); $fields = $class->getFieldDefinitions(); foreach ($fields as $field) { $field->setLocked(true); } $class->save(); ``` --- ## Path Formatter #### Summary * Allows you to show a user friendly "object information' instead of technical path in OpenDXP data types such as Many-To-One, Many-To-Many (Object) etc. * Uses Ajax to request nice path info on demand (i.e. after rendering) #### Example In this example, we want to display the asset metadata title of the target asset. ![Asset Metadata](../../../img/formatter_class_asset.png) #### Configuration via class editor Just specify the formatter service in the class editor. ![Formatter Class DI](../../../img/formatter_class_di.png) #### Sample Formatter Class ```php $item) { $newPath = ($item['path'] ?? $item['fullpath']) . ' - ' . time(); if (isset($context['language'])) { $newPath .= ' ' . $context['language']; } if ($item['type'] === 'object') { $targetObject = Concrete::getById($item['id']); if ($targetObject instanceof News) { $newPath = $targetObject->getTitle() . ' - ' . $targetObject->getShortText(); } else if ($targetObject instanceof BlogArticle) { $newPath = $targetObject->getTitle(); } } elseif ($item['type'] === 'asset') { $asset = Asset::getById($item['id']); if ($asset) { $title = $asset->getMetadata('title'); if (!$title) { $title = 'this asset does not have a title, use ' . $newPath . ' instead'; } if ($fd instanceof Data\ManyToManyRelation) { $newPath = '' . $title; } else { $newPath = $title; } } } // don't forget to use the same key, otherwise the matching doesn't work $result[$key] = $newPath; } return $result; } } ``` **Note regarding batch assignment** The containerType will be `batch` and the object ID will be the folder ID. --- ## Preview Generator #### Summary Preview Generators provide services to get more control over the preview tab. They provide a UI component to pass additional parameters to a URL-generator. Providers need to implement: `\OpenDxp\Model\DataObject\ClassDefinition\PreviewGeneratorInterface` > As of OpenDXP 10.6, a default implementation of a `PreviewGenerator` is provided. You only need to add > a [link generator](./30_Link_Generator.md). The generated URL will then be used for the preview. Parameters returned in the `getParams` method will be rendered as a select box. Whatever the user chooses will be passed to the `generatePreviewUrl` method. Provide a Preview Generator within the Class settings: ![Preview Generator Setup](../../../img/preview_generator_1.png) #### Sample PreviewProvider Implementation ```php namespace App\Service\PreviewParamProvider; use App\Website\LinkGenerator\ProductLinkGenerator; use OpenDxp\Model\DataObject\ClassDefinition\PreviewGeneratorInterface; use OpenDxp\Model\DataObject\Concrete; class ProductPreviewParamProvider implements PreviewGeneratorInterface { protected ProductLinkGenerator $productLinkGenerator; public function __construct(ProductLinkGenerator $productLinkGenerator) { $this->productLinkGenerator = $productLinkGenerator; } public function generatePreviewUrl(Concrete $object, array $params): string { $additionalParams = []; foreach($this->getPreviewConfig($object) as $paramStore) { $paramName = $paramStore['name']; if($paramValue = $params[$paramName]) { $additionalParams[$paramName] = $paramValue; } } return $this->productLinkGenerator->generate($object, $additionalParams); } public function getPreviewConfig(Concrete $object): array { return [ [ 'name' => '_locale', 'label' => 'Locale', 'values' => [ 'English' => 'en', 'German' => 'de' ], 'defaultValue' => 'en' ], [ 'name' => 'otherParam', 'label' => 'Other', 'values' => [ 'Label Text' => 'value', 'Option #2' => 2, 'Custom Option' => 'custom' ], 'defaultValue' => 'value' ] ]; } } ``` ![Preview Generator Example UI](../../../img/preview_generator_2.png) --- ## Object Variants The best way to show the use and function of object variants is via a use case: Your goal is to store lots of products in OpenDXP. Many of these products are variants of each other, for example a yellow t-shirt, a blue t-shirt, a red t-shirt etc. Most of the t-shirts' attributes have the same values and they just differ in color and EAN code. One way to achieve this is to make a generic t-shirt object and then create for each variant a child object within the tree which inherits most attributes and sets only those which differ. This approach works fine, but if you have dozens or even hundreds of variants, your object tree becomes quite big and confusing. This is where object variants come in. Basically, they are just objects which you can configure to be not shown in the object tree. In the tree, you just create the generic t-shirt. For each variant of this t-shirt, you create an object variant. While you can choose variants to not be shown in the tree, you will nevertheless be able to edit them via an own tab within the object editor. The only difference between objects and variants in behaviour is that you cannot add an object of another class below a variant. So, you can create hundreds of object variants without blowing your object tree. ![Object Variants](../../../img/classes-variants.png) As the normal object grid, the object variant grid supports paging, filtering, hiding of columns and visualization of inherited values. So even a big number of variants should be manageable. ### Create and organize Object Variants To use object variants, they have to be activated in the class definition first. Object variants only make sense, if inheritance is activated. Therefore, inheritance is a requirement for object variants. ![Object Variants](../../../img/classes-variants1.png) Once they are activated, the object editor has an additional tab 'Variants'. There, all variants of the current object are shown in a grid. Via buttons object variants can be created, opened and deleted. ![Object Variants](../../../img/classes-variants2.png) To create object variants via code, just create a normal object, set as parent the generic t-shirt and set the object type to `DataObject::OBJECT_TYPE_VARIANT`. ```php $objectX = new DataObject\Product(); $objectX->setParent(DataObject\Product::getById(362603)); $objectX->setKey("variantname"); $objectX->setColor("black"); $objectX->setType(DataObject::OBJECT_TYPE_VARIANT); $objectX->save(); ``` ### Query Object Variants ##### Get all Object Variants of an object Getting all variants of an object is quite simple. Just call `getChildren` and pass the wanted object types as an array. If only variants should be returned use following line. ```php $objectX->getChildren([DataObject::OBJECT_TYPE_VARIANT]); ``` By default, `getChildren` delivers objects, variants, and folders. ##### Object Variants in Object Lists Similar to `getChildren`, the object list objects now have an object type property, which defines the object types to deliver. Per default objects, variants and folders are delivered. To deliver object variants, use one of the following code snippets: ```php $list = new DataObject\Product\Listing(); $list->setObjectTypes([DataObject::OBJECT_TYPE_VARIANT]); $list->load(); // or DataObject\Product::getList([ "objectTypes" => [DataObject::OBJECT_TYPE_VARIANT] ]); ``` If you want regular objects and variants, you should use: ```php $list = new DataObject\Product\Listing(); $list->setObjectTypes([DataObject::OBJECT_TYPE_VARIANT,DataObject::OBJECT_TYPE_OBJECT]); $list->load(); ``` --- ## Additional Class Settings On class level, there are multiple additional settings and features available which influence the appearance and behaviour of OpenDXP. These can be either configured in the OpenDXP backend or via code by a developer. ##### These features include: * [Composite Indices](./05_Composite_Indices.md) * [Data Inheritance and Parent Class](./25_Inheritance.md) * [Object Variants](./70_Variants.md) * [Custom Icons for objects](./10_Custom_Icons.md) * [Custom Layouts](./15_Custom_Layouts.md) * [Custom Views](./20_Custom_Views.md) * [Locking Fields](./35_Locking_Fields.md) * [Path Formatter](./50_Path_Formatter.md) * [Link Generator](./30_Link_Generator.md) * Type Declaration --- ## Object Classes To get started with OpenDXP objects, classes must be defined. In [Create A First Project](../../01_Getting_Started/06_Create_a_First_Project.md) you can see the first steps how to create objects and classes. Defining a class consists of two parts: * defining the attributes of the object and * defining the layout for the object editor. Layout object properties can be grouped into panels, which incorporate the layout areas north, east, west, south and center and additionally they can be positioned into tab panels. This allows logical structuring of object attributes into smaller units of data belonging together. It depends on the use case how data should be grouped and structured. Common applications are tabs/groups for different languages or logical groups like basic data, media, sales data, etc. In addition to the main editor layout, Custom Layouts for different views on the object data can be defined. To define a class, the menu `Settings` -> `Data Objects` -> `Classes` needs to be used in the OpenDXP toolbar menu. The class name has to be a valid PHP class name. After creating a new class, the class attributes and layout can be built. Add `title` field to classdefinitions, where you can add a translation key like `app.classes.product` which is used for translations in your translation file. Class attributes are defined from a set of predefined data types. These data types define not only the type of data such as text, number, image, reference to another object etc. but also how data input can be achieved and how data is accessed. Each data type comes with an input widget. For instance, the text input data type comes with a simple text field, the image data type comes with a drop area to which a user can drag and drop an image. For detailed documentation about these data types see [Data Types](./01_Data_Types/README.md). Also have a look at [Layout Elements](./03_Layout_Elements/README.md) for information about the layout elements and [Class Settings](./05_Class_Settings/README.md) for further details and features of OpenDXP classes like inheritance, variants, preview, custom layouts, etc. --- ## Working With Objects via PHP API OpenDXP provides an object orientated PHP API to work with Objects. There are several generic functionalities provided by OpenDXP and for each OpenDXP object class OpenDXP generates corresponding PHP classes for working with these objects via a comfortable PHP API and take full advantage of an IDE (e.g. code completion etc.). ### CRUD Operations The following code snippet indicates how to access, create and modify an object programmatically: ```php setKey(\OpenDxp\Model\Element\Service::getValidKey('New Name', 'object')); $newObject->setParentId(123); $newObject->setName("New Name"); $newObject->setDescription("Some Text"); // the optional parameter allows you to provide additional info // currently supported: // * versionNote: note added to the version (see version tab) $newObject->save(["versionNote" => "my new version"]); //getting objects $myObject = DataObject\Myclassname::getById(167); //reading data $myObject->getName(); $myObject->getDescription(); // it's also possible to get an object by an foreign ID $city = DataObject\City::getByZip(5020,1); // you can also get an object by id where you don't know the type $object = DataObject::getById(235); // or obtain an object by path $object = DataObject::getByPath("/path/to/the/object"); // or get data objects matching a defined set of object types (default is to fetch data objects and variants) $product = DataObject\Product::getByColor('purple', 1, 0, [Product::OBJECT_TYPE_VARIANT]); //updating and saving objects $myObject->setName("My Name"); $myObject->save(); //deleting objects $city->delete(); ``` > When using your generated classes in the code, the classname always starts with a capital letter. > Example-Classname: `product` > PHP-Class: `DataObject\Product`   ### Object Listings Once data is available in a structured manner, it can not only be accessed more conveniently but also be filtered, sorted, grouped and displayed intuitively by the use of an object listing. Moreover, data can be exported very easily not only programmatically but also through the OpenDXP object csv export. Object listings are a simple way to retrieve objects from OpenDXP while being able to filter and sort data along that process. Object listings also come with a built-in paginator that simplifies the display of results in a paged manner. When working with object listings, user defined routes come in handy while implementing object detail views. User defined routes allow directing requests to certain detail pages, even though the request does not portray the path of a document, but matches a certain route. For more information have a look at [URLs based on Custom Routes](../02_MVC/04_Routing_and_URLs/02_Custom_Routes.md). An object listing class is created automatically for each class defined in OpenDXP. Objects for the class `Myobject` are retrieved through a listing as in the following example: ```php setOffset($offset); $entries->setLimit($perPage); $entries->setOrderKey("date"); $entries->setOrder("desc"); $entries->setCondition("name LIKE ?", ["%bernie%"]); // use prepared statements! Mysqli only supports ? placeholders // or $entries->setCondition("name LIKE :name", ["name" => "%bernie%"]); // With PDO_Mysql you can use named parameters // to add param to the condition (until build 181 this cannot be used with setCondition in the same listing, you should use setCondition OR addConditionParam but not both) $entries->addConditionParam("city = ?", "New York", "AND"); // concatenator can be AND or OR //use array bindings for prepared statements $entries->setCondition("city IN (?)", [["New York", "Chicago"]]); // or $entries->setCondition("city IN (:cities)", ["cities" => ["New York", "Chicago"]]); // named parameters //if necessary you can of course custom build your query $entries->setCondition("name LIKE " . $entries->quote("%bernie%")); // make sure that you quote variables in conditions! // some data types support direct filtering, which can be verified via 'isFilterable()' method on field definition: if ($entries->getClass()->getFieldDefinition('fieldname e.g. name or age or city')->isFilterable()) { $entries->filterByName('Jan'); // filters for name='Jan' $entries->filterByAge(18, '>='); // filters for age >= 18 $entries->filterByCity([['New York', 'Chicago']], 'IN (?)'); // filters for city IN ('New York','Chicago') } foreach ($entries as $entry) { $entry->getName(); } // there is also a shorthand eg.: $items = DataObject\Myclassname::getList([ "offset" => $offset, "limit" => $perPage, "orderKey" => "date", "order" => "desc" ]); // order by multiple columns $items = DataObject\Myclassname::getList([ "offset" => $offset, "limit" => $perPage, "orderKey" => ["date", "name"], "order" => "desc" ]); // with different directions $items = DataObject\Myclassname::getList([ "offset" => $offset, "limit" => $perPage, "orderKey" => ["name", "date"], "order" => ["asc","desc"] ]); // with random order $items = new DataObject\PhoneProduct\Listing(); $items->setOrderKey("RAND()", false); foreach ($items as $item) { echo $item . "
    "; // output the path of the object } // with subselect in order $items = new DataObject\PhoneProduct\Listing(); $items->setOrderKey("(SELECT id FROM sometable GROUP BY someField)", false); ``` #### Using prepared statement placeholders and variables The syntax is similar to that from the Zend Framework described [here](https://framework.zend.com/manual/1.12/en/zend.db.adapter.html#zend.db.adapter.select.fetchall). ```php setCondition("name LIKE ?", "%bernie%"); $entries->load(); foreach($entries as $entry) {...} // using more variables / placeholders $entries = new DataObject\Myclassname\Listing(); $entries->setCondition("name LIKE ? AND date > ?", ["%bernie%", time()]); $entries->load(); foreach($entries as $entry) {...} // using named placeholders (recommended) $entries = new DataObject\Myclassname\Listing(); $entries->setCondition("name LIKE :name AND date > :date", ["name" => "%bernie%", "date" => time()]); $entries->load(); ``` #### Conditions on localized fields Following code will only search the EN value of the field `name`. ```php setLocale("en"); $entries->setCondition("name LIKE :name", ["name" => "%term%"]); // name is a field inside a localized field container ``` ###### Disable Localized Fields in listings Sometimes you don't want to have localized data on the listings (condition & order by). For this particular case you can disable localized fields on your listing (the objects in the list will still include the localized fields). Conditions and order by statements on localized fields are then not possible anymore. ```php setIgnoreLocalizedFields(true); $entries->load(); ``` #### Get Objects matching a value of a property Often it's very useful to get a listing of objects or a single object where a property is matching exactly one value. This is especially useful to get an object matching a foreign key, or get a list of objects with only one condition. ```php $result = DataObject\ClassName::getByMyfieldname($value, ['limit' => $limit, 'offset' => $offset]); // or object variants matching a value $result = DataObject\ClassName::getByMyfieldname($value, ['limit' => $limit, 'offset' => $offset, 'objectTypes' => [DataObject::OBJECT_TYPE_VARIANT]]); // or for localized fields $result = DataObject\ClassName::getByMyfieldname($value, ['locale' => $locale, 'limit' => $limit, 'offset' => $offset]); // or object variants matching a value in localized fields $result = DataObject\ClassName::getByMyfieldname($value, ['locale' => $locale, 'limit' => $limit, 'offset' => $offset, 'objectTypes' => [DataObject::OBJECT_TYPE_VARIANT]]); // or object variants and objects matching a value in localized fields $result = DataObject\ClassName::getByMyfieldname($value, ['locale' => $locale, 'limit' => $limit, 'offset' => $offset, 'objectTypes' => [DataObject::OBJECT_TYPE_VARIANT, DataObject::OBJECT_TYPE_OBJECT]]); ``` If you set no limit, a list object containing all matching objects are returned. If the limit is set to 1 the first matching object is returned directly (without listing). Only published objects are return. Alternatively you can pass an array as second parameter which will be applied to the object listing. ```php $result = DataObject\ClassName::getByMyfieldname($value, ['limit' => 1,'unpublished' => true]); ``` ###### Examples ```php getZip(); ... } // get a city by zip $city = DataObject\City::getByZip(5020, 1); $city->getZip(); // do something with the city // get the first 10 cities in Austria $list = DataObject\City::getByCountry("AT", 10); foreach ($list as $city) { // do something with the cities $city->getZip(); } ``` #### Get an Object List/Object by Localized Fields ```php $list = DataObject\News::getByLocalizedfields($fieldName, $value, $locale, $limit | array('limit' => $limit, 'offset' => $offset, 'unpublished' => $unpublished)); // or $list = DataObject\News::getByFieldName($value, $locale, $limit | array('limit' => $limit, 'offset' => $offset, 'unpublished' => $unpublished)); ``` ###### Examples ```php 1]); // or $city = DataObject\City::getByCity("Wels", null, 1); // get the first 10 cities in Austria by localized field using default locale $list = DataObject\City::getByLocalizedfields("country", "Österreich", null, 10); // or $list = DataObject\City::getByCountry("Österreich", null, 10); // get the first 10 cities in Austria by localized field "de" locale $list = DataObject\City::getByLocalizedfields("country", "Österreich", "de", 10); // or $list = DataObject\City::getByCountry("Österreich", "de", 10); //get a country by localized name in english $country = DataObject\Country::getByLocalizedfields("name", "Austria", "en", 1); // or $country = DataObject\Country::getByName("Austria", "en", 1); ``` #### Get an Object List including unpublished Objects Normally object lists only give published objects. This can be changed by setting a lists `unpublished` property to `true`. ```php true]); //or $list = new \OpenDxp\Model\DataObject\News\Listing(); $list->setUnpublished(true); $list->load(); ``` Sometimes, by default all unpublished objects are returned even if `setUnpublished` is set to `false`. It is the case when working on the admin side (plug-in for instance). You can switch globally the behaviour (it will bypass `setUnpublished` setting), using the following static method: ```php addFieldCollection("MyCollection", "collection"); $list->addFieldCollection("MyCollection"); $list->setCondition("`MyCollection~collection`.myinput = 'hugo' AND `MyCollection`.myinput = 'testinput'"); ``` ```php [ ["type" => "MyCollection", "fieldname" => "collection"], ["type" => "MyCollection"] ], "condition" => "`MyCollection~collection`.myinput = 'hugo' AND `MyCollection`.myinput = 'testinput'" ]); ``` You can add field collections to a listing object by specifying the type of the field collection and optionally the fieldname. The fieldname is the fieldname of the field collection in the class definition of the current object. Once field collections are added to an object listing, you can access attributes of field collections in the condition of the object listing. The syntax is as shown in the examples above `FIELDCOLLECTIONTYPE~FIELDNAME.ATTRIBUTE_OF_FIELDCOLLECTION`, or if you have not specified a fieldname `FIELDCOLLECTION.ATTRIBUTE_OF_FIELDCOLLECTION`. The object listing of this example only delivers objects of the type Collectiontest, which have * a Fieldcollection of the type `MyCollection` and the value `testinput` in the attribute `myinput` and * a Fieldcollection in the field `collection` of the type `MyCollection` and the value `hugo` in the attribute `myinput`.   #### Working with Knp\Component\Pager\Paginator ###### Action ```php public function testAction(Request $request, \Knp\Component\Pager\PaginatorInterface $paginator): Response { $list = new DataObject\Simple\Listing(); $list->setOrderKey("name"); $list->setOrder("asc"); $paginator = $paginator->paginate( $list, $request->query->getInt('page', 1), 10 ); return $this->render('Test/Test.html.twig', [ 'paginator' => $paginator, 'paginationVariables' => $paginator->getPaginationData() ]); } ``` ###### View ```twig {% for item in paginator %}

    {{ item.name }}

    {% endfor %}
    {% include 'includes/pagination.html.twig' %} ``` ###### Partial Script (`includes/pagination.html.twig`) ```twig ``` #### Access and modify internal object list query It is possible to access and modify the internal query from every object listing. The internal query is based on `\Doctrine\DBAL\Query\QueryBuilder`. ```php onCreateQueryBuilder( function (QueryBuilder $queryBuilder) { $queryBuilder->join( 'object_localized_CAR_en', 'object_query_EF_OSOI', 'onlineOrderItem', 'onlineOrderItem.product__id = object_localized_CAR_en.id' ); } ); ``` #### Debugging the Object List Query You can access and print the internal query which is based on `\Doctrine\DBAL\Query\QueryBuilder` to debug your conditions like this: ```php onCreateQueryBuilder( function (QueryBuilder $queryBuilder) { // echo query echo $queryBuilder->getSQL(); } ); ``` --- ## External System Interaction Whenever interaction with other systems is required, data objects are the vital components of data exchange. OpenDXP data objects can be created, filled and listed programmatically in order to realize batch imports and exports with only very few lines of code. Therefore the recommended way of interacting with external systems is using the PHP API of OpenDXP and create a interaction layer with your custom PHP code. This interaction layer can be within a [OpenDXP plugin](../20_Extending_OpenDxp/13_Bundle_Developers_Guide/README.md), a library component, a custom web service, a [CLI Command](../19_Development_Tools_and_Details/11_Console_CLI.md) or just a simple CLI script - you have the full flexibility. To keep things simple, we're using simple CLI scripts in the following example, although we're recommending the use of [CLI Commands](../19_Development_Tools_and_Details/11_Console_CLI.md). ### Import The following example indicates the creation of a new object of the class `myclass`. Put the following script into the file `/bin/example.php` (or any other PHP file). ```php setKey(1); $object->setParentId(1); $object->setPublished(true); $object->setMyattribute("This is a test"); $object->save(); // or create multiple objects for ($i = 0; $i < 60; $i++) { $o = new DataObject\News(); $o->setKey(uniqid() . "-" . $i); $o->setParentId(1); $o->setPublished(true); $o->save(); $output->writeln("Created object " . $o->getFullPath() . "\n"); } } } ``` Thus, with very few lines of codes importer scripts can be implemented to populate data objects. Please have a look at OpenDxp\Console how to integrate your custom CLI scripts to the [OpenDXP console](../19_Development_Tools_and_Details/11_Console_CLI.md). ### Export Export of data objects can be achieved programmatically similar to imports by using object listings and writing just a few lines of code. ```php $file = fopen("export.csv","w"); $entries = new DataObject\Myclassname\Listing(); $entries->setCondition("name LIKE ?", "%bernie%"); foreach($entries as $entry) { fputcsv($file, [ 'id' => $entry->getId(), 'name' => $entry->getName() ]); } fclose($file); ``` For simple CSV exports, OpenDXP backend interface provides a CSV export functionality. ### Memory Issues If you're using / creating very much objects you should call the OpenDXP garbage collector after several cycles to prevent memory issues ```php // just call this static method \OpenDxp::collectGarbage(); ``` Or use `RuntimeCache::disable()` before iterate many objects to avoid excesive memory usage. **WARNING:** This will flush the entire internal registry! To avoid this, you can pass an array with keys (indexes) which should stay in the registry eg. ```php \OpenDxp::collectGarbage(["myImportantKey", "myConfig"]); // You can also add items to the static list of globally protected keys by passing them to $longRunningHelper = \OpenDxp::getContainer()->get(\OpenDxp\Helper\LongRunningHelper::class); $longRunningHelper->addOpenDxpRuntimeCacheProtectedItems(["myVeryImportantKey", "mySuperImportKey", "..."]); // This list is maintained as long as the process exists. You can remove protected keys again by calling $longRunningHelper->removeOpenDxpRuntimeCacheProtectedItems(["myVeryImportantKey", "mySuperImportKey", "..."]); ``` You can pass in a string instead of an array if you only want to supply a single key. ### Temporary files Temporary files which get created during processing are usually deleted when the current process finishes. In some cases this may be a problem when thousands of temporary files get created within a process. If you want to clear temporary files before the script ends, you can call ```php \OpenDxp::deleteTemporaryFiles(); ``` --- ## Customize Editing Interface ### Customize _Add Object_ Dialog To customize the _Add Object_ dialog, just create admin translations in the following format: `object_add_dialog_custom_title.CLASSNAME` `object_add_dialog_custom_text.CLASSNAME` replace `CLASSNAME` with the actual name of the class of which dialog you'd like to customize (case-sensitive). ##### Example ![Admin translation configuration](../img/object-create-dialog-admin-translations.png) ![add object dialog box](../img/object-create-dialog-box.png) --- ## Objects Objects are the PIM part of OpenDXP and are the way to go for managing structured data within OpenDXP. Based on a class definition that defines structure and attributes object can be used for pretty much any structured data – may it be products, categories, persons, customers, news, orders, blog entries, … For the attributes many datatypes (simple ones and really complex ones) are available. OpenDXP objects are literally objects in the sense of object oriented programming. The class definition can be defined through a user friendly graphical user interface (GUI), but nevertheless in the background a plain PHP class is created, which can profit from inheritance and can be utilized and accessed within your custom PHP code. So managing data becomes really easy. Data objects can be instantiated and filled within OpenDXP backend or within your custom code by using the PHP API and common programming paradigms (create new instances, using getter and setter, ...). For saving objects just call the `save`` method and OpenDXP takes care of the rest. So it is also really easy to serve object from external systems like CRM, ERP, PIM or asset management systems. This chapter describes following aspects of objects from a technical point of view: * [Object Classes](./01_Object_Classes/README.md) * [Working with Objects via PHP API](./03_Working_with_PHP_API.md) * [External System Interaction](./05_External_System_Interaction.md) For all the provided backend functionality within OpenDXP have a look at the User Documentation of OpenDXP. [comment]: #(TODO add link) --- ## Localize Your Documents OpenDXP allows you to localize every document. You can find the setting in your document in the tab `Properties`. There you can choose from language which is configured in the system settings. The selected language is registered as a property on the document, which is inherited to all of its children. If you have selected a language this will be automatically set on your request object (`$request->getLocale()`) and is therefore automatically used for shared translations, localized object lists and all other localized kind of contents. ![Localization Settings](../img/localization-documents.png) Since the language is a simple property you can access it like every other property like: ```php // in your controller / action $locale = $request->getLocale(); //or $language = $this->document->getProperty("language"); // any document $doc = \OpenDxp\Model\Document::getById(234); $language = $doc->getProperty("language"); ``` ```twig {% set documentLanguage = document.getProperty('language') %} ``` Once you have defined the language of your documents you can also use the [translate helper](./04_Shared_Translations.md) in your views, as described [here](./04_Shared_Translations.md). OpenDXP uses the standard Symfony translator, so you can even access all the translations provided by your bundles. ### Translating terms on the website OpenDXP comes with a translation module for the website which is explained in [Shared Translations](./04_Shared_Translations.md). This is what needs to be done to use translations in templates and display them accordingly on the website (frontend). E.g. button names, labels - all the stuff that is predefined by the template and not entered by the editor. #### More about this To learn more about this visit the [best practices for multilanguage pages](../26_Best_Practice/04_Multilanguage_Setup.md) --- ## Shared Translations OpenDXP provides an easy way for editors to edit commonly used translation terms across the application, which can be found here: `Extras` > `Translation` > `Shared Translations`. In the background the standard Symfony Translator component is used to add the shared translation functionality to the application. The main benefit is that you have only one single translator for all your translations. It automatically uses the locale specified on a document or from a fallback mechanism. For more information, please also check out [Symfony's Translations Component](https://symfony.com/doc/current/translation.html). ![Shared Translations](../img/localization-translations.png) Available languages are defined within the system languages, see [here](./README.md). Shared translations are stored in `translations_messages` database table and can be versioned using [Migrations](../19_Development_Tools_and_Details/37_Migrations.md). ### Translations case sensitivity Translations are case sensitive by default. You can reconfigure OpenDXP to handle website and admin translations as case insensitive, however as this implies a performance hit (translations might be looked up twice) and it does not conform with Symfony's translators you're encouraged to reference translation keys with the same casing as they were saved. ### Working with Shared Translations / the Translator in Code ##### Example in Templates / Views You can also use variable interpolation in localized messages. ```twig
    © {{ 'Copyright'|trans }}
    {{ 'Imprint'|trans }} {# variable interpolation, 'about' translates to 'About {{siteName}}' #} {{ 'about'|trans({'{{siteName}}': siteName}) }}
    ``` Parameters in translations can be wrapped in double curly braces (`{{` and `}}`) but you are free to use other placeholder wrappers as well, e.g. `%parameter%` like in the [Symfony docs](https://symfony.com/doc/current/translation.html#translatable-objects) also works. ##### Example in a Controller ```php trans("legal_notice"); $siteName = "Demo"; // or get dynamically // variable interpolation, 'about' translates to 'About {{siteName}}' $translatedAbout = $translator->trans("about", ['siteName' => $siteName]); // ... } } ``` ##### Translation Pluralization/Selection Since OpenDXP uses Symfony Translator component in background, you can store and use the translations in ICU Message Format(supported by Symfony Translator) for Pluralization, Selection and more. [Read here](https://symfony.com/doc/current/translation.html#message-format) This can be achieved in OpenDXP by selecting type "ICU Format" on translation UI and passing required parameter in view/Controller. e.g. - Add translation key and select type "ICU Format". ![Translation Pluralization1](../img/translation_pluralization1.png) - Click on language cell plain text button to edit ![Translation Pluralization1](../img/translation_pluralization1b.png) and add translation in ICU format `{variable_name, function_name, function_statement}` ![Translation Pluralization2](../img/translation_pluralization2.png) - Use in view ```twig {{ 'cars_sold'|trans({'sold_count': 0}) }} {# output: No car sold yet. #} {{ 'cars_sold'|trans({'sold_count': 1}) }} {# output: Only one car sold. #} {{ 'cars_sold'|trans({'sold_count': 100}) }} {# output: Total of 100 cars sold! #} ``` ### OpenDXP backend functionalities #### Sorting & Filtering on language level ![Sorting Shared Translations](../img/localization-translations-sorting.jpg) #### Translation Export & Import Translations can be exported to a CSV file and then re-imported later on. ![Translation Export](../img/localization-translations-export.jpg) Translations are still imported automatically as long as the translation key does not exist in the target system or the translation itself is still empty. Conflicts (i.e. the translation in the target system does not match the version of the source) are shown in an overview tab and then can be merged manually. ![Translation Import](../img/localization-translations-import.jpg) --- ## Admin Translations There are several components in the OpenDXP backend UI which are configured differently for each project. These are * object class names * object field labels * object layout components * document types * predefined properties * custom views * document editables All these elements (except document editables) can be translated in *Settings* > *Admin Translations* similar to the Shared Translations. All installed system languages are available for translation. It's even possible to override the system translations shipped with OpenDXP, so basically you can translate anything within the backend UI. Strings which are subject to special translations, but have not been translated yet, are displayed with a "+" in front and after the string, if `Debug Admin-Translations (wrapped in +)` is activated in system settings (*Settings* > *System Settings*). But you can use the admin translation also in your custom templates. Admin translations use the same translator component (Symfony) but on a different domain. Admin translations underlay the same case sensitivity logic as [shared translations](./04_Shared_Translations.md#translations-case-sensitivity). ##### Example: Translate Options of a Select Editable in the language of the current user ```twig {{ opendxp_select("select", { "store": [ ["option1", {{ "Option One"|trans({}, 'admin', opendxp_editmode_admin_language()) }}], ["option2", {{ "Option Two"|trans({}, 'admin', opendxp_editmode_admin_language()) }}], ["option3", {{ "Option Three"|trans({}, 'admin', opendxp_editmode_admin_language()) }}] ] }) }} ``` ##### Adding your own admin languages (since v6.3.6) OpenDXP comes with a set of translations which are managed by [POEditor](https://poeditor.com). There is a list of [essential translations](https://poeditor.com/join/project/VWmZyvFVMH) and another [extended translations](https://poeditor.com/join/project/XliCYYgILb) list. However, the amount of available languages is limited, because only languages with certain translation progress are included in the main distribution. If you want to make additional languages available for the admin interface, you can do so by putting a symfony translation file for the desired language into the default path for the symfony translator (e.g. use `translations/admin.af.yaml` for making `Afrikaans` available, the translation file can be also empty). If you haven't configured anything different this is `%kernel.project_dir%/translations` for Symfony 4 projects. ##### Override language of admin translations in editmode of documents In some projects you want to use a different language as admin translations, e.g. English (en) instead of Croatian (hr) or Chinese (zh_Hans) instead of Chinese (zh). ```yaml # config/config.yaml opendxp: translations: admin_translation_mapping: 'hr': 'en' 'zh': 'zh_Hans' ``` --- ## Formatting Service OpenDXP ships a service for international formatting of numbers, currencies and date time. The service is basically a factory and wrapper of the [`IntlDateFormatter` component of php](https://php.net/manual/de/class.intldateformatter.php). ##### Usage Example ```php get(OpenDxp\Localization\IntlFormatter::class); //optionally set locale (otherwise it is resolved from the request) $service->setLocale("de"); echo $service->formatDateTime($time, IntlFormatter::DATETIME_MEDIUM); echo $service->formatNumber("45632325.32"); echo $service->formatCurrency("45632325.32", "EUR"); //for formatting currencies you can also define a pattern echo $service->formatCurrency("45632325.32", "EUR", "#,##0.00 ¤¤"); ``` ##### Overwriting Definition You can overwrite the default service definition with your own, e.g. to overwrite the default currency patterns. ```yml services: # Formatting service for dates, times and numbers OpenDxp\Localization\IntlFormatter: calls: - [setCurrencyFormat, ['en', '¤ #,##0.0']] - [setCurrencyFormat, ['de', '#,##0.00 ¤¤']] ``` --- ## Multi Language i18n & Localization in OpenDXP Localization is a very important aspect in every content management. In OpenDXP localization can be centrally configured and has influence on multiple aspects within the system. Bottom line is that using OpenDXP in a multi language mode is pretty easy for users and developers. OpenDXP takes care of all technical aspects and by doing so follows the Symfony patterns. OpenDXP has different sets of languages/locales and translations for the back end (CMS) and front end (website). This allows you to have the user interface of OpenDXP in different languages than the website. You need to be aware of this when requesting the current and available locales, as they are different depending on the context. If a user is saving an object in OpenDXP which is set to English, the current locale is different then when a visitor on your French website triggers a save action. ### Content Localization #### Language Configuration The available languages for content are configured centrally in system settings (*Settings* > *System Settings* > *Localization & Internationalization (i18n/l10n)*). ![Localization Settings](../img/localization-settings.png) Following settings can be defined here: * Available languages * System wide default language * Fallback language for each language: if defined, OpenDXP returns values from fallback language if primary language has no values set. * Define if content for that language should be mandatory in localized fields of data objects. Details see [here](../05_Objects/01_Object_Classes/01_Data_Types/50_Localized_Fields.md#definition-of-required-languages) > *Note: Removing language from the Localization & Internationalization (i18n/l10n) list will not delete its respective data. Please use console command `opendxp:locale:delete-unused-tables` for cleanup.* #### Localized Content Areas The activated languages have influence to following modules of content within OpenDXP: * [Document - Localization (system property for language)](./02_Localize_your_Documents.md) * [Shared Translations (Symfony Translations Component)](./04_Shared_Translations.md) * [Localized Fields for Objects (object localization)](../05_Objects/01_Object_Classes/01_Data_Types/50_Localized_Fields.md) * [Structured Data Fields - Classification Store](../05_Objects/01_Object_Classes/01_Data_Types/15_Classification_Store.md) ### OpenDXP Backend UI Localization OpenDXP backend UI localization is independent of content localization but works similar to Shared Translations. Basically every text in OpenDXP backend is translatable, but there are two different sources for translations - OpenDXP system translations and project specific translations. #### OpenDXP System Translations This covers all labels and texts within OpenDXP that ship with OpenDXP installation package. Here the standard language English is maintained by the core team. In addition to that, everybody can join the [OpenDXP translation project](https://poeditor.com/join/project/VWmZyvFVMH) to add system translations in additional languages. With every OpenDXP release, newly added translations are added to the OpenDXP installation package. System translations can be overwritten by [Admin Translations](./07_Admin_Translations.md). --- ## Placeholder Example Workflows support placeholders. By using placeholders, it is possible, to reuse an existing workflow and reapply places and transitions onto a new workflow. ### Available options Example: ``` opendxp: workflows: product_workflow_local_de: &local_workflow_reference placeholders: '%%stateFieldName%%': 'translationStateDe' '%%locale%%': 'de' enabled: true label: "Local Release Workflow" type: "state_machine" supports: &local_workflow_supports_ref - \OpenDxp\Model\DataObject\Product initial_markings: "local_300_basic_data_pending" marking_store: &local_workflow_marking_store_ref type: single_state arguments: - %%stateFieldName%% places: &local_workflow_places_ref 100_new: label: "Basic Data Pending from Global Workflow (%%locale%%)" visibleInHeader: true color: '#cddc39' colorInverted: false permissions: - publish: true local_300_basic_data_pending: label: "Pending" visibleInHeader: true color: '#cddc39' colorInverted: false permissions: - publish: true ... transitions: &local_workflow_transitions_ref to_published: to: local_400_published from: [local_700_locked] guard: is_fully_authenticated() and ('ROLE_OPENDXP_ADMIN' in role_names or 'ROLE_RECIPE_WORKFLOW_FINISH_DEVELOPMENT' in role_names) options: label: 'Set to local_400_published' .... ``` Example cloned workflows: ``` product_workflow_local_en: placeholders: '%%stateFieldName%%': 'translationStateEn' '%%locale%%': 'en' '%%flag%%': 'gb' enabled: true label: "Local Release Workflow" type: "state_machine" supports: <<: *local_workflow_supports_ref initial_markings: "local_300_basic_data_pending" marking_store: <<: *local_workflow_marking_store_ref places: <<: *local_workflow_places_ref transitions: <<: *local_workflow_transitions_ref product_workflow_local_hr: placeholders: '%%stateFieldName%%': "translationStateHr" '%%locale%%': "hr" '%%flag%%': 'hr' enabled: true label: "Local Release Workflow" type: "state_machine" supports: <<: *local_workflow_supports_ref initial_markings: "local_300_basic_data_pending" marking_store: <<: *local_workflow_marking_store_ref places: <<: *local_workflow_places_ref transitions: <<: *local_workflow_transitions_ref product_workflow_local_ro: placeholders: '%%stateFieldName%%': "translationStateRo" '%%locale%%': "ro" '%%flag%%': 'ro' enabled: true label: "Local Release Workflow" type: "state_machine" supports: <<: *local_workflow_supports_ref initial_markings: "local_300_basic_data_pending" marking_store: <<: *local_workflow_marking_store_ref places: <<: *local_workflow_places_ref transitions: <<: *local_workflow_transitions_ref ``` ... --- ## Details ### Available options ```yaml opendxp: workflows: # Prototype name: # Placeholder values in this workflow configuration (locale: "%%locale%%") will be replaced by the given placeholder value (eg. "de_AT") placeholders: # Example: placeholders: %%locale%%: de_AT # Can be used to enable or disable the workflow. enabled: true # When multiple custom view or permission settings from different places in different workflows are valid, the workflow with the highest priority will be used. priority: 0 # Will be used in the backend interface as nice name for the workflow. If not set the technical workflow name will be used as label too. label: ~ # Enable default audit trail feature provided by Symfony. Take a look at the Symfony docs for more details. audit_trail: enabled: false # A workflow with type "workflow" can handle multiple places at one time whereas a state_machine provides a finite state_machine (only one place at one time). Take a look at the Symfony docs for more details. type: ~ # One of "workflow"; "state_machine" # Handles the way how the state/place is stored. If not defined "state_table" will be used as default. Take a look at the marking store section of the OpenDXP workflow docs for a description of the different types. marking_store: type: ~ # One of "multiple_state"; "single_state"; "state_table"; "data_object_multiple_state"; "data_object_splitted_state" arguments: [] service: ~ # List of supported entity classes. Take a look at the Symfony docs for more details. supports: # Example: - \OpenDxp\Model\DataObject\Product # Can be used to implement a special logic which subjects are supported by the workflow. For example only products matching certain criteria. Take a look at the support strategies page of the OpenDXP workflow docs for more details. support_strategy: # Examples: type: expression arguments: - \OpenDxp\Model\DataObject\Product - subject.getProductType() == "article" and is_fully_authenticated() and "ROLE_OPENDXP_ADMIN" in role_names # Type "expression": a symfony expression to define a criteria. type: ~ # One of "expression" arguments: [] # Define a custom service to handle the logic. Take a look at the Symfony docs for more details. service: ~ # Possibility to add multiple initial places. initial_markings: [] places: # Example: places: closed: label: close product permissions: - condition: is_fully_authenticated() and 'ROLE_OPENDXP_ADMIN' in role_names modify: true # for OpenDXP roles use ROLE_ - condition: is_fully_authenticated() and 'ROLE_OPENDXP_USER' in role_names modify: true - modify: false objectLayout: 2 # Prototype - # Nice name which will be used in the OpenDXP backend. label: ~ # Title/tooltip for this place when it is displayed in the header of the OpenDXP element detail view in the backend. title: '' # Color of the place which will be used in the OpenDXP backend. color: '#bfdadc' # If set to true the color will be used as border and font color otherwise as background color. colorInverted: false # If set to false, the place will be hidden in the header of the OpenDXP element detail view in the backend. visibleInHeader: true permissions: # Prototype - # A symfony expression can be configured here. The first set of permissions which are matching the condition will be used. condition: ~ # save permission as it can be configured in OpenDXP workplaces save: ~ # publish permission as it can be configured in OpenDXP workplaces publish: ~ # unpublish permission as it can be configured in OpenDXP workplaces unpublish: ~ # delete permission as it can be configured in OpenDXP workplaces delete: ~ # rename permission as it can be configured in OpenDXP workplaces rename: ~ # view permission as it can be configured in OpenDXP workplaces view: ~ # settings permission as it can be configured in OpenDXP workplaces settings: ~ # versions permission as it can be configured in OpenDXP workplaces versions: ~ # properties permission as it can be configured in OpenDXP workplaces properties: ~ # a short hand for save, publish, unpublish, delete + rename modify: ~ # if set, the user will see the configured custom data object layout objectLayout: ~ transitions: # Required # Example: close_product: from: open to: closed options: label: close product notes: commentEnabled: 1 commentRequired: 1 additionalFields: - name: accept title: accept terms required: 1 fieldType: checkbox - name: select title: please select a type setterFn: setSpecialWorkflowType fieldType: select fieldTypeSettings: options: - key: Option A value: a - key: Option B value: b - key: Option C value: c # Prototype - name: ~ # Required # An expression to block the transition guard: ~ # Example: is_fully_authenticated() and 'ROLE_JOURNALIST' in role_names and subject.getTitle() == 'My first article' from: [] to: [] options: # Nice name for the OpenDXP backend. label: ~ notes: # If enabled a detail window will open when the user executes the transition. In this detail view the user be asked to enter a "comment". This comment then will be used as comment for the notes/events feature. commentEnabled: false # Set this to true if the comment should be a required field. commentRequired: false # Can be used for data objects. The comment will be saved to the data object additionally to the notes/events through this setter function. commentSetterFn: ~ # Can be used for data objects to prefill the comment field with data from the data object. commentGetterFn: ~ # Set's the type string in the saved note. type: 'Status update' # An optional alternative "title" for the note, if blank the actions transition result is used. title: ~ # Add additional field to the transition detail window. additionalFields: # Prototype - # The technical name used in the input form. name: ~ # Required # The data component name/field type. fieldType: ~ # One of "input"; "numeric"; "textarea"; "select"; "datetime"; "date"; "user"; "checkbox", Required # The label used by the field title: ~ # Whether or not the field is required. required: false # Optional setter function (available in the element, for example in the updated object), if not specified, data will be added to notes. The Workflow manager will call the function with the whole field data. setterFn: ~ # Will be passed to the underlying OpenDXP data object field type. Can be used to configure the options of a select box for example. fieldTypeSettings: [] # Configure the output of custom HTML for a transition. customHtml: # Define a custom service for rendering custom HTML within the note modal. service: 'App\Service\Workflow\CustomHtmlService' # Set position of custom HTML inside modal (top, center, bottom; default=top). position: 'top' # Css class to define the icon which will be used in the actions button in the backend. iconClass: ~ # Forces an object layout after the transition was performed. # This objectLayout setting overrules all objectLayout settings within the places configs. objectLayout: false notificationSettings: # Prototype - # A symfony expression can be configured here. All sets of notification which are matching the condition will be used. condition: ~ # Send a email notification to a list of users (user names) when the transition get's applied notifyUsers: [] # Send a email notification to a list of user roles (role names) when the transition get's applied notifyRoles: [] # Define which channel notification should be sent to, possible values "mail" and "opendxp_notification", default value is "mail". channelType: # Default: - mail # Type of mail source. mailType: template # One of "template"; "opendxp_document" # Path to mail source - either Symfony path to template or fullpath to OpenDXP document. Optional use %_locale% as placeholder for language. mailPath: '@OpenDxpCore/Workflow/NotificationEmail/notificationEmail.html.twig' # Change published state of element while transition (only available for documents and data objects). changePublishedState: no_change # One of "no_change", "force_unpublished", "force_published", "save_version" # behaviour when transition gets applied but there are unsaved changes unsavedChangesBehaviour: warn # One of "warn", "save", "ignore" # Actions which will be added to actions button independently of the current workflow place. globalActions: # Prototype - # Nice name for the OpenDXP backend. label: ~ # Css class to define the icon which will be used in the actions button in the backend. iconClass: ~ # Forces an object layout after the global action was performed. # This objectLayout setting overrules all objectLayout settings within the places configs. objectLayout: false # An expression to block the action guard: ~ # Example: is_fully_authenticated() and is_granted('ROLE_JOURNALIST') and subject.getTitle() == 'My first article' # Determines if the global action should save the subject or not, defaults to true. saveSubject: false # Optionally set the current place of the workflow. Can be used for example to reset the workflow to the initial place. to: [] # See notes section of transitions. It works exactly the same way. notes: commentEnabled: false commentRequired: false commentSetterFn: ~ commentGetterFn: ~ type: 'Status update' title: ~ additionalFields: # Prototype - name: ~ # Required fieldType: ~ # One of "input"; "textarea"; "select"; "datetime"; "date"; "user"; "checkbox", Required title: ~ required: false setterFn: ~ fieldTypeSettings: [] # Configure the output of custom HTML for a transition. customHtml: # Define a custom service for rendering custom HTML within the note modal. service: 'App\Service\Workflow\CustomHtmlService' # Set position of custom HTML inside modal (top, center, bottom; default=top). position: 'top' ``` --- ## Marking Stores The OpenDXP workflow engine provides several different ways how to store the actual places of a subject. These are represented of the following marking store types. ### state_table (default) This is the default marking store. The place information is stored in the element_workfow_state table. This would be the best option for Assets and Documents. For data objects the other marking store options might be the better choice as the data would be stored directly in the data object model as attributes. ###### Configuration Example ```yaml marking_store: type: state_table ``` ### single_state Stores the place in a attribute of the subject (calls the setter method). Can be used if a model cannot be in more then one state at the same time. This is the default single_state marking store provided by the Symfony framework. For data objects a select field (or maybe input field) would be the right OpenDXP field to store the places when the single_state marking store is used. ###### Configuration Example ```yaml marking_store: type: single_state arguments: - workflowState ``` ### multiple_state Same as single_state but can be used if the subject can be in more then one state at the same time. Note: this cannot be used in combination with data object multiselect fields - use data_object_multiple_state instead. ###### Configuration Example ```yaml marking_store: type: multiple_state arguments: - workflowState ``` ### data_object_multiple_state Can be used to store mutliple places in a data object multiselect field. ###### Configuration Example ```yaml marking_store: type: data_object_multiple_state arguments: - workflowState ``` ### data_object_splitted_state (data objects only) Works similar to single_state and data_object_multiple_state but is able to store different places in different OpenDXP data object attributes. Therefore it's needed to configure a mapping between places and data object attribute names. ###### Configuration Example In the following example places which are related to the text of the data object are stored in the `workflowStateText` attribute whereas image related places are stored in `workflowStateImages`: ```yaml marking_store: type: data_object_splitted_state arguments: - text_open: workflowStateText text_finished: workflowStateText text_released: workflowStateText images_open: workflowStateImages images_finished: workflowStateImages images_released: workflowStateImages ``` ### Options provider (for single_state, data_object_multiple_state and data_object_splitted_state) If data object attributes (select or multiselect) are used to store the places a special options provider can be used to automatically provide the correct select options. Just setup `@opendxp.workflow.place-options-provider` as options provider and the workflow name as options provider data in the used data object attribute. ![Options Provider](../img/workflow_options_provider.jpg) This options provider adds the places in a nicely formatted way: ![Options Provider Select Example](../img/workflow_options_provider_select.jpg) --- ## Support Strategies The workflow engine offers several different ways to define which entities are supported by the configured workflow. Important: The different configuration ways cannot be combined. It's necessary to choose one. ### Supports The simplest way is to use `supports`. A single entity class name or an array of entity class names can be defined. ###### Configuration Examples ```yaml supports: OpenDxp\Model\DataObject\Product ``` ```yaml supports: - OpenDxp\Model\DataObject\Product - OpenDxp\Model\DataObject\ProductCategory ``` ### Expression Support Strategy The expression support strategy can be used if a workflow should apply to a entity under certain circumstances only. It's possible to define a symfony expression - the workflow then applies only if the expression is valid. ###### Configuration Example In the following example the workflow applies to products where the attribute "productType" is equal to "article". ```yaml support_strategy: type: expression arguments: - OpenDxp\Model\DataObject\Product - "subject.getProductType() == 'article'" ``` ### Custom Support Strategy If a very specific logic is needed it's possible to add a service which implements the `Symfony\Component\Workflow\SupportStrategy\WorkflowSupportStrategyInterface`. ###### Configuration Example ```yaml support_strategy: service: App\Workflow\SupportStrategy ``` ###### Example Implementation (needs to be registered in the service container) ```php If multiple places provide a valid permission configuration the one with the highest priority will be used. > The priority is based on the workflow priority (the workflow with the higher priority setting will win). Within a > single workflow the order within the places section of the configuration file will be used. For conditions to other roles than admin users, use `ROLE_`, e.g. `ROLE_EDITOR` for a role named "Editor". --- ## Simple Workflow Tutorial Let's make a one truly simple example workflow for product objects. ### Create a class and custom layouts I've created the really simple product class (sku, localized name, localized picture and localized description, price and quantity). ![Example product class](../img/workflow_example_product_class.png) Next, I added four custom layouts which later I will assign to the specific statuses. * `newProduct` layout with ID = 1 ![The new product custom layout](../img/workflow_example_product_cl_1.png) * `fillContents` layout with ID = 2 ![The fill contents custom layout](../img/workflow_example_product_cl_2.png) * `updatePicture` layout with ID = 3 ![The update picture custom layout](../img/workflow_example_product_cl_3.png) * `validateQtyPrice` layout with ID = 4 ![The validate qty and price custom layout](../img/workflow_example_product_cl_4.png) ### The workflow declaration Now create the base configuration in `config/config.yaml` ```yml opendxp: workflows: workflow: label: 'Product Workflow' type: 'state_machine' supports: - 'OpenDxp\Model\DataObject\Product' places: #TODO transitions: #TODO ``` As you can see, the workflow is called **Product workflow**, we haven't added any places and transitions yet. The workflow is available only for instances of `OpenDxp\Model\DataObject\Product` objects. We use the workflow type `state_machine`, so one transition can start from multiple places. #### Specify places Now it's the best time to define some places for products. What I want to achieve? Let's suppose that our new products are integrated with an external system and new positions comes to OpenDXP as empty objects only with SKU. I need to have ability to decide which products would be used in OpenDXP, the rest of products I want to reject. To achieve that requirement, I have to make (at least) three places. * new - for the newest products * rejected - for products which I'm not going to use in the future. Also I would like to add some note with a reason here. * update content - for products I would like to publish ```yml (...) places: new: label: 'New product' color: '#377ea9' permissions: - objectLayout: 1 rejected: label: 'Rejected product' color: '#28a013' update_content: label: 'Update Content' title: 'Updating content step' color: '#d9ef36' permissions: - objectLayout: 2 (...) ``` As you can see I used `objectLayout` key to define which custom layout would be used with the *new* status. #### Specify the first transitions As an administrator, I can decide which product can be processed and which shouldn't be. To do so, I need to add some actions. * reject product - to change the status for products I don't want to use * start processing - to move the product to the processing step ```yml (...) transitions: reject_product: from: new to: rejected options: label: 'Reject the product' notes: commentEnabled: true commentRequired: true start_processing: from: new to: update_content options: label: 'Start processing the product' (...) ``` #### More statuses actions and definitions Let's add 4 more places for updating content * updating the content * updating the picture * updating the price and stock * mark content as a ready - move product back to the administrator Let's add few new rows in the configuration file ```yml (...) places: (...) update_picture: label: 'Update Product Picture' title: 'Update the product picture' color: '#d9ef36' permissions: - objectLayout: 3 validate_stock_and_price: label: 'Validate Stock + Price' title: 'Check the quantity and the price' color: '#d9ef36' permissions: - objectLayout: 4 content_prepared: label: 'Content Prepared' title: 'Content ready to publish' color: '#28a013' (...) transitions: (...) content_updated: from: update_content to: update_picture options: label: 'Content up-to-date' notes: commentEnabled: true commentRequired: false picture_updated: from: update_picture to: validate_stock_and_price options: label: 'Picture up-to-date' notes: commentEnabled: true commentRequired: false content_ready: from: validate_stock_and_price to: content_prepared options: label: 'Content is ready to publish' (...) ``` #### Last actions: publish or rollback At the final stage of the workflow I would like to have three choices * Publish the product (with additional field called *"timeWorked"*) * Start workflow from the beginning * Reject the product (with note) We've already made the reject and start processing transition, the only thing here is to add an additional from place. This can be done because we have workflow type `state_machine` activated, here our modified transition definitions. ```yml (...) transitions: reject_product: from: [new, content_prepared] to: rejected options: label: 'Reject the product' notes: commentEnabled: true commentRequired: true start_processing: from: [new, content_prepared] to: update_content options: label: 'Start processing the product' notes: commentEnabled: true commentRequired: false (...) ``` The last one we need is publishing - place and transition - that is only allowed to a certain role. ```yml (...) places: (...) accepted: label: 'Accepted product' color: '#28a013' (...) ``` And, the transition with a *"timeWorked"* field. ```yml (...) transitions: (...) publish: from: content_prepared to: accepted guard: "is_fully_authenticated() and is_granted('ROLE_OPENDXP_ADMIN')" options: label: 'Publish the product' notes: commentEnabled: true commentRequired: true additionalFields: - name: 'timeWorked' fieldType: 'input' title: 'Time Spent' required: true (...) ``` #### Workflow in action Below, you can find showcase of the workflow I've just prepared. | Status | Screenshot | | ------------------------------------------------------- |----------------------------------------------------| | Initial status when new object comes into the system | ![Initial Place](../img/workflow_editmode_1.png) | | Update Content | ![Update Content](../img/workflow_editmode_2.png) | | Update Picture | ![Update Picture](../img/workflow_editmode_3.png) | | Validate Price and Stock | ![Validate](../img/workflow_editmode_4.png) | | Content is ready | ![Content Ready](../img/workflow_editmode_5.png) | | Publish the Product | ![Publish Product](../img/workflow_editmode_6.png) | #### Check the history In the *"Notes & Events"* tab, there is a list with every action used on the object via the Workflow module. --- ## Workflow Reporting Depending on the marking store of workflows, different ways of Workflow Reporting are available. For details see [marking store docs](./02_Marking_Stores.md). ### Using `state_table` and Custom Reports You can easily use the custom reports to make workflow place reporting, filtering, exporting and directly open related elements. This way, you can follow and monitor workflows and the progress of document, asset and object. #### Create a custom report for objects First, you just have to create a new empty custom report, please see: [custom reports](../18_Tools_and_Features/29_Custom_Reports.md) After creating it, you can configure it like this for the Source Definition, Column Configuration and Chart Settings: ![Source Definition](../img/workflow-report-source-definition.png) Save it and you are ready to use it! You can filter globally by state and status, order and filter the columns and export results Here is an example of rendered workflow custom report: ![Rendered workflow custom report](../img/workflow-report-result.png) ### Using `single_state`, `data_object_multiple_state` and `data_object_splitted_state` together with Object Grid Since `single_state` (and others) stores the place information into data object attributes, OpenDXP default object grids can be used to do workflow reporting on OpenDXP Objects. Just create a corresponding grid configuration and use default filtering and sorting functionality. Additionally extensions like [Advanced Object Search](https://github.com/open-dxp/advanced-object-search) can be used to create saved searches with predefined filters. --- ## Working With PHP API The OpenDXP workflow management can also be used via PHP API. ### Using Workflow API to modify Places of Elements Since the OpenDXP workflow management is based on the Symfony workflow component, also its API can be used the same way. For details see [Symfony docs](https://symfony.com/doc/current/workflow/usage.html). Additionally OpenDXP provides the `\OpenDxp\Workflow\Manager`, which provides additional functionality for working with the workflow management - like additional methods for apply places with additional data (`applyWithAdditionalData()`) and apply global actions (`applyGlobalAction()`). See following example how to interact with workflows with PHP API. ```php /** * $object ... your element, e.g. a OpenDXP data object * $workflowRegistry Symfony\Component\Workflow\Registry from Symfony container */ $workflow = $workflowRegistry->get($object, 'workflow'); if($workflow->can($object, 'content_ready')) { //modify workflow via Symfony API and without saving additional data $workflow->apply($object, 'content_ready'); //make sure you save the workflow subject afterwards if any data was changed during transition //e.g. by a marking store $object->save(); } if($workflow->can($object, 'publish')) { //modify workflow with OpenDXP Workflow Manager - notes are written with additional data $additionalData = [ NotesSubscriber::ADDITIONAL_DATA_NOTES_COMMENT => 'this is some additional note', NotesSubscriber::ADDITIONAL_DATA_NOTES_ADDITIONAL_FIELDS => [ 'timeWorked' => 20 ] ]; /** * $workflowManager OpenDxp\Workflow\Manager from Symfony container */ //last parameter defines if workflow subject should be saved after transition $workflowManager->applyWithAdditionalData($workflow, $object, 'publish', $additionalData, true); } ``` ### Using Events for Additional Functionality Symfony workflow module comes with a bunch of events that can be used for customizing and extending default workflow functionality. See [Symfony docs](https://symfony.com/doc/current/workflow/usage.html#using-events) for details. In addition to the Symfony events, OpenDXP provides two additional events for global actions: - `opendxp.workflow.preGlobalAction` - `opendxp.workflow.postGlobalAction` See [WorkflowEvents](https://github.com/open-dxp/opendxp/blob/1.x/lib/Event/WorkflowEvents.php) for details. #### Using Additional Data in Events If additional data fields are defined in the transition configuration, it's possible to retrieve those data on event listener functions. See following example how to interact with additional data on transition events. Let's first define an additional field in the workflow configuration. ```yaml transitions: close_product: from: open to: closed options: label: close product notes: commentEnabled: 1 commentRequired: 1 additionalFields: - name: mySelect title: please select a type fieldType: select fieldTypeSettings: options: - key: Option A value: a - key: Option B value: b - key: Option C value: c ``` Then, we should define the transition event on `services.yaml`. ```yaml services: App\EventListener\WorkflowsEventListener: tags: - { name: kernel.event_listener, event: workflow.projectWorkflow.transition.close_product, method: onCloseProduct } ``` The additional data will be then available in the transition event ```php getContext(); $additionalData = $context["additional"]; $mySelectValue = $additionalData["mySelect"];; // do something with the value } } ``` --- ## Workflow Management ### General OpenDXP Workflow Management provides configuration of multiple workflows on OpenDXP elements (assets, documents, data objects) to support data maintenance processes, element life cycles and various other processes. It is based on the [Symfony workflow component](https://symfony.com/doc/current/workflow.html) and extends it with a few OpenDXP specific features. So, before using OpenDXP Workflow Management it makes sense to know the basics of Symfony workflow component. #### Concepts **Workflow** A workflow is a model of a process an element in OpenDXP goes through. It consists of *places*, *transitions*, a *marking store*, *global actions* and a couple of additional configuration options. Each element can be in multiple workflows simultaneously. **Workflow Type 'Workflow'** Workflow type *workflow* describes the default type of workflows and allows to model a *workflow net* which is a subclass of a *petri net*. It models a process of an element and allows multiple places simultaneously for this element. **Workflow Type 'State Machine'** A state machine is a subset of a workflow and its purpose is to hold a state of your model. The most important restriction is that a state machine cannot be in more than one place simultaneously. For further details see also [Symfony docs](https://symfony.com/doc/current/workflow/state-machines.html). **Place** A place is a step in the workflow and describes a characteristic or a status of an element - for example *in progress*, *product attributes defined*, *copyright available*, *element ready for publish*, etc. Depending on the place an element may appear in a specific view (e.g. custom layout for data objects) and may have certain special permissions (e.g. finished elements cannot be modified anymore). **Marking Store** The marking store stores the current place(s) for each element. OpenDXP ships with a couple of stores that can be configured in [workflow configuration](./01_Configuration_Details/README.md). **Transition** A transition describes the action to get from one place to another. Transitions are allowed (or not) depending on additional criteria (transition guards) and may require additional notes and information entered by user. **Transition Guard** Define criteria that define if a transition is currently allowed or not. **Global Action** While transitions are only available when the element is in a certain place, global actions are available at every place. Besides that, they are very similar to transitions. ### Configuration The workflow configuration takes place in the Symfony configuration tree in the OpenDXP namespace. For details of configuration options see inline comments and documentation (call command `bin/console config:dump-reference OpenDxpCoreBundle`) or [Configuration Details](./01_Configuration_Details/README.md). ### Events The OpenDXP workflow management fires several events that can be used to customize and extend functionality. For details see [Working with PHP API](./09_Working_with_PHP_API.md). ### User Notifications Notifications (via email or OpenDXP notifications) can be configured to be sent to users when an transition takes place. To do this simply specify an array of user(s) or role(s) that you would like to be notified in options section of the transition definition. Roles will send an notification to every user with that role. ```yml ... transitions: myTransition: options: notificationSettings: - # A symfony expression can be configured here. All sets of notification which are matching the condition will be used. condition: "" # optional some condition that should apply for this notification setting to be executed # Send a email notification to a list of users (user names) when the transition get's applied notifyUsers: ['admin'] # Send a email notification to a list of user roles (role names) when the transition get's applied notifyRoles: ['projectmanagers', 'admins'] # Define which channel notification should be sent to, possible values "mail" and "opendxp_notification", default value is "mail". channelType: - mail - opendxp_notification # Type of mail source. mailType: 'template' # this is the default value, One of "template"; "opendxp_document" # Path to mail source - either Symfony path to template or fullpath to OpenDXP document. # Optional use %%_locale%% as placeholder for language. mailPath: '@OpenDxpCore/Workflow/NotificationEmail/notificationEmail.html.twig' #this is the value ... ``` Multiple notification settings with conditions allow sophisticated notifications to be configured for each transition. To customize the e-mail template, following options are available: - Overwrite the template `@OpenDxpCore/Workflow/NotificationEmail/notificationEmail.html.twig` or configure your own template path in settings. Default parameters available in the template are `subjectType`, `subject`, `action`, `workflow`, `workflowName`, `deeplink`, `note_description`, `translator`, `lang`. If additional parameters are required, overwrite the service `OpenDxp\Workflow\Notification\NotificationEmailService`. - Configure a OpenDXP Mail Document and use full power of OpenDXP Mail Documents, with Controller, Action, Placeholders, etc. In the mail document same parameters as above are available. - If more custom notifications are necessary, use custom event listeners. ### Workflow History In the *"Notes & Events"* tab, there is a list with every action used on the object via the Workflow module. ### Workflow Overview If workflows are configured for a OpenDXP element, an additional tab with workflow details like all configured workflows, their current places and a workflow graph is added to OpenDXP element detail page. ![Workflow Overview](../img/workflow-overview.jpg) > To render the graph, `graphviz` is needed as additional system requirement. --- ## Versioning ### General All contents in OpenDXP (documents, assets and objects) are versioned. You can have as many versions as you want. On each change a new version of the element is created. For example, if you would like to find the version history in objects you have to choose **Versions** tab. There you can see a list of changes, what is the difference between revisions and you can choose which version should be published. ![Object versions changeslist](../img/versioning_changeslist.png) ### Settings You can configure the versioning behavior in the ![Settings](../img/Icon_settings.png) **Settings -> System Settings -> (Documents, Assets, Objects)** ![Objects version history settings](../img/versioning_settings.png) #### Stack trace OpenDXP generates a stack trace in the db table for each version. You can deactivate this with the following settings: ```yml opendxp: assets: versions: disable_stack_trace: true documents: versions: disable_stack_trace: true objects: versions: disable_stack_trace: true ``` OpenDXP has a maintenance job (VersionsCleanupStackTraceDbTask) to cleanup stack trace for versions older than 7 days. ### Version storage For every version the metadata and, if present, binary data is stored. Since the amount of information can turn out to be too big real quick, OpenDXP provides 3 different ways to handle the storage of version data. #### Configuration ##### Filesystem *This is the default setting*. To store version data in the filesystem, use the `FileSystemStorageAdapter`. ```yml OpenDxp\Model\Version\Adapter\VersionStorageAdapterInterface: public: true alias: OpenDxp\Model\Version\Adapter\FileSystemVersionStorageAdapter OpenDxp\Model\Version\Adapter\FileSystemVersionStorageAdapter: ~ ``` ##### Database To store the version data in a database, use the `DatabaseVersionStorageAdapter` service. You need to pass a configured doctrine database connection as an argument. Therefore, you are able to provide a connection to a completely separate database which may contains only the version data. ```yml OpenDxp\Model\Version\Adapter\VersionStorageAdapterInterface: public: true alias: OpenDxp\Model\Version\Adapter\DatabaseVersionStorageAdapter OpenDxp\Model\Version\Adapter\DatabaseVersionStorageAdapter: arguments: $databaseConnection: '@doctrine.dbal.versioning_connection' ``` The database needs to contain a table called `versionsData`. The following script can be used to create the table including the necessary columns. ```sql CREATE TABLE `versionsData` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `cid` int(11) unsigned DEFAULT NULL, `ctype` enum('document','asset','object') DEFAULT NULL, `metaData` longblob DEFAULT NULL, `binaryData` longblob DEFAULT NULL, PRIMARY KEY (`id`) ) ``` #### Delegate To store the version data based on a threshold in either the default storage location or a fallback storage location use `DelegateVersionStorageAdapter` service. If the size of metadata or binary data information exceeds the configured `byteThreshold` value, the version data is stored using the fallback adapter. ```yaml OpenDxp\Model\Version\Adapter\VersionStorageAdapterInterface: public: true alias: OpenDxp\Model\Version\Adapter\DelegateVersionStorageAdapter OpenDxp\Model\Version\Adapter\DelegateVersionStorageAdapter: public: true arguments: $byteThreshold: 1000000 $defaultAdapter: '@OpenDxp\Model\Version\Adapter\DatabaseVersionStorageAdapter' $fallbackAdapter: '@OpenDxp\Model\Version\Adapter\FileSystemVersionStorageAdapter' OpenDxp\Model\Version\Adapter\FileSystemVersionStorageAdapter: ~ OpenDxp\Model\Version\Adapter\DatabaseVersionStorageAdapter: arguments: $databaseConnection: '@doctrine.dbal.versioning_connection' ``` In this example the version data is stored in the database as long as neither the metadata nor the binary data exceeds 1000000 bytes in size. Otherwise, the filesystem is used as storage. ### Turn off Versioning for the Current Process Sometimes it is very useful to just deactivate versioning for a process. For example for importers or synchronization with 3rd party systems. You can globally deactivate and activate the versioning with the following PHP code directly in your scripts: ```php \OpenDxp\Model\Version::disable(); // to disable versioning for the current process \OpenDxp\Model\Version::enable(); // to enable versioning for the current process ``` *Note:* With these commands you only deactivate/activate the versioning for the current PHP process. This setting is not saved, and only affects changes on elements which are modified within this process! ### Working with PHP API When working with PHP API - especially when saving elements - you need to set the `userModification` so that a proper user is shown in version history. When you set `userModification` to `0` OpenDXP shows `system` as user in the version history. ```php $object->setUserModification(0); $object->save(); ``` #### Example: How to get a previous version of an object ```php $versions = $currentObject->getVersions(); $previousVersion = $versions[count($versions)-2]; $previousObject = $previousVersion->getData(); ``` --- ## Auto Save Drafts OpenDXP has an auto save functionality enabled by default for Data Objects and Documents, which creates a draft on default interval of 60 seconds or as soon as there is a first change detected on a data object/document. This feature creates a draft version, which is not published and changes will appear only in backend until published. It is possible to change interval or completely turn off auto save functionality(by setting interval to 0) in config.yaml: ```yaml opendxp: documents: auto_save_interval: 60 # saving interval in seconds, default 60s, set to 0 to disable it objects: auto_save_interval: 60 # saving interval in seconds, default 60s, set to 0 to disable it ``` > Note: When using Auto Save for a type, the "Disable unsaved content warning" checkbox in User profile will have no effect on the close action. --- ## Custom Icons & Tooltips for Documents/Assets & Data Objects OpenDXP allows to dynamically define custom element icons & tooltips in the element tree. In addition, the icon of the editor tab can be changed. ##### Properties that can be changed * Element CSS class * Element icon * Element icon class * Tree node tooltip * Element Text ### How to override the default style The basic idea is to provide one's own implementation of `OpenDxp\Model\Element\AdminStyle`. This can be achieved by attaching a listener to the [`AdminEvents::RESOLVE_ELEMENT_ADMIN_STYLE`](https://github.com/open-dxp/admin-bundle/blob/1.x/src/Event/AdminEvents.php#L428-L439) event. Example: In `config/services.yaml` add ```yaml App\EventListener\AdminStyleListener: tags: - { name: kernel.event_listener, event: opendxp.admin.resolve.elementAdminStyle, method: onResolveElementAdminStyle } ``` Create AdminStyleListener in EventListeners ```php getElement(); // decide which default styles you want to override if ($element instanceof \App\Model\Product\Car) { $event->setAdminStyle(new \App\Model\Product\AdminStyle\Car($element)); } } } ``` #### Example: Custom Icon for the Car DataObject This will change the `Car` icon depending on the car type: ```php namespace App\Model\Product\AdminStyle; use OpenDxp\Model\DataObject; use OpenDxp\Model\Element\AdminStyle; class Car extends AdminStyle { protected ElementInterface $element; public function __construct(ElementInterface $element) { parent::__construct($element); $this->element = $element; if ($element instanceof \App\Model\Product\Car) { DataObject\Service::useInheritedValues(true, function () use ($element) { if ($element->getObjectType() == 'actual-car') { // setting this to false is necessary for the elementIcon to actually be used $this->elementIconClass = false; $this->elementIcon = '/bundles/opendxpadmin/img/twemoji/1f697.svg'; } }); } } } ``` Result: ![Class Icons](../img/classes-icons2.png) ### Example: Custom Tooltips It is possible to define custom tooltips which are shown while hovering over the element tree. The example outlines how to provide a custom tooltip for `Car` objects. ```php public function getElementQtipConfig(): ?array { if ($this->element instanceof \App\Model\Product\Car) { $element = $this->element; return DataObject\Service::useInheritedValues(true, function () use ($element) { $text = '

    ' . $element->getName() . '

    '; $mainImage = $element->getMainImage(); if ($mainImage) { $thumbnail = $mainImage->getThumbnail("content"); $text .= '

    '; } $text .= wordwrap($this->element->getDescription(), 50, "
    "); return [ "title" => "ID: " . $element->getId() . " - Year: " . $element->getProductionYear(), "text" => $text, ]; }); } return parent::getElementQtipConfig(); } ``` Result: ##### Example: Custom Style for Assets This will display the modification date and image size as additional information. Besides that, it shows a different icon for all assets starting with a capital 'C' in their key. ```php namespace App\Model\Product\AdminStyle; use OpenDxp\DateFormat; use OpenDxp\Model\Asset; use OpenDxp\Model\Element\AdminStyle; class AssetEventStyle extends AdminStyle { public function __construct(ElementInterface $element) { parent::__construct($element); if ($element instanceof Asset\Image) { if (strpos($element->getKey(), 'C') === 0) { $this->elementIconClass = null; $this->elementIcon = '/bundles/opendxpadmin/img/twemoji/1f61c.svg'; } $this->elementQtipConfig = [ 'title' => 'ID: ' . $element->getId(), 'text' => 'Path: ' . $element->getFullPath() . '
    Modified: ' . date(DateFormat::ISO_8601, $element->getModificationDate()) . '
    Size: '. $element->getWidth() . 'x' . $element->getHeight() . " px" ]; } } } ``` ![Class Icons](../img/asset-tree-custom-icon.png) --- ## Scheduling ### General Every element type in OpenDXP (documents, objects, assets) has implemented a scheduler which provides the ability to create tasks like: * Publish * Unpublish * Delete * Publish version - Publish a specific version (You can read more about Versions in [the Versioning section](./01_Versioning.md)) Important: If object is already published, then using `Publish` option will not publish latest version(unpublished) so it is recommended to use `Publish version` option in that case. **Note:** To use scheduler you have to configure "cronjobs". You can find more in the [System setup section](../23_Installation_and_Upgrade/03_System_Setup_and_Hosting/README.md). ### Usage Let's use objects as an example. In the OpenDXP backend UI find the icon: ![Scheduling - the icon in editmode](../img/scheduling_editmode_icon.png) You can add a task by clicking on the **Add** button, which will add an empty row. It has some configurable options: `date`, `time` and `action` (which should run with that task). The `version` option will only be used if you chose the *"Publish version"* action. The `active` checkbox will indicates that the task was not finished yet. To make a task that automatically publishes an unpublished object just fill the values like in the picture, below: ![Scheduling - the new task](../img/scheduling_new_task.png) The effect in the database will be: ``` `schedule_tasks` # id, cid, ctype, date, action, version, active '7', '76', 'object', '1474034700', 'publish', NULL, '1' ``` When the `./bin/console opendxp:maintenance -j scheduledtasks` script will finish processing jobs you could see the changes. In the edit object view: ![Scheduling - the processed task](../img/scheduling_processed_task.png) In the database: ``` `schedule_tasks` # id, cid, ctype, date, action, version, active '8', '76', 'object', '1474034700', 'publish', NULL, '0' ``` --- ## Notes & Events ### General Notes & Events are primarily used to log changes or events on elements independently from the versioning. This includes changes made by marketers, editors, automated importers / synchronisations, .... Simply everything that has nothing to do with the data itself but is important to know. ### Use cases * An importer (CLI-script) that adds information to objects which changes were made * Marketers / SEOs adding information which changes were made on documents like *"optimized for keyword xyz ..."* There are really nearly endless possibilities what to do with Notes & Events. ### Create Notes & Events #### Using API ```php use OpenDxp\Model; $object = Model\DataObject::getById(4); $note = new Model\Element\Note(); $note->setElement($object); $note->setDate(time()); $note->setType("erp_import"); $note->setTitle("changed availabilities to xyz"); $note->setUser(0); // you can add as much additional data to notes & events as you want $note->addData("myText", "text", "Some Text"); $note->addData("myObject", "object", Model\DataObject::getById(7)); $note->addData("myDocument", "document", Model\Document::getById(18)); $note->addData("myAsset", "asset", Model\Asset::getById(20)); $note->save(); ``` And this is how the entry looks like: > **Note:** As the title of a note is translatable (admin domain) make sure you don't add variable text that would lead > to unintended translation entries. Use the description or data for details instead. #### Add Events in OpenDXP backend UI You could also add the note directly in the edit view of objects, documents and assets. ![Notes & events - add a note manually](../img/notesandevents_add_note.png) ##### Specify Custom Types for Notes and Events Via OpenDXP configuration, the selectable types for notes and events can be specified per content type (asset, document, data object), see sample config below: ```yml # config/config.yaml or any other Symfony config file opendxp_admin: documents: notes_events: types: - "" - "content" - "seo" - "some other type" assets: notes_events: types: - "" - "content" - "licese renewal" - "some other type" objects: notes_events: types: - "" - "manual data change" - "some other type" ``` --- ## Properties ### General Every element can have custom properties. You can find these in the **Properties** tab for each type of elements (documents, assets, objects). ![Properties in the document](../img/properties_tab_editmode_preview.png) The properties could be used to specify some special behavior when the document is rendered. Have a look at a few cases below: * Hide the main navigation * Show the sidebar * Use an additional stylesheet ### Get property in the template The following example shows how you can get a property value in the template: ```twig {# retrieve the value of a property named "hideNavigation" #} {% set hideNavigation = document.getProperty('hideNavigation') %} ``` ### Predefined properties With predefined properties you can help/show the editors working within your OpenDXP installation which properties are available for their use. You can also define default values for each defined property to improve the productivity of your editors. **Predefined** does not mean that the value of the predefined property is available for every document. To add global properties which are available everywhere use [Website Settings](./27_Website_Settings.md) instead. ![Predefined properties - selectbox](../img/properties_predefined_selectbox.png) ### Configuration example You can find the Predefined properties configuration in the ![Settings](../img/Icon_settings.png) **Settings -> Predefined properties** menu. The following fields are available in the properties configuration. | Name | Is required? | Description | |---------------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Name | Y | The friendly name shown in the selection. | | Description | N | The description would help understand a specific property meaning. | | Key | Y | This field is the key which you use in your code to retrieve the contents of the property. For example: `$document->getProperty("key");` | | Type | Y | Specifies the type of the content which is allowed in the property. Available types are: text, document, asset, object, bool (checkbox), select. | | Value | N | Here you can define a default value for this property which is added automatically to the property when it is added to an element. This field is optional. See the example configuration above for details. | | Configuration | N | This field is used to configure a property. At the moment, this is used only by the property-type *select*. Separate options with a comma. | | Content-Type | Y | Defines for which element-type (document, asset or object) the property should be available. | > **Note** > Each defined field can be overwritten in the element after it was added. --- ## Tags ### General Tags provide a way to create additional taxonomies and classifications for Documents, Assets and Data Objects. Using tags, you can easily filter OpenDXP Elements (Documents, Data Objects, Assets) and keep the additional search criteria to the application. ### Tags Definition The available tags have to be defined centrally (user permission *tags configuration* is necessary). ![Tags OpenDXP menu](../img/tags_menu.png) ### Tags Assignment In `Documents`, `Assets`, or `Data Objects` editor, there is an additional tab where tags can be assigned to the current element (user permission *tags assignment* is necessary). ![Tags assignment](../img/tags_assignment.png) ### Tags Usage In the `Search` dialog, tags can be selected as additional criteria for the search (user permission *tags search* necessary). ### Working With Tags via API #### Overview For accessing and working with tags via API, take a look into `OpenDxp\Model\Element\Tag`. ```php /** * returns all assigned tags for element * * @return Tag[] */ public static function getTagsForElement(string $cType, int $cId): array { $tag = new Tag(); return $tag->getDao()->getTagsForElement($cType, $cId); } /** * adds given tag to element */ public static function addTagToElement(string $cType, int $cId, Tag $tag): void { $tag->getDao()->addTagToElement($cType, $cId); } /** * removes given tag from element */ public static function removeTagFromElement(string $cType, int $cId, Tag $tag): void { $tag->getDao()->removeTagFromElement($cType, $cId); } /** * sets given tags to element and removes all other tags * to remove all tags from element, provide empty array of tags * * @param Tag[] $tags */ public static function setTagsForElement(string $cType, int $cId, array $tags): void { $tag = new Tag(); $tag->getDao()->setTagsForElement($cType, $cId, $tags); } ``` #### API Usage Examples ##### *Get Tags for Element* To get all tags from the element below: ![API for gettings tags for the shown demo asset.](../img/tags_api_get_tags.png) You can use the `getTagsForElement` method by specifying the element type in the `$cType` parameter. In the case above, the element type is `asset`. ```php $tags = \OpenDxp\Model\Element\Tag::getTagsForElement('asset', 30); dump($tags); ``` The output will be an array with the `OpenDxp\Model\Element\Tag` elements. ``` array:3 [▼ 0 => OpenDxp\Model\Element\Tag {#7351 ▼ #id: 9 #name: "Italy" #parentId: 7 #idPath: "/7/" #children: null #parent: OpenDxp\Model\Element\Tag {#7354 ▶} #dao: OpenDxp\Model\Element\Tag\Dao {#7349 ▶} id: 9 name: "Italy" parentId: 7 idPath: "/7/" children: null parent: OpenDxp\Model\Element\Tag {#7354 ▶} } 1 => OpenDxp\Model\Element\Tag {#7357 ▶} 2 => OpenDxp\Model\Element\Tag {#7345 ▶} ] ``` ##### *Assign a New Tag to an Element* To add a new tag to an element, you first need to create the new tag. Then you just have to use the `\OpenDxp\Model\Element\Tag::addTagToElement` method to assign the tag to the chosen element (by element id). ```php $tag = new \OpenDxp\Model\Element\Tag(); try { $tag->setName('newtag')->save(); \OpenDxp\Model\Element\Tag::addTagToElement('asset', 30, $tag); } catch (Exception $e) { // .... } ``` The result will be: ![Assign new tag by API](../img/tags_api_assign_new_element.png) In the same way, you can use the rest of the available methods. The type properties list is standard. You can use one of `document`, `asset` or `object`. --- ## 13_Perspectives > **Moved to admin-bundle** > > This documentation has moved to the Admin Bundle: > [`admin-bundle/docs/10_Extension_Points/04_Perspectives.md`](https://github.com/open-dxp/admin-bundle/blob/1.x/docs/10_Extension_Points/04_Perspectives.md) --- ## Perspective Example Configuration ```yaml #var/config/perspectives/Event.yaml opendxp: perspectives: definitions: Event: elementTree: - type: customview position: left sort: 0 expanded: true hidden: false id: 87705013-edb9-c9ec-0f5e-c3ee45ca4459 iconCls: null icon: /bundles/opendxpadmin/img/flat-color-icons/vip.svg toolbar: file: hidden: true items: perspectives: true dashboards: true openDocument: true openAsset: true openObject: true searchReplace: true schedule: true seemode: true closeAll: true help: true about: true marketing: hidden: true items: reports: true tagmanagement: true targeting: true seo: hidden: false items: documents: true robots: true httperrors: true extras: hidden: true items: glossary: true redirects: true translations: true recyclebin: true plugins: true notesEvents: true applicationlog: true gdpr_data_extractor: true emails: true maintenance: true systemtools: hidden: false items: phpinfo: true opcache: true requirements: true serverinfo: true database: true fileexplorer: true settings: hidden: true items: customReports: true marketingReports: true documentTypes: true predefinedProperties: true predefinedMetadata: true system: true website: true web2print: true users: hidden: false items: users: true roles: true thumbnails: true objects: hidden: false items: classes: true fieldcollections: true objectbricks: true quantityValue: true classificationstore: true bulkExport: true bulkImport: true routes: true cache: hidden: false items: clearAll: true clearData: true clearSymfony: true clearOutput: true clearTemp: true adminTranslations: true tagConfiguration: true perspectiveEditor: true search: hidden: true items: quickSearch: true documents: true assets: true objects: true datahub: hidden: true ```` --- ## Application logger > [!CAUTION] > To use this feature, please enable the `OpenDxpApplicationLoggerBundle` in your `bundle.php` file and install it accordingly with the following command: > > `bin/console opendxp:bundle:install OpenDxpApplicationLoggerBundle` ### General The application logger bundle is a tool which developers can use to log certain events and errors within a OpenDXP powered application. The logs are visible and searchable within the OpenDXP backend GUI ![Tools menu](../img/Icon_tools.png) **Tools -> Application Logger**: ![Application logger menu](../img/applogger_menu.png) ![Application logger preview](../img/applogger_backend_preview.png) ### How to create log entries The application logger is a PSR-3 compatible component and available on the service container as service `OpenDxp\Bundle\ApplicationLoggerBundle\ApplicationLogger` and therefore it can be used the usual way. #### Basic Usage - Example ##### Controller / Action ```php error('Your error message'); $logger->alert('Your alert'); $logger->debug('Your debug message', ['foo' => 'bar']); // additional context information } public function anotherAction(): void { // fetched from container $logger = $this->get(ApplicationLogger::class); $logger->error('Your error message'); } } ``` ##### Dependency Injection ```yaml App\YourService: calls: - [setLogger, ['@OpenDxp\Bundle\ApplicationLoggerBundle\ApplicationLogger']] ``` You can also make use of autowiring by defining the application logger as dependency: ```yaml services: _defaults: autowire: true App\YourService: ~ ``` ```php logger = $logger; $logger->debug('Hello from YourService'); } } ``` #### Usage as monolog handler Instead of using the `ApplicationLogger` class, you can configure monolog to use the application logger as monolog log handler and make full use of monolog's possibilities. To do so, OpenDXP provides the `ApplicationLoggerDb` monolog handler which is already preconfigured as service and can easily be registered to monolog: ```yaml monolog: handlers: # monolog allows us to register custom handlers via type: service # note that the only supported extra option besides type and id is channels application_logger_db: type: service id: OpenDxp\Bundle\ApplicationLoggerBundle\Handler\ApplicationLoggerDb channels: ["application_logger"] ``` Note that the channel(s) need to exist. This can either by achieved by [configuring them manually](https://symfony.com/doc/current/logging/channels_handlers.html#creating-your-own-channel) or by using [DI tags](https://symfony.com/doc/current/reference/dic_tags.html#dic-tags-monolog) to select the logger for the channel you want to log to. When using DI tags, the channel will be created implicitly by monolog. > **IMPORTANT**: As the `ApplicationLoggerDb` handler has a dependency on the database connection it is important to exclude channels logging database queries (typically the `doctrine` channel) from the handler to avoid infinite loops. Either specify a allowlist of supported channels (as shown in the example above) or exclude the `doctrine` channel by setting channels to `["!doctrine"]`. As the `type: service` handler config does not support filtering by log level, you can use the `filter` handler type to wrap the application logger and to filter by a specific log level: ```yaml monolog: handlers: # The filter handler can be used to filter for a given log level. # Note that the supported channels are now configured on the filter # handler. To filter by level you can set accepted_levels or min_level and max_level. # See https://github.com/symfony/monolog-bundle/blob/master/DependencyInjection/Configuration.php#L97 # for details. application_logger_filter: type: filter channels: ["application_logger"] handler: application_logger_db min_level: ERROR application_logger_db: type: service id: OpenDxp\Bundle\ApplicationLoggerBundle\Handler\ApplicationLoggerDb ``` Of course you can also use the handler in combination with other log handlers such as the [Fingers Crossed Handler](https://symfony.com/doc/current/logging.html#handlers-that-modify-log-entries). See the [Symfony Logging Documentation](https://symfony.com/doc/current/logging.html) for details. As soon as the handler is configured, you can use it (as any other monolog logger) by using a DI tag to specify the channel you want to log to: ```php logger = $logger; } public function testAction(): void { $this->logger->error('Your error message'); } } ``` The service definition can add a DI tag to specify which logger should be injected: ```yaml services: App\Controller\TestController: arguments: $logger: '@logger' tags: - { name: monolog.logger, channel: application_logger } ``` It's also possible to autowire the logger channel by changing the argument name format to `(channel name in camel case) + Logger`. An example for channel `foo_bar`: ```php public function __construct(LoggerInterface $fooBarLogger) { $this->logger = $fooBarLogger; } ``` More details on [Logging Chanel Handlers](https://symfony.com/doc/current/logging/channels_handlers.html#how-to-autowire-logger-channels) #### Special context variables There are some context variables with a special functionality: `fileObject`, `relatedObject`, `component`. ```php error('my error message', [ 'fileObject' => $fileObject, 'relatedObject' => $myObject, 'component' => 'different component', 'source' => 'Stack trace or context-relevant information' // optional, if empty, gets automatically filled with class:method:line from where the log got executed ]); // ... } } ``` In the application logger grid, the new row was created: *my error message* with related object. If you click on the row you can go to the object editor by clicking on the *Related object* edit icon in the popup. ![App logger popup](../img/applogger_backend_popup.png) #### Logging exceptions The application logger provides a helper method to log exceptions and implicitly create a `FileObject` from the exception when writing the log entry. This can be done in 2 ways depending on how you use the application logger: ```php logException('Oh no!', $exception, 'alert', $relatedObject, $component); // 2) When using as monolog handler (see above). Given your logger is any PSR-3 compatible logger, you // can use a static helper to generate a log entry with the same file object as the logging call // above. /** @var \Psr\Log\LoggerInterface $logger */ ApplicationLogger::logExceptionObject($logger, 'Oh no!', $exception, 'alert', $relatedObject); ``` #### Setting an individual logger level Adds a console logger and sets the minimum logging level to *INFO* (overwrites log level in OpenDXP system settings): ```php $logger = \OpenDxp\Bundle\ApplicationLoggerBundle\ApplicationLogger::getInstance("SAP_exporter", true); // returns a PSR-3 compatible logger, registers a custom app logger as `opendxp.app_logger.SAP_exporter` on the service container $logger->addWriter(new \Monolog\Handler\StreamHandler('php://output', \Monolog\Logger::INFO)); ``` ### Configuration There are some options in the system settings to configure the application logger (within the *Debug* panel): ![Application logger settings](../img/applogger_settings.png) When the *Send log summary per mail* checkbox is activated the defined receivers will receive log entries by mail. The priority can be used to setup which log messages will be contained in the mail. For example errors are more important than just info entries. The archive function automatically creates new database tables to archive the log entries in the form `application_logs_archive_*`. In the above example log entries will be moved after 30 days to these archive tables. Optionally a different database name for the archive tables can be defined. --- ## Glossary > [!CAUTION] > To use this feature, please enable the `OpenDxpGlossaryBundle` in your `bundle.php` file and install it accordingly with the following command: > > `bin/console opendxp:bundle:install OpenDxpGlossaryBundle` ### General The glossary module is a powerful tool making internal linking easy and smart. In a special editor you can define your terms which are replaced automatically with a link to the defined page. But the glossary is not only useful for internal linking, it's also perfect for explaining abbreviations. ### How it Works Open the glossary editor ![Tools](../img/Icon_tools.png) **Tools -> Glossary** and define some terms. Then you have to define one or more regions in your views, telling the glossary where you want it to replace your terms. ```twig {% apply opendxp_glossary %}
    {{ opendxp_wysiwyg('content', { height: 200 }) }}
    {% endapply %} ``` Now the output of the WYSIWYG field will look like this. ![Glossary frontend](../img/glossary_frontend.png) And the HTML-markup will look like, below. ```php

    PHP is a widely used, general-purpose scripting language that was originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page  document. As a general-purpose programming language, PHP code is processed by an interpreter application in command-line mode performing desired operating system operations and producing program output on its standard output channel. It may also function as a graphical application. PHP is available as a processor for most modern web servers and as standalone interpreter on most operating systems and computing platforms. You can download it free at php.net.

    ``` > **Note** > Since the glossary depends on languages you'll have to register a language first. [Read more about this topic here.](../06_Multi_Language_i18n/02_Localize_your_Documents.md) --- ## System Settings In the system settings (*Settings* > *System Settings*) system-wide settings for OpenDXP can be made. Changes should be made with care and only by developers. These settings are saved in `var/config/system_settings/system_settings.yaml` or in the settings store based on your configuration. The production environment has them stored in the settings store by default. To save system settings into the settings store, you will need to add following to your configuration: ```yaml opendxp: config_location: system_settings: write_target: type: 'settings-store' read_target: type: 'settings-store' ``` To switch from the Symfony configuration to the settings store for the first time, please follow these steps: 1. Set your write target to `settings-store`: ```yaml opendxp: config_location: system_settings: write_target: type: 'settings-store' ``` 2. Save your system settings via admin user interface (Settings > System Settings). 3. Set your read target to `settings-store` as well: ```yaml opendxp: config_location: system_settings: write_target: type: 'settings-store' read_target: type: 'settings-store'  ``` ### Localization & Internationalization (i18n/l10n) These settings are used in documents to specify the content language (in properties tab), for objects in localized-fields, for shared translations, ... simply everywhere the editor can choose or use a language for the content. Fallback languages are currently used in object's localized fields and shared translations. ### Debug Debugging settings for OpenDXP, like Debug email addresses, Debug admin translations. ### Website System settings about the CMS part of OpenDXP. ### Documents Settings for documents like version steps, default values and URL settings. ### Objects Version steps for objects. ### Assets Settings for assets like version steps. ### Access system config in PHP Controller You can access the system configuration like in the following example: ```php *Appearance & Branding*) system-wide settings for OpenDXP Admin Interface can be made. Changes should be made with care and only by developers. These settings are saved in `var/config/admin_system_settings/admin_system_settings.yaml` or in the settings store based on your configuration. To switch from the Symfony configuration to the settings store for the first time, please follow these steps: 1. Set your write target to `settings-store`: ```yaml opendxp_admin: config_location: admin_system_settings: write_target: type: 'settings-store' ``` 2. Save your system settings via admin user interface (Settings > Appearance & Branding). 3. Set your read target to `settings-store` as well: ```yaml opendxp_admin: config_location: admin_system_settings: write_target: type: 'settings-store' read_target: type: 'settings-store'  ``` ### Colors Settings regarding colors of OpenDXP admin interface like login screen color, Admin interface color, Admin interface background etc. ### Custom Logo Settings allowing to customize the logo in OpenDXP admin interface. ### Custom Login Background Image Settings allowing to customize the background image in OpenDXP login screen. ### Assets Settings for assets like disabling tree preview or hiding edit image tab in the admin interface. ### Access admin config in PHP Controller You can access the admin settings configuration like in the following example: ```php getAdminSystemSettingsConfig(); $bar = $config['branding']['color_login_screen']; } } ``` --- ## Website Settings The `Website Settings` give you the possibility to configure website-specific settings, which you can access in every controller and view. Examples: * ReCAPTCHA public & private key * Locale settings * Google Maps API key * Defaults * .... #### Access the Settings In controllers and views, you can use view helpers or argument resolves to access the config. The returned configuration is an array containing your settings. #### Example Configuration Usage in a template: ```twig {# access the whole configuration #} {{ opendxp_website_config() }} {# or only a single value #} {{ opendxp_website_config('googleMapsKey') }} {# you can pass a default value in case the value is not configured #} {{ opendxp_website_config('googleMapsKey', 'NOT SET') }} ``` Usage in a controller: ```php getData(); // Now do something with the data or set new data (count up in this case) $newNumber = $currentNumber + 1; $somesetting->setData($newNumber); $somesetting->save(); // ... } } ``` #### Events You can listen to events when a website setting is loaded or changed. **Load events** fire a `WebsiteSettingLoadEvent`, which carries a `type` constant indicating the access path: | Constant | Fired by | Event type | |-----------------------------------|---------------------------------------|----------------------------------------| | `WebsiteSettingEvents::POST_LOAD` | `WebsiteSetting::getById()` | `WebsiteSettingLoadEvent::TYPE_SINGLE` | | `WebsiteSettingEvents::LIST_LOAD` | `Config::getWebsiteConfig()` | `WebsiteSettingLoadEvent::TYPE_LIST` | | `WebsiteSettingEvents::DATA_LOAD` | `Config::getWebsiteConfigValue($key)` | `WebsiteSettingLoadEvent::TYPE_DATA` | **Mutation events** fire a `WebsiteSettingEvent`: | Constant | Fired by | |-------------------------------------|------------| | `WebsiteSettingEvents::PRE_ADD` | `save()` | | `WebsiteSettingEvents::POST_ADD` | `save()` | | `WebsiteSettingEvents::PRE_UPDATE` | `save()` | | `WebsiteSettingEvents::POST_UPDATE` | `save()` | | `WebsiteSettingEvents::PRE_DELETE` | `delete()` | | `WebsiteSettingEvents::POST_DELETE` | `delete()` | #### HTTP Cache When HTTP caching is enabled, website settings participate in tag-based cache invalidation automatically. The tag added to a response depends on which access path triggered the load: | Access | Tags added | |---------------------------------|------------------------| | `WebsiteSetting::getById($id)` | `website_setting_{id}` | | `opendxp_website_config('key')` | `website_setting_{id}` | | `opendxp_website_config()` | `website_setting_list` | When a setting is saved or deleted, both `website_setting_{id}` and `website_setting_list` are invalidated. > [!TIP] > Using `opendxp_website_config('key')` instead of `opendxp_website_config()` gives more granular cache invalidation: > only pages that loaded the changed setting are purged, not every page that loaded any setting. --- ## Custom Reports > [!CAUTION] > To use this feature, please enable the `OpenDxpCustomReportsBundle` in your `bundle.php` file and install it accordingly with the following command: > > `bin/console opendxp:bundle:install OpenDxpCustomReportsBundle` Custom Reports is a report engine directly integrated into OpenDXP. With Custom Reports it is possible to create tabular or chart reports (or both) with further filtering and export functionality. ![Custom Reports](../img/custom-reports.png) The data source for the reports is always a source adapter which is responsible for retrieving and preparing the report data. Currently two adapters ship with OpenDXP: - SQL: Retrieve Data based on a SQL statement ![Custom Reports Configuration](../img/custom-reports-config.png) - Google Analytics: Retrieve Data from Google Analytics only available if - Only available if the corresponding `OpenDxpGoogleMarketingBundle` is enabled. ### Custom Report Permissions With custom report permissions it is possible to define which users should be able to see a report. Following options are available: - `Share globally`: Custom report is visible to all users that have `reports` permission. - `Visible to users`: Custom report is visible to all listed users. - `Visible to roles`: Custom report is visible to all listed roles. ### Custom Data Source Adapters It is easily possible to implement custom source adapters for special use cases. To do so following steps are necessary: - JavaScript Class: This class defines the user interface in the configuration of the custom report. It has to be located in the namespace `opendxp.bundle.customreports.custom.definition`, named like the adapter (e.g. `opendxp.report.custom.definition.mySource`) and implement the methods `initialize`, `getElement` and `getValues`. As sample see [sql.js](https://github.com/open-dxp/opendxp/blob/1.x/bundles/CustomReportsBundle/public/js/opendxp/report/custom/definitions/sql.js) - PHP Adapter Class: This class is the server side implementation of the adapter. It is responsible for retrieving and preparing the options, columns and data. It has to extend the abstract class `OpenDxp\Model\Tool\CustomReport\Adapter\AbstractAdapter` (or implement `OpenDxp\Model\Tool\CustomReport\Adapter\CustomReportAdapterInterface`). As examples see [Analytics adapter](https://github.com/open-dxp/google-marketing-bundle/blob/1.x/src/CustomReport/Adapter/Analytics.php) and [Sql adapter](https://github.com/open-dxp/opendxp/blob/1.x/bundles/CustomReportsBundle/src/Tool/Adapter/Sql.php). - Register your Adapter Factory as Service - If you are using a simple adapter class without dependency injection parameters, you can use the `DefaultCustomReportAdapterFactory` providing the adapter class' FQN as single argument ```yml app.custom_report.adapter.factory.custom: class: OpenDxp\Bundle\CustomReportsBundle\Tool\Adapter\DefaultCustomReportAdapterFactory arguments: - 'App\CustomReport\Adapter\Custom' ``` - If you are using a more complex adapter, you can create your own factory by implementing the interface `OpenDxp\Bundle\CustomReportsBundle\Tool\Adapter\CustomReportAdapterFactoryInterface` - Add your Adapter Factory to the configuration: ```yml opendxp_custom_reports: adapters: myAdapter: app.custom_report.adapter.factory.custom ``` ### Custom JS Class for Report Visualization If you need to fully customize the appearance of the report, you can specify a custom java script class that should be used when opening the report in OpenDXP Backend. This class can be specified in `Report Class` option and should extend the default java script class for the reports which is `opendxp.bundle.customreports.custom.report`. --- ## Rendering PDFs Instead of directly returning the HTML code of your website you could also return a PDF version. You can use the OpenDxpWebToPrintBundle functionality to accomplish this. Please make sure that you have set up and installed the OpenDxpWebToPrintBundle correctly ("Settings" -> "Web2Print Settings"). You need to enable and install the OpenDxpWebToPrintBundle via the bundles.php, and then you just have to provide the correct settings (Tool -> PDFreactor / Chromium / Gotenberg) and the corresponding settings. In your controller you just have to return the PDF instead of the HTML. ### Simple example ```php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class BlogController extends FrontendController { public function indexAction(Request $request): Response { //your custom code.... //return the pdf $html = $this->renderView(':Blog:index.html.php', [ 'document' => $this->document, 'editmode' => $this->editmode, ]); return new Response( \OpenDxp\Bundle\WebToPrintBundle\Processor::getInstance()->getPdfFromString($html), 200, array( 'Content-Type' => 'application/pdf', ) ); } ``` ### Advanced example ```php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class BlogController extends FrontendController { public function indexAction(Request $request): Response { //your custom code.... //return the pdf $params = [ 'document' => $this->document, 'editmode' => $this->editmode, ]; $params['testPlaceholder'] = ' :-)'; $html = $this->renderView(':Blog:index.html.php', $params); $adapter = \OpenDxp\Bundle\WebToPrintBundle\Processor::getInstance(); //add custom settings if necessary if ($adapter instanceof \OpenDxp\Bundle\WebToPrintBundle\Processor\PdfReactor) { //Config settings -> http://www.pdfreactor.com/product/doc/webservice/php.html#Configuration $params['adapterConfig'] = [ 'author' => 'Max Mustermann', 'title' => 'Custom Title', 'javaScriptMode' => 0, 'addLinks' => true, 'appendLog' => true, 'enableDebugMode' => true ]; } elseif ($adapter instanceof \OpenDxp\Bundle\WebToPrintBundle\Processor\Gotenberg) { $params = Config::getWeb2PrintConfig(); $params = json_decode($params['gotenbergSettings'], true) ?: []; } elseif ($adapter instanceof \OpenDxp\Bundle\WebToPrintBundle\Processor\Chromium) { $params = Config::getWeb2PrintConfig(); $params = json_decode($params['chromiumSettings'], true) ?: []; } return new Response( $adapter->getPdfFromString($html, $params), 200, array( 'Content-Type' => 'application/pdf', // 'Content-Disposition' => 'attachment; filename="custom-pdf.pdf"' //direct download ) ); } ``` --- ## Cloning Elements Use ```php $new = OpenDxp\Model\Element\Service::cloneMe($source) ``` to get a safe copy of the original element (everything that implements ElementInterface). Note that this will not update any internal references. For example: A relation inside the source element pointing to the source element will still reference the source element in the copy. If you want to get a persistent copy use the `copyAsChild`method of the corresponding service. E.g. ```php $user = \OpenDxp\Model\User::getById(123); $assetService = new \OpenDxp\Model\Asset\Service($user); $assetService->copyAsChild($target, $source); $documentService = new \OpenDxp\Model\Document\Service($user); $documentService->copyAsChild($target, $source); // additional arguments are available for inheritance, ... $objectService = new \OpenDxp\Model\DataObject\Service($user); $objectService->copyAsChild($target, $source); ``` where `$source`is the source element and `$target` the parent element of the new element. This will also create a unique element key (or filename for asset elements). If you also want to update the references there is a helper method which accomplishes this for you. Just call the service's `rewriteIds` and provide a mapper config. Example: ```php $rewriteConfig = array( "object" => array( 176 => 190 ) ); $object = DataObject\Service::rewriteIds($object, $rewriteConfig); ``` meaning that in the copy everything point to object with ID 176 will be replaced with a reference pointing to object 190. --- ## Permission Analyzer Allows you to drop an element (plus optionally a user) and display the calculated workspace permissions. If no user is specified this is done for all users. In addition, the general user permissions can be displayed. When you expand a result row you will see a detailed overview which tells you which rule (path, user or role and which one) has been applied. How to launch it: ![Example](../img/permission_analyzer_menu.png) How it looks like: ![Example](../img/permission_analyzer.png) --- ## GDPR Data Extractor The GDPR Data Extractor is a tool that helps the user to full fill the *right of access by the data subject* and helps to export data that is stored for a specific person in different data sources like `data objects`, `sent mails`, `OpenDXP backend user`, etc. ![GDPR Data Extractor](../img/gdpr-data-extractor.jpg) ### Configuration Via the configuration, following options can be set to modify the behaviour of the Data Extractor: * What data object classes should be included (e.g. exclude data object classes without personal information like products) * What relation attributes should included recursively into the data export (e.g. include order items into export of orders) * Allow deletion of data object directly in result view For Details see configuration reference as follows: ```yml # Default configuration for "OpenDxpAdminBundle" opendxp_admin: gdpr_data_extractor: # Settings for DataObjects DataProvider dataObjects: # Configure which classes should be considered, array key is class name classes: # Prototype: # MY_CLASS_NAME: # include: true # allowDelete: false # includedRelations: # - manualSegemens # - calculatedSegments # - # Set if class should be considered in export. include: true # Allow delete of objects directly in preview grid. allowDelete: false # List relation attributes that should be included recursively into export. includedRelations: [] ``` OpenDXP ships with a reasonable default configuration. By using it, all data object classes are considered in the search, export concludes all attributes directly attached to the data object (no relations) and allows deletion of the data objects directly in the result list. > Please note: The GDPR search will be very limited if haven`t installed the simpleBackendSearchBundle! ### Extending GDPR Data Extractor with Custom Data Sources It is possible to attach additional data sources to the GDPR Data Extractor with OpenDXP Bundles. Thereby specific data exports can be attached or external data sources can be included. To do so, following steps are necessary: 1) Create a custom implementation of [`OpenDxp\Bundle\AdminBundle\GDPR\DataProvider\DataProviderInterface`](https://github.com/open-dxp/admin-bundle/blob/1.x/src/GDPR/DataProvider/DataProviderInterface.php#L20). The following functions need to be implemented: * `getSortPriority()` - Returns sort priority for the tabs - higher is sorted first. * `getName()` - Returns the name of the data provider. * `getJsClassName()` - Returns the name of the JavaScript class implementation for frontend presentation. 2) Implement the specified JavaScript class with all the user interface with following restrictions: * The constructor gets the current `searchParams` as parameter. * It needs to have a function `getPanel()` that returns a `Ext.Panel`. 3) Register your custom implementation as service. The service needs to be tagged with the tag `opendxp.gdpr.data-provider`. If you're using autoconfiguration this will be automatically done for you, otherwise you need to specify the tag in your service definition: ```yml # either enable autoconfigure as _defaults (or only for your service) services: _defaults: autoconfigure: true public: false App\GDPR\DataProvider\MyCustomDataProvider: ~ # or specify the tag manually if not using autoconfiguration services: _defaults: public: false App\GDPR\DataProvider\MyCustomDataProvider: tags: - { name: opendxp.gdpr.data-provider } ``` For an example see the implementation for the [customers data provider](https://github.com/open-dxp/customer-data-framework/blob/master/src/GDPR/DataProvider/Customers.php) in our customer management framework. --- ## Site Declarations > [!CAUTION] > To use this feature, please enable the `OpenDxpSeoBundle` in your `bundle.php` file and install it accordingly with the following command: > > `bin/console opendxp:bundle:install OpenDxpSeoBundle` A site declaration is a text file that every site serves under the same path. Editors maintain its content per site under *Marketing > Search Engine Optimization > Site Declarations*. ![Site Declarations Editor](../img/site-declarations-editor.png) | Name | Path | Enabled by default | |----------------|-----------------------------|--------------------| | `robots_txt` | `/robots.txt` | yes | | `security_txt` | `/.well-known/security.txt` | no | | `ads_txt` | `/ads.txt` | no | | `app_ads_txt` | `/app-ads.txt` | no | | `llms_txt` | `/llms.txt` | no | ### Enable a site declaration An enabled site declaration owns its path on every site. A document, a static route or a route of your own under the same path no longer answers. Enable a site declaration in the configuration: ```yaml opendxp_seo: site_declarations: security_txt: true robots_txt: false ``` A disabled site declaration has no route. Its path answers as if the site declaration did not exist. ### Edit a site declaration The permission `site_declarations` allows a user to edit every site declaration. The editor shows a tab for the main site and for every other site. A site without content of its own gets the default content of the site declaration. Only robots.txt has one: ``` User-agent: * Disallow: ``` Every other site declaration answers 404 for a site without content. A file under the same path in the `public` folder wins over the site declaration, because the web server delivers it before OpenDXP. The editor then disables saving. ### Placeholders A site declaration can offer placeholders. The editor shows them above the text field. A click inserts the placeholder at the cursor. The response replaces each placeholder with its current value. ### security.txt security.txt follows [RFC 9116](https://www.rfc-editor.org/rfc/rfc9116). The editor refuses content without `Contact`, without `Expires` or with more than one `Expires`. The placeholder `%expires%` turns into a date 364 days after the day of the request. The file therefore never expires: ``` Contact: mailto:security@example.com Expires: %expires% Preferred-Languages: en, de ``` A fixed date stays as it is. A signed file needs a fixed date. ### Sites Every site has its own content. A site without content does not fall back to the content of the main site. A host without a site gets the content of the main site. ### Caching The response carries `Cache-Control: private, no-store`. Neither the full page cache nor a proxy keeps it, so a saved change applies at once. ### Add a site declaration A bundle adds a site declaration with a service that implements `OpenDxp\Bundle\SeoBundle\SiteDeclaration\SiteDeclarationInterface`. Autoconfiguration registers it. ```php use OpenDxp\Bundle\SeoBundle\SiteDeclaration\SiteDeclarationInterface; final class AppleAppSiteAssociationDeclaration implements SiteDeclarationInterface { public function getName(): string { return 'apple_app_site_association'; } public function getPath(): string { return '/.well-known/apple-app-site-association'; } public function getContentType(): string { return 'application/json'; } public function getDefaultContent(): ?string { return null; } public function getPlaceholders(): array { return []; } public function validate(string $content): array { return []; } } ``` The project enables the site declaration in its configuration. A name that is not snake case, a name used twice or a path used twice fails when the cache is built. --- ## Sitemaps > [!CAUTION] > To use this feature, please enable the `OpenDxpSeoBundle` in your `bundle.php` file and install it accordingly with the following command: > > `bin/console opendxp:bundle:install OpenDxpSeoBundle` OpenDXP includes the [`presta/sitemap-bundle`](https://github.com/prestaconcept/PrestaSitemapBundle) which adds a simple, yet powerful API to generate XML sitemaps. Have a look at the bundle documentation on details how the bundle works and how you can add sitemaps to it. The bundle exposes a way to add sitemap entries by [firing an event](https://github.com/prestaconcept/PrestaSitemapBundle/blob/3.x/doc/4-dynamic-routes-usage.md) which you can handle to add entries to an `UrlContainerInterface`. For simple scenarios, you can directly implement such an event handler and start to add entries. ### Exposing Sitemaps Sitemaps can either be exposed by being generated on-the-fly or by being dumped to static files. What to use depends on the size of your site (e.g. the size of the tree which needs to be processed). In general it's recommended to create static files as it reduces the overhead of creating the sitemap on every crawler request. If you want to serve the sitemap directly, you need to register the sitemaps routes in your routing config (see [PrestaSitemapBundle Documentation](https://github.com/prestaconcept/PrestaSitemapBundle/blob/3.x/doc/1-installation.md) for details). ```yaml PrestaSitemapBundle: resource: "@PrestaSitemapBundle/config/routing.yml" prefix: / ``` After the route is registered, you should be able to access your sitemaps via `/sitemap.xml` and `/sitemap.
    .xml`. To dump the sitemaps to static files, use the `presta:sitemaps:dump` command: $ bin/console presta:sitemaps:dump Dumping all sections of sitemaps into public directory Created/Updated the following sitemap files: sitemap.default.xml sitemap.xml #### Configuring the scheme and host to be used by sitemaps As the command-line context does not know what scheme (http/https) and host to use for the absolute URLs of your sitemap, those values need to be configured. Symfony allows to set those parameters on the [Request Context](https://symfony.com/doc/current/routing.html#generating-urls-in-commands). If configured, OpenDXP will set the domain configured as main domain in system settings as default host. Those parameters will be overridden from the current request in the web context when using the on-the-fly method by adding the route. When using the `presta:sitemaps:dump` command, you can override those parameters by passing the `--base-url` option: $ bin/console presta:sitemaps:dump --base-url=https://opendxp.io/ For details see: * [Bundle Documentation](https://github.com/prestaconcept/PrestaSitemapBundle/blob/3.x/doc/2-configuration.md#configuring-your-application-base-url) * [Symfony Documentation on the Request Context](https://symfony.com/doc/current/routing.html#generating-urls-in-commands) * [`UrlGenerator`](https://github.com/open-dxp/opendxp/blob/1.x/bundles/SeoBundle/src/Sitemap/UrlGenerator.php) ### Sitemap Generators OpenDXP adds a way to hook one or more generators into the sitemap generation process. Such generators can be registered, ordered by priority and enabled/disabled via config. The basic generator interface defines a single `populate()` method which is expected to add entries to the URL container: ```php setOrderKey('date'); $list->setOrder('DESC'); // the context contains metadata for filters/processors // it contains at least the url container, but you can add additional data // with the params parameter $context = new GeneratorContext($urlContainer, $section, ['foo' => 'bar']); /** @var BlogArticle $blogArticle */ foreach ($list as $blogArticle) { // only add element if it is not filtered if (!$this->canBeAdded($blogArticle, $context)) { continue; } // use a link generator to generate an URL to the article // you need to make sure the link generator generates an absolute url $link = $blogArticle->getClass()->getLinkGenerator()->generate($blogArticle, [ 'referenceType' => UrlGeneratorInterface::ABSOLUTE_URL ]); // create an entry for the sitemap $url = new UrlConcrete($link); // run url through processors $url = $this->process($url, $blogArticle, $context); // processors can return null to exclude the url if (null === $url) { continue; } // add the url to the container $urlContainer->addUrl($url, $section); } } } ``` The `AbstractElementGenerator` exposes the methods `canBeAdded()` and `process()` to run the entry through filters and processors. If you handle nested tree structures, you can also use `handlesChildren()` to test if children should be handled. All 3 methods accept a `GeneratorContextInterface` object which you can use to pass context metadata to filters and processors. For example, the `DocumentTreeProcessor` uses the context to define the site the document lives in. In the example above, the URL is created by using a [Link Generator](../05_Objects/01_Object_Classes/05_Class_Settings/30_Link_Generator.md). > It's important that your link generator is able to generate an absolute URL for the given object. Above is only an example. After creating the generator, register it as service and add it to the config. Use filters and processors to reuse already implemented behaviour. ```yaml # services.yaml services: _defaults: autowire: true autoconfigure: true public: false App\Sitemaps\BlogGenerator: arguments: $filters: - '@OpenDxp\Bundle\SeoBundle\Sitemap\Element\Filter\PublishedFilter' - '@OpenDxp\Bundle\SeoBundle\Sitemap\Element\Filter\PropertiesFilter' $processors: - '@OpenDxp\Bundle\SeoBundle\Sitemap\Element\Processor\ModificationDateProcessor' - '@OpenDxp\Bundle\SeoBundle\Sitemap\Element\Processor\PropertiesProcessor' ``` Make the generator available to the core listener by registering it on the configuration: ```yaml # config.yaml opendxp_seo: sitemaps: generators: app_blog: generator_id: App\Sitemaps\BlogGenerator ``` ##### Creating a custom filter Filters can be created by implementing the `FilterInterface`. An example filter excluding any element with a modification date older than a year could look like the following: ```php maxYears = $maxYears; } public function canBeAdded(ElementInterface $element, GeneratorContextInterface $context): bool { $modicationDate = \DateTimeImmutable::createFromFormat(DateFormat::UNIX_TIMESTAMP, (string)$element->getModificationDate()); $now = new \DateTimeImmutable(); $diff = $modicationDate->diff($now); // exclude element if years is more than the configured amount return $diff->y < $this->maxYears; } public function handlesChildren(ElementInterface $element, GeneratorContextInterface $context): bool { // not matching the age constraint does not mean not handling children return true; } } ``` Now you can define the filter as service and use it in your generators: ```yaml services: _defaults: autowire: true autoconfigure: true public: false App\Sitemaps\Filter\AgeFilter: ~ App\Sitemaps\BlogGenerator: arguments: $filters: - '@App\Sitemaps\Filter\AgeFilter' ``` ##### Creating a custom processor Creating a processor is very similar to creating a filter. As example, let's create a processor which adds a random priority to each entry. ```php setPriority(rand(0, 10) / 10); } // important: return an Url instance to be added. if your // processor returns null it will be omitted. return $url; } } ``` > It's important that a processor returns an Url instance as otherwise it will be omitted. You can use this in your own processors to apply some kind of filtering on the processor level or to return a different instance from your processor. A typical use case would be to use an [Url Decorator](https://github.com/prestaconcept/PrestaSitemapBundle/blob/3.x/doc/5-decorating-urls.md) in a processor and to return its instance instead of the original Url. Again, define it as service and start using it from your generators: ```yaml services: _defaults: autowire: true autoconfigure: true public: false App\Sitemaps\Processor\RandomPriorityProcessor: ~ App\Sitemaps\BlogGenerator: arguments: $processors: - '@App\Sitemaps\Processor\RandomPriorityProcessor' ``` #### Generating absolute URLs To generate absolute URLs, OpenDXP defines an [url generator](https://github.com/open-dxp/opendxp/blob/1.x/bundles/SeoBundle/src/Sitemap/UrlGenerator.php) which, given a path, takes care of creating an absolute URL based on the [Request Context](https://symfony.com/doc/current/routing.html#generating-urls-in-commands). As example how to use the URL generator in a processor: ```php urlGenerator = $urlGenerator; } public function process(Url $url, ElementInterface $element, GeneratorContextInterface $context): UrlConcrete { $path = $this->urlGenerator->generateUrl('/foo/bar'); $url = new UrlConcrete($path); return $url; } } ``` --- ## Two Factor Authentication since build 256 OpenDXP has an integrated two factor authentication using the Google Authenticator ([Android](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2), [iOS](https://itunes.apple.com/at/app/google-authenticator/id388497605)) ### User Setup By default every user can enable or disable their two factor authentication freely in the profile settings. ![Settings](../img/Icon_settings.png) **(Settings -> My Profile)** After enabling it a secret will be generated and you can setup your Google Authenticator App. **Please be aware if you don't setup the App properly you will loose access to your account!** ![2fasetup](../img/two_factor_authentication_setup.png) After reloading you will be prompt to enter the verification code for the first time. ### Admin Setup It is also possible to force users to use two factor authentication. This can be done in the Users menu by checking 'Two Factor Authentication required'. ![Settings](../img/Icon_settings.png) **(Settings -> Users / Roles -> Users)** ![2farequired](../img/two_factor_authentication_required.png) If this is enabled the user will have to setup two factor authentication and cannot disable it anymore. ### Config If you want to change the default name / description that is displayed in the app you can do this by overwriting the following config: ```yaml scheb_two_factor: google: server_name: OpenDXP # Server name used in QR code issuer: OpenDXP 2 Factor Authentication # Issuer name used in QR code ``` ![Settings](../img/two_factor_authentication_app_descriptions.png) --- ## Notifications Feature allows to send notifications to user. `Notifications` adds to status bar new clickable icon, on click it opens new tab with all notifications, also it contains badge with unread notifications count. When there's new notification for user, it shows as window with possibility to close it, mark as read or open details. User can use `Share via Notifications` button in order to open a new notification window and pre-fill the attachment field with desired element. ### Working with Notifications via API #### Overview For accessing and working with tags via API, take a look into `OpenDxp\Model\Notification\Service\NotificationService`. Be aware that the service is tagged as internal and can change in future releases. ```php $filter * @param array{offset?: int|string, limit?: int|string|null} $options * * @return array{total: int, data: Notification[]} * * @throws Exception */ public function findAll(array $filter = [], array $options = []): array { $listing = new Listing(); $conditions = []; $conditionVariables = []; foreach ($filter as $key => $value) { if (isset($value['condition'])) { $conditions[] = $value['condition']; $conditionVariables[] = $value['conditionVariables'] ?? []; } else { $conditions[] = $key . ' = :' . $key; $conditionVariables[] = [$key => $value]; } } $condition = implode(' AND ', $conditions); $listing->setCondition($condition, array_merge(...$conditionVariables)); $listing->setOrderKey('creationDate'); $listing->setOrder('DESC'); $offset = $options['offset'] ?? 0; $limit = $options['limit'] ?? null; if (is_string($offset)) { //TODO: Trigger deprecation $offset = (int) $offset; } if (is_string($limit)) { //TODO: Trigger deprecation $limit = (int) $limit; } $this->beginTransaction(); $result = [ 'total' => $listing->count(), 'data' => $listing->getItems($offset, $limit), ]; $this->commit(); return $result; } ``` If you want to send some notifications to user: ```php sendToUser( 4, // User recipient 2, // User sender 0 - system 'Example notification', 'Example message', $element // Optional linked element ); // ... } ``` If you want to send some notifications to users from group: ```php sendToGroup( 4, // Group recipient 2, // User sender 0 - system 'Example notification', 'Example message', $element // Optional linked element ); // ... } ``` #### Configuration The configuration allows enabling/disabling the *Notifications menu* in the toolbar and the *check of new notifications* (url: `/admin/notification/find-last-unread`). It is done in the `opendxp_admin` configuration in the `notifications` section. default: ```yaml opendxp_admin: notifications: enabled: true check_new_notification: enabled: true interval: 30 ``` ##### Example configurations: * Disable notifications menu and check of new unread notifications: ```yaml opendxp_admin: notifications: enabled: false ``` * Disable only the check of new unread notifications: ```yaml opendxp_admin: notifications: check_new_notification: enabled: false ``` * Change interval to fetch new unread notifications (in seconds): ```yaml opendxp_admin: notifications: check_new_notification: interval: 60 ``` --- ## Tools and Features This section of documentation gives an overview over tools and features provided in or for the OpenDXP backend UI but also can be used via OpenDXP PHP API. The topics include insights to [Versioning](./01_Versioning.md), [Notes and Events](./05_Notes_and_Events.md), [Tags](./09_Tags.md), [Perspectives](./13_Perspectives.md) and much much more. Just have a look at the sub pages and dive into the possibilities of OpenDXP. --- ## Database Model OpenDXP tries to keep a clean and optimized database model for managing the data. Nevertheless, there are quite a lot of tables around and finding the correct data might be a bit challenging at the beginning. Basically, there are two types of tables * Default tables which are created during install - for all sorts of data like assets, documents logs, versions, ... * Dynamically created tables which are created during object data model configuration - mainly for all object related data. ## Default Tables These tables are created during OpenDXP install and are always the same. | Table | Description | |-----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | application_logs | Contains all application logs. For more information see [Application Logger](../18_Tools_and_Features/17_Application_Logger.md). Additionally, there might be application_logs_archive* tables for old logging entries. | | assets | Assets (Images, etc.), with system metadata | | assets_metadata | Additional user metadata (Metadata tab in the asset panel) | | classes | List of all object classes with ID and name. Everything else is stored in PHP configuration files. | | classificationstore_collectionrelations | Relation Collection - Group for Classification Store | | classificationstore_collections | Collections of Classification Store | | classificationstore_groups | Groups of Classification Store | | classificationstore_keys | Keys of Classification Store | | classificationstore_relations | Relation Group - Key for Classification Store | | classificationstore_stores | Stores of Classification Store | | custom_layouts | Definition of the `custom layouts` for object classes | | dependencies | Stores dependencies between elements such as objects, assets, documents | | documents | List of all documents, folders, links, hardlinks, emails and snippets of the document area with meta- and config-data, relations | | documents_editables | Editables of documents (data), in a serialized form | | documents_email | Extra config data | | documents_hardlink | Extra config data | | documents_link | Extra config data | | documents_page | Extra config data | | documents_printpage | Extra config data | | documents_snippet | Extra config data | | documents_translations | Relation between same documents for different languages | | edit_lock | Tracks which user opened which resource in the backend | | element_workflow_state | Keeps track of workflow state for all elements | | email_blocklist | Blocklist for eMail-addresses | email_log | Log for sent emails | | glossary | Words to auto-link in texts. See [Glossary](../18_Tools_and_Features/21_Glossary.md) | | http_error_log | HTTP error log | | lock_keys | Store for Locking functionality | | notes | [Notes](../18_Tools_and_Features/05_Notes_and_Events.md) for elements | | notes_data | Additional data for notes | | objects | List of all objects with metadata like id, class name, path, parent, ... | | object_url_slugs | [URL Slug](../05_Objects/01_Object_Classes/01_Data_Types/65_Others.md) data | | properties | Data from the `properties` tab | | quantityvalue_units | Available quantities for quantity value object data type | | recyclebin | Stores metadata of deleted elements | | redirects | Stores redirects | | schedule_tasks | Stores scheduled tasks | | search_backend_data | Stores the index for the backend search - is a InnoDb Table with fulltext capabilities | | sites | Stores [sites](../02_MVC/04_Routing_and_URLs/08_Working_with_Sites.md) | | tags | Stores available [tags](../18_Tools_and_Features/09_Tags.md) | tags_assignment | Stores assignment of tags to elements | | tmp_store | OpenDXP internal tmp store | | tracking_events | | | translations_admin | Backend translations | | translations_messages | Frontend translations | | tree_locks | Locks in the tree of OpenDXP backend interface | | users | Backend users | | users_permission_definitions | List of globally assignable user permissions | | users_workspaces_asset | Stores user access permissions for asset folder | | users_workspaces_document | Stores user access permissions for document folders | | users_workspaces_object | Stores user access permissions for object folders | | uuids | stores Unique Identifiers - if enabled | | versions | List of object/asset/document versions. Actual data is serialized and written to disk | ## Object Tables These tables are created and modified dynamically during the configuration of the object data model. As a result, they look different on an every OpenDXP installation depending on the data model. #### Objects As soon as a new object class is created in OpenDXP, at least three tables are added to the database. The tables have a numerical suffix, denoting the number (id) of the object class: `object_query_(id)`, `object_relations_(id)`, `object_store_(id)` and an additional database view `object_(id)` which is a combination of `object_query_(id)` and `objects`. | Table / View | Description | |-------|-------------| | `object_(id)` View | Database view joining object_query_(id) and objects table | | `object_query_(id)` Table | Use this table to retrieve data incl. inherited data. Data types with relations are usually stored in a serialized form here, too. OpenDXP Object-Lists work with this table. | | `object_relations_(id)` Table | Contains data of fields with relations to objects, assets, etc. | | `object_store_(id)` Table | This is the main data storage table of an object class. It contains all "flat" data without any relations or external dependencies. | | `objects` Table | Contains an entry for each and every object in the system. The id field is an auto_increment and the source of the primary key for an object. Metadata about an object is stored in this table, too. | > When restore of query tables is necessary (for what ever reason) calling `DataObject\Concrete::disableDirtyDetection();` and > saving all data objects of class will do the trick. When not disabling dirty detection, there might be data missing in query table. ##### Simple Data Field Types Following is an overview of how different object data types are stored in the database. This overview might not be complete. This overview might be a useful starting point when querying object data with object lists. ###### Text Table: object_store_(id) | Name | Data Type | Default | Comment | | ---- | --------- | ------- | ------- | | Input | varchar(255) | NULL | / | | Textarea | longtext | NULL | / | | wysiwyg | longtext | NULL | Text with HTML-tags | | password | varchar(255) | NULL | Password - as hash | ###### Number Table: object_store_(id) | Name | Data Type | Default | Comment | | ---- | --------- | ------- | ------- | | Number | double/decimal(64,3) | NULL | Datatype depends on selected precision | | Slider | double | NULL | / | ###### Date Table: object_store_(id) | Name | Data Type | Default | Comment | | ---- | --------- | ------- | ------- | | Date | bigint(20) | NULL | < 1970 = negative Timestamp | | Date & Time | bigint(20) | NULL | < 1970 = negative Timestamp | | Time | varchar(5) | NULL | String - e.g.: "12:00" | ###### Select Table: object_store_(id) | Name | Data Type | Default | Comment | | ---- | --------- | ------- | ------- | | Select | varchar(255) | NULL | Selected value | | User | varchar(255) | NULL | OpenDXP User-ID | | Country | varchar(255) | NULL | Country code | | Language | varchar(255) | NULL | Language code | | Multiselection | text | NULL | String, selected values, separated by "," | | Countries (Multiselect) | text | NULL | String, selected language-codes, separated by "," | | Languages (Multiselect) | text | NULL | String, selected language-codes, separated by "," | ###### Relations Table: object_relations_(id) & object_meta_data_(id) * Data fields of relation types are stored in extra tables * Data fields are not stored in distinct columns, but as rows, whereas the field name is in an extra column `fieldname` * The column `type` specifies the type of the linked resource (Object, Document, Asset) * The columns `src_id` and `dest_id` define the relation / the link between the objects. * Column `index` is used to specify the order of the relations * Columns `ownertype`, `ownername` and `position` are used when relations are within field collections, localized fields, object bricks, etc. * The data type `Advanced Many-To-One Object Relation` stores the extra data in a table `object_meta_data_(id)` - the column `column` specifies the name of the meta item and `data` stores the value ###### Structured | Name | Comment | | ---- | ------- | | Table | Table data is stored as a string - serialized. | | Structured Table | Each table cell is stored distinctively; schema: (fieldname)__(row key)#(column key) | | Field-Collections | see special data fields later | | Objectbricks | see special data fields later | | Localized Fields | see special data fields later | ###### Geographic Table: object_store_(id) | Name | Data Type | Default | Comment | | ---- | --------- | ------- | ------- | | Geographic Point | double | NULL | Creates two columns: ‘(name)__longitude’ and ‘(name)__latitude’ | | Geographic Bounds | double | NULL | Creates four columns: ‘(name)__NElongitude’, ‘(name)__NElatitude’, ‘(name)__SWlongitude’ und ‘(name)__SWlatitude’ | | Geographic Polygon | longtext | NULL | Serialized geo-data | ###### Other | Name | Data Type | Default | Comment | | ---- | --------- | ------- | ------- | | Image | int(11) | NULL | ID of the image asset | | Image Advanced | int(11), text | NULL | Creates a column `(name)__image`(int) for the image assets id and the column `(name)__hotspots`(text). Hotspots are stored serialized. | | Video | text | NULL | Serialized data | | Checkbox | tinyint(1) | NULL | Boolean value (1 = true) | | Link | text | NULL | Serialized data | ##### Special Data Fields ###### Objectbricks | Table/View | Purpose | | ---------- | ------- | | object_brick_query_(id) Table | Analog to object_query_(id) | | object_brick_store_(id) Table | Main data storage | ###### Localized fields | Table/View | Purpose | | ---------- | ------- | | object_localized_(id)_(language-code) View | A database view per language, combining regular and localized data fields | | object_localized_data_(id) Table | Stores localized field data | | object_localized_query_(id)_(language-code) Table | Analog to object_query_(id) | ###### Field Collections | Table/View | Purpose | | ---------- | ------- | | object_collection_(collection-name)_(object-id) | Stores data of the field collections fields and the order (index) | --- ## Doctrine Schema Filter OpenDXP registers a DBAL schema filter (`UnmanagedTablesSchemaFilter`) that limits Doctrine's view of the database to only the tables it manages as ORM entities. When active, any table not mapped to a Doctrine entity is invisible to schema comparisons. This prevents `doctrine:schema:update` from generating `DROP TABLE` statements for tables that OpenDXP or third-party bundles manage outside of the ORM (e.g. via raw SQL or a separate migration system). ### Default behaviour The filter is **disabled by default**. It activates automatically for: - `doctrine:schema:update` - `doctrine:schema:validate` - Any console command implementing `ExcludesUnmanagedTablesInterface` At runtime (outside of these commands) all tables are visible, which is required for features that inspect the schema directly (e.g. checking whether a table already exists). ### ExcludesUnmanagedTablesInterface ``` OpenDxp\Bundle\CoreBundle\Doctrine\ExcludesUnmanagedTablesInterface ``` Implement this marker interface on a console command that calls `SchemaTool::updateSchema()` directly. It signals the filter to activate for the duration of that command — the same protection that `doctrine:schema:update` gets automatically. Without the filter, `SchemaTool::updateSchema()` compares all database tables against the provided metadata and generates `DROP TABLE` statements for every table it does not recognise. #### When to use it Use it whenever a command calls `SchemaTool::updateSchema()` or `SchemaTool::getUpdateSchemaSql()` with a partial set of metadata (i.e. not all ORM entities, but only those relevant to the command). #### Example ```php use OpenDxp\Bundle\CoreBundle\Doctrine\ExcludesUnmanagedTablesInterface; use Symfony\Component\Console\Command\Command; final class CreateDatabaseTablesCommand extends Command implements ExcludesUnmanagedTablesInterface { // ... } ``` --- ## Logging(Development_Tools_and_Details) There are several different kinds of logs in OpenDXP. All of them are located under `/var/log` and get rotated as well as compressed automatically on every day (7 days retention) by the maintenance command. ### `.log` This is definitely one of the most important logs and also the default logging location. OpenDXP uses Symfony default monolog logging with following channels: `opendxp`, `opendxp_api`, `session`. For details see [Symfonys monolog docs](https://symfony.com/doc/current/logging.html). #### Context of a log entry Every log entry carries its context in the field `extra` at the end of the line: | Key | Content | |------------|------------------------------------------------------------| | `token` | The user of the request and the roles of the user | | `requests` | The controller, the route and the parameters of the route | | `command` | The name and the arguments of the console command | An error in the admin interface: ```text [2026-10-14T15:17:46+02:00] request.ERROR: Uncaught PHP Exception ...DocumentNotFoundException: "Document with id 99999999 not found" at GetDocumentDataHandler.php line 50 {"exception":"..."} {"token":{"authenticated":true, "roles":["ROLE_OPENDXP_ADMIN"],"user_identifier":"admin"},"requests":[{"controller":"...DocumentController:: getDataByIdAction","route":"opendxp_admin_document_document_getdatabyid","route_params":[]}]} ``` An entry of a console command: ```text [2026-10-14T15:18:04+02:00] app.DEBUG: Successfully released the "opendxp:thumbnails:image" lock. {...} {"token":null,"command":{"name":"opendxp:thumbnails:image","arguments":{"command":"opendxp:thumbnails:image"}}} ``` The IP address of a request is personal data, so OpenDXP leaves it out. A project adds it together with the URL and the method of the request with the `WebProcessor` of Symfony: ```yaml services: Symfony\Bridge\Monolog\Processor\WebProcessor: tags: [monolog.processor] ``` ### php.log By default OpenDXP writes PHP-Engine Log Messages to the file `php.log`. You can change this by add the following to your symfony config: ```yaml monolog: handlers: error: type: stream path: "%kernel.logs_dir%/own_php.log" level: error ``` ### usagelog.log In this log you can find every action done within the OpenDXP Backend Interface. It can be deactivated by configuring `disable_usage_statistics` in `config/config.yaml`: ```yaml opendxp: general: disable_usage_statistics: true ``` ###### Example Entry: ``` 2021-04-26T13:18:35+0200 : 2|OpenDxp\Bundle\AdminBundle\Controller\Admin\Document\PageController::saveAction|opendxp_admin_document_page_save|{"task":"publish","id":"1","data":"{\"cImage_0\":{\"data\":{\"id\":337,\"path\":\"\\\/..."} 2021-04-26T13:18:35+0200 : 2|OpenDxp\Bundle\AdminBundle\Controller\Admin\Asset\AssetController::getImageThumbnailAction|opendxp_admin_asset_getimagethumbnail|{"id":"3","alt":"","height":"undefined","thumbnail":"portalCarousel","opendxp_editmode":"1"} ``` ###### Explanation | Value (from the example above) | Description | |-----------------------------------------------------------------------------------|-------------------------------------------| | `2021-04-26T13:18:35+0200` | Timestamp | | `2` | User-ID | | `OpenDxp\Bundle\AdminBundle\Controller\Admin\Document\PageController::saveAction` | Module\Controller::Action | | `opendxp_admin_document_page_save` | Route name | | `\{"task":"pub .... \}` | Request Parameters (shortened & censored) | ### redirect.log Sometimes it's necessary to debug redirects, for example when a redirect ends in an infinite loop. In this log you can see every request where a redirect takes action. ###### Example ``` 2021-04-26T14:03:20+0200 : 10.242.2.255 Custom-Redirect ID: 1, Source: /asdsad/redirectsource/asd -> /en/Events ``` > [!NOTE] > Redirects are logged into a `redirect` monolog log channel at info level. By default, OpenDXP logs that channel into `var/log/redirect.log`. > Of course, the corresponding monolog handler configuration can be adapted as needed. ### Writing Your Own Log Files To create a custom log entry, we need to create the monolog log channels and log handlers configuration. Here is an example on how to log in a custom filename called `custom.log` ```yaml monolog: handlers: custom_handler: level: debug type: stream path: '%kernel.logs_dir%/custom.log' channels: [custom_log] channels: [custom_log, some_other_channel] ``` It is possible to inject the `Psr\Log\LoggerInterface` by changing the variable name eg. `$customLogLogger` (camel case channel name + `Logger`) and Symfony will automatically wire the specified channel. ```php class SomeService { public function __construct(\Psr\Log\LoggerInterface $customLogLogger) { $customLogLogger->debug('Test Message'); } } ``` For more, please refer to [Monolog Documentation](https://symfony.com/doc/6.2/logging/channels_handlers.html) --- ## 01_Jobs ### Define Jobs Jobs are defined and configured via `OpenDxp\Bundle\GenericExecutionEngineBundle\Model\Job` objects which contain a name, steps (with defined message class and optional step specific configuration), selected elements and environment data (e.g. content that is entered by a user and that should be available in job step handlers). Create a job as follows ```php $job = new Job( 'my-first-job', [ new JobStep('Step 1', MyFirstTestMessage::class, '', [], StepSelectionMode::FOR_EACH), new JobStep('Step 2', MySecondTestMessage::class, '', [], StepSelectionMode::FOR_EACH), ], [new ElementDescriptor('object', 234)], [ 'foo' => 'bar' ] ); ``` ### Executing Jobs Execution of jobs is done via [`OpenDxp\Bundle\GenericExecutionEngineBundle\Agent\JobExecutionAgentInterface`] service, which provides all sorts of methods for executing and managing running jobs. To execute a job use the `startJobExecution` method which accepts 3 arguments: 1. The job object 2. Owner ID (optional) - the ID of the user who owns the job run 3. Execution context (optional) - the context in which the job should be executed. This is used for example to get the translation domain (by default admin) for localized messages. ```php $jobExecutionAgent->startJobExecution($job, null, 'my-custom-context'); ``` > [!CAUTION] > Be aware that the execution engine does not retry failed messages. > > ```yaml > opendxp_generic_execution_engine: > dsn: 'doctrine://default?queue_name=opendxp_generic_execution_engine' > retry_strategy: > max_retries: 0 # no retries to prevent data corruption > ``` After starting the job execution, the job run is created and the job steps are executed based on the configuration. For further information on how to handle job runs (cancel, stop, ...), see [Job Runs](./02_JobRun.md). ### Report from a Handler A handler of a job step gets the `JobProgress` of its job run as an additional argument: `__invoke(ExportMessage $message, JobProgress $progress)`. It reports progress, status line and result like any tracked code. See [Show the progress](03_Track_Background_Work.md#show-the-progress). ### Start a Job from the Admin An action in the admin starts its job through a route of your bundle. The route answers with the ID of the job run: ```php #[Route('/admin/my-bundle/delete-elements', name: 'my_bundle_delete_elements', methods: ['POST'])] public function deleteElementsAction(Request $request, JobExecutionAgentInterface $jobExecutionAgent): JsonResponse { $jobRun = $jobExecutionAgent->startJobExecution( $this->createDeleteJob($request), $this->getAdminUser()->getId(), 'my_bundle_delete', ); return $this->json(['jobRunId' => $jobRun->getId()]); } ``` The button of the action calls the runner of the engine: ```js opendxp.bundle.genericexecutionengine.jobrun.runner.start({ url: Routing.generate('my_bundle_delete_elements'), params: {ids: selectedIds.join(',')}, title: t('delete'), message: t('my_bundle_delete_started') }); ``` - The runner shows the message and hands the job run to the menu in the sidebar. The menu shows its progress. - A file of the result arrives as a download in the browser tab that started the job. - The job run needs the user as its owner. A job run without an owner never appears in the menu. - An execution context with `disposable: true` removes the job run once the user picked up its result. See [Configuration](../02_Configuration/02_Configuration.md). --- ## 02_JobRun ### Job Runs Job Runs are the entity for storing information about runs of a job. There is the [`OpenDxp\Bundle\GenericExecutionEngineBundle\Repository\JobRunRepositoryInterface`] for all kind of CRUD operations on job runs. #### Localization of Current Message The current message of a job run can be localized. That means, that in user interface, the message is translated into the users' language. To ease handling of these messages, the `JobRunRepository` provides a specialized `updateLogLocalized` method, which helps you to create a localized log entry. It writes the untranslated message to the job run object, but translates the message to english and adds it to the job run log, based on the execution context of the Job Run. You can pass the `message` to the method, which then again can be translated using OpenDXP's `Translations` menu by selecting `your custom` domain. In addition, it is also possible to add a translation directly in the corresponding `your-domain..yaml` file. > [!NOTE] > By default, the admin domain is used for the translation. If you want to use a different domain, you can set it in the `opendxp_generic_execution_engine` configuration. As example see: ```php $this->jobRunRepository->updateLogLocalized( $jobRun, 'opendxp_copilot_job_execution_job_cancelled', ['%job_run_id%' => $jobRun->getId()] ); ``` ### Accessing JobStep in Handler The `JobStep` object can be accessed in the handler via the `getJobStep` method. This can be useful if you need to access the step configuration in the handler. ```php $jobRun = $this->getJobRun($message); $steps = $jobRun->getJob()?->getSteps(); if($steps !== null) { $step = $steps[$jobRun->getCurrentStep()] ?? null; if($step) { return $step->getSelectionMode(); } } ``` ### End of a Job Run A job run counts its open work: - the callback of `trackJob()`, while it runs - the dispatch of a step, while the engine dispatches its messages - every message with `JobRunMessageInterface` and the ID of the job run, until a worker handled it or gave it up for good The job run ends when its open work falls to zero. A job starts its next step at this point, and after its last step the job run ends. A message that Messenger tries again counts once. ### Job Run States The following states are available for a job run: - `running` - The job run has open work. - `finished` - The job run ended without an error. - `finished_with_errors` - Some messages failed, at least one succeeded. - `failed` - Every message failed, or the callback of `trackJob()` threw an exception. - `cancelled` - A user or the code cancelled the job run. With `stop_on_first_error`, the first error fails the job run. The `JobTrackingMiddleware` discards its other messages. ### Cancel Job Run To cancel a job run, use the `cancelJobRun` method of the `JobExecutionAgentInterface`: ```php $jobExecutionAgent->cancelJobRun($jobRun->getId()); ``` PHP cannot stop running code from outside, so the engine cancels in three ways: - The job run gets the state `cancelled` at once. - The next write of the `JobProgress` throws `JobRunStoppedException`. The engine does not count it as an error. Running code stops at its next report, at most a second later. - The `JobTrackingMiddleware` discards the waiting messages of the job run before their handler starts. The bus of the engine always has it. For your own bus, see [Continue in messages](03_Track_Background_Work.md#continue-in-messages). Code without a report runs to its end. The engine drops its result. ### Rerun Job Run To start a job again, use the `rerunJobRun` method of the `JobExecutionAgentInterface`. It starts a new job run with the job of the given one: ```php $jobExecutionAgent->rerunJobRun($jobRun->getId(), $ownerId); ``` The new job run repeats every step for every element with the input of the old one. Only the code that built the job knows whether this is safe, so the admin offers no rerun. ### Disposable Job Runs A job run in a disposable execution context disappears once its result is picked up. See [Discard job runs](../02_Configuration/02_Configuration.md#discard-job-runs). ### Delete Job Runs `JobExecutionAgentInterface::deleteJobRun()` deletes an ended job run with its error logs and its artifacts. It refuses a running job run. The maintenance deletes ended job runs after `delete_job_runs_older_than` and fails a running job run without activity after `fail_inactive_job_runs_after`. See [Configuration](../02_Configuration/02_Configuration.md). ### Adding additional log entries To update the log you have to inject the `JobRunExtractorInterface` and use its `logMessageToJobRun` method. This can be useful if you want to provide additional information about why a job run has was cancelled or failed. ```php $this->jobRunExtractor->logMessageToJobRun( $jobRun, 'translation_key', [ '%param1%' => $var1, '%param2%' => $var2 ] ); ``` ### Job Run Error Logs Job Run Error Logs are the entity for storing log information about Job Run. There is the [`OpenDxp\Bundle\GenericExecutionEngineBundle\Repository\JobRunErrorLogRepositoryInterface`] for all kind of CRUD operations on these logs. --- ## Track Background Work Your project runs work in the background: imports, syncs, cleanups. The engine shows such work as a job run in the admin. Your code keeps running where it runs today. The engine only follows it. ### Rules - A job run starts with `JobTrackingAgentInterface::trackJob()`. Nothing else starts one. - Code in a job run gets a `JobProgress` as an argument. It reports its progress and its result through it. - A message belongs to a job run when it implements `JobRunMessageInterface` and carries the ID of the job run. Its bus has the `JobTrackingMiddleware`. - A job run ends when its callback returned and every message of the job run is done. The agent works in every place: in a command, a service, a maintenance task, a scheduler task or a controller. ### Show the job run ```php use OpenDxp\Bundle\GenericExecutionEngineBundle\Agent\JobProgress; use OpenDxp\Bundle\GenericExecutionEngineBundle\Agent\JobTrackingAgentInterface; final readonly class ProductImport { public function __construct( private JobTrackingAgentInterface $jobTrackingAgent, ) { } public function import(): void { $this->jobTrackingAgent->trackJob('erp_product_import', function (JobProgress $progress): void { $this->importProducts(); }); } } ``` The admin now shows the job run, its end and its errors. - An exception in the callback fails the job run. The error log holds the message of the exception. The agent throws the exception on, so your code behaves as before. - The callback can also be a method: `$this->importProducts(...)` or `[$this, 'importProducts']`. - The admin shows the job name. It translates the name in the domain of the execution context. - `trackJob()` takes the ID of an owner as `ownerId`. A job run without an owner belongs to the system. - The callback runs in the process that calls `trackJob()`. In a web request, the browser waits for it. Long work runs in a command, a task or a worker, or it continues in messages. ### Show the progress ```php $this->jobTrackingAgent->trackJob('erp_product_import', function (JobProgress $progress): void { $progress->setTotal($this->erpClient->countProducts()); foreach ($this->erpClient->getProducts() as $product) { $this->importProduct($product); $progress->advance(); } }); ``` The admin shows the progress as "done / total" with a bar. | Method | Purpose | |---|---| | `setTotal(int $total)` | Sets the total, when your code knows it. | | `advance(int $steps = 1)` | Moves the progress forward. | | `setCurrentMessage(string $message, array $parameters = [])` | Sets the line that tells the user what happens now. | - A message is a translation key or a plain text. The admin translates it into the language of the viewer. - The `JobProgress` collects in memory and writes at most once per second. - Without `setTotal()`, the admin shows the progress without a bar. A user can cancel a running job run in the admin. The next call of the `JobProgress` then throws `JobRunStoppedException`. The agent catches it. Your code stops there, and its caller does not notice the cancel. Code without a call of the `JobProgress` runs to its end. ### Hand over files An artifact is a file that a job run hands over as its result. The admin offers each artifact for download: ```php use OpenDxp\Bundle\GenericExecutionEngineBundle\Model\JobRunArtifact; $progress->setResult( 'erp_product_import_finished', ['%count%' => $count], artifacts: [new JobRunArtifact('report.csv', fopen($path, 'rb'))], ); ``` - `setResult()` replaces an earlier result and its files. - The engine keeps artifacts in the temporary storage `opendxp.temp.storage`. With several servers, this storage must be shared. The artifacts of a job run disappear together with the job run. ### Continue in messages Work often continues in messages, and their handlers dispatch more messages. Each message of the job run implements `JobRunMessageInterface` and carries the ID of the job run: ```php use OpenDxp\Bundle\GenericExecutionEngineBundle\Messenger\Messages\JobRunMessageInterface; final readonly class ImportProductMessage implements JobRunMessageInterface { public function __construct( public ?int $jobRunId, public string $productNumber, ) { } public function getJobRunId(): ?int { return $this->jobRunId; } } ``` The callback dispatches the first messages. The ID comes from the `JobProgress`: ```php $this->jobTrackingAgent->trackJob('erp_product_import', function (JobProgress $progress): void { foreach ($this->erpClient->getProductNumbers() as $productNumber) { $this->messageBus->dispatch(new ImportProductMessage($progress->getJobRunId(), $productNumber)); } }); ``` Add the `JobTrackingMiddleware` to the bus of your messages: ```yaml framework: messenger: buses: messenger.bus.default: middleware: - 'OpenDxp\Bundle\GenericExecutionEngineBundle\Messenger\Middleware\JobTrackingMiddleware' ``` A handler then gets the `JobProgress` of the job run as an additional argument. It passes the ID on to the messages it dispatches: ```php #[AsMessageHandler] final readonly class ImportProductHandler { public function __invoke(ImportProductMessage $message, ?JobProgress $progress = null): void { $this->importProduct($message->productNumber); foreach ($this->findMissingVariants($message->productNumber) as $variantNumber) { $this->messageBus->dispatch(new ImportProductMessage($progress?->getJobRunId(), $variantNumber)); } } } ``` - The job run ends after its last message, also when handlers dispatch more messages on the way. - The admin counts the messages: "handled / dispatched". The total grows with every new message. - After a cancel, the middleware discards the waiting messages of the job run. - A message that Messenger tries again counts once. A message that fails for good lands in the error log. - A message with `null` belongs to no job run. Its handler gets `null` and runs as without the engine. - A handler that reports its own progress with `setTotal()` or `advance()` replaces the count of the messages. > [!NOTE] > Your bus may use `doctrine_transaction`. Put the `JobTrackingMiddleware` before it. A handler in the transaction > dispatches the messages of the job run with `DispatchAfterCurrentBusStamp`. Messenger then sends them after the > commit and not at all after a rollback. See "Transactional Messages" in the Symfony documentation. ### Set your own rules An execution context groups job runs and gives them rules. Pass its name to `trackJob()`: ```php $this->jobTrackingAgent->trackJob('erp_product_import', $callback, executionContext: 'erp'); ``` ```yaml opendxp_generic_execution_engine: execution_context: erp: disposable: true ``` A job run of a disposable context disappears once its result is picked up. A command that a cron starts every five minutes then keeps the admin clear. An unknown context throws `ExecutionContextNotDefinedException` at the start. See [Configuration](../02_Configuration/02_Configuration.md). ### Limits The count of a job run can go wrong in two cases: - A transport throws while it sends a message. The engine counted the message already. The job run stays running. Set `fail_inactive_job_runs_after` to fail such a job run after a while. - Code dispatches a message without `DispatchAfterCurrentBusStamp` in a database transaction, to a transport outside this transaction. The transaction rolls back. The message is out, but its count is gone. The job run then ends too early. --- ## Step configuration The configuration of a step is done via the `JobStep` object. The `JobStep` is part of the `Job` object and contains the following properties: - `name`: The name of the step. - `messageClass`: The message class that should be dispatched. - `configuration`: The configuration of the step. - `selectionMode`: The selection mode of the step. ### Name The name of the step is a string that is used to identify the step in the job run log. ### Message class The message class is the class of the message that should be dispatched when the step is executed. ### Configuration The configuration of a step is an array that can contain any kind of data that is necessary for the step handler to execute the step. Additionally, you can refer environment variables in the configuration by using the following syntax: `job_env('')`. ### Selection Processing mode The selection processing mode of a step is an enum that defines how the step should process the selected elements. - `SelectionProcessingMode::FOR_EACH`: The step is executed for each selected element. For example if you pass 10 selected elements to the job, the message gets dispatched 10 times and the step handler therefore is executed 10 times. Use `getSubjectFromMessage()` in `AbstractAutomationActionHandler` method to access the current element in the handler. - `SelectionProcessingMode::FOR_ALL`: The step is executed once for all selected elements. If you pass 10 selected elements to the job, the message gets dispatched once and the step handler therefore is executed once. Use `getSubjectsFromMessage()` in `AbstractAutomationActionHandler` method to access all elements in the handler. --- ## Working with the Generic Execution Engine Working with the Generic Execution Engine consists of the several steps. The following sections describe the most important aspects of the Generic Execution Engine. [Jobs](01_Jobs.md) [JobRun](02_JobRun.md) [Track Background Work](03_Track_Background_Work.md) --- ## Configuration of the Generic Execution Engine The Generic Execution Engine is configured via Symfony configuration files. Default configuration looks like this: ```yaml opendxp_generic_execution_engine: error_handling: 'continue_on_error' execution_context: default: translations_domain: admin ``` ### Define the error handling behavior There are currently two error handling strategies available: - `continue_on_error`: The job run continues when a message fails. - `stop_on_first_error`: The job run fails at the first error. A worker discards its other messages. You can define the global (used for all job runs as fallback) error handling strategy in the configuration file: ```yaml opendxp_generic_execution_engine: error_handling: 'stop_on_first_error' ``` ### Define the execution context Sometimes, it's necessary to customize your translation domain or error handling strategy, depending on your bundle or specific job run. You can achieve this by defining a custom execution context: ```yaml opendxp_generic_execution_engine: execution_context: my_custom_context: translations_domain: my_custom_domain error_handling: 'continue_on_error' ``` You can then pass the name of your execution context when defining a new job run: ```php $jobExecutionAgent->startJobExecution($job, $owner, 'my_custom_context'); ``` Based on the execution context, the translation domain and error handling strategy are set for the job run. By default, the `admin` translation domain is used. For error handling, the global strategy is the fallback. Its default is `continue_on_error`. A context can disappear from the configuration while its job runs still exist. These job runs get the defaults. ### Discard job runs A job run of a disposable execution context disappears once its result is picked up: ```yaml opendxp_generic_execution_engine: execution_context: my_export: translations_domain: admin disposable: true ``` | Case | Result | |-----------------------------------|---------------------------------------------------------------------------| | Each artifact was downloaded once | The job run and its artifacts are deleted after the last download. | | No artifacts, with an owner | The menu of the admin shows the end to the owner and deletes the job run. | | No owner, ended without failure | The job run is deleted at its end. | | Cancelled | The job run and its artifacts are deleted at once. | | Failed | The artifacts are deleted at once. The job run stays with its errors. | The maintenance deletes an ended disposable job run one day after its end. A context keeps its job runs by default. ### Clean up job runs The maintenance deletes ended job runs and fails running job runs without activity: ```yaml opendxp_generic_execution_engine: delete_job_runs_older_than: 604800 # 7 days fail_inactive_job_runs_after: 86400 # 1 day ``` - `delete_job_runs_older_than` deletes an ended job run after the given number of seconds. Without it, the engine keeps every job run outside a disposable context. - `fail_inactive_job_runs_after` fails a running job run when it showed no activity for the given number of seconds. A job run shows activity with every report and every finished message. Use a value above the longest silence of your code. Without it, a job run of a crashed worker stays running until a user cancels it. --- ## Extending Generic Execution Engine ### Extending Generic Execution Engine via Events Currently, it is possible to use the following event to extend the Generic Execution Engine: * `OpenDxp\Bundle\GenericExecutionEngineBundle\Event\JobRunStateChangedEvent` With this event it is possible to react to changes in the state of a job run. The event is dispatched whenever the state of a job run changes. The event object contains the job run ID, the previous state and the new state. #### Example The following example notifies a user via email when a job run fails. ```php 'onFailedState', ]; } public function onFailedState(JobRunStateChangedEvent $event) { $state = $event->getNewState(); if ($state !== 'failed') { return; } // Notify user about failed job run $mail = new Mail(); $mail->addTo('user@lorem.com', 'User'); $mail->setSubject('Job Run ' .$event->getJobRunId() . ' failed'); $mail->setBody('The job run ' . $event->getJobRunId() . ' failed. Please check the job run log for more information.'); $mail->send(); } } ``` --- ## Generic Execution Engine > [!CAUTION] > To use this feature, please update your `composer.json` by requiring `phpdocumentor/reflection-docblock` and `symfony/property-info` like in the `suggest` section. Enable the `OpenDxpGenericExecutionEngineBundle` in your `bundles.php` file and install it accordingly with the following command: > > > `bin/console opendxp:bundle:install OpenDxpGenericExecutionEngineBundle` The Generic Execution Engine shows background work as job runs in the admin. A job run has a state, a progress, errors and a result. Work becomes a job run in two ways: - The engine runs a [job](01_Jobs_and_Jobruns/01_Jobs.md). A job has steps, and the engine dispatches a message for each step and selected element. - The engine tracks your own code. See [Track Background Work](01_Jobs_and_Jobruns/03_Track_Background_Work.md). Both ways lead to the same [job runs](01_Jobs_and_Jobruns/02_JobRun.md). The admin shows them, a user cancels them, and the engine cleans them up. ### See what runs The admin lists job runs under "Extras" > "Background Jobs": ![Background Jobs in the admin](../../img/GenericExecutionEngine_job_runs_panel.png) - A double click on a job run opens its log with its errors. - A running job run can be cancelled. An ended one can be deleted. - The files of a job run are offered for download. - The permission "Background Jobs" opens the list with the own job runs. With "See all Background Jobs", a user sees every job run, also those without an owner. An icon in the sidebar shows the own job runs to every user, also without a permission: - A counter shows how many of them run. - The menu of the icon shows their progress and lets the user cancel them. - A finished job run of a disposable context stays in the menu until the user downloads its files or removes it. - The admin reports the end of each job run with a notification. A job run started from this browser tab hands over its files as a download at once. > [!CAUTION] > The engine dispatches the messages of a job through the transport `opendxp_generic_execution_engine`. Run a worker > for this transport, for example `bin/console messenger:consume opendxp_generic_execution_engine`. Without a worker, > a job does not start its steps. --- ## Full Page Cache (Output Cache) ### Overview ![Full Page Cache](../../img/output-cache.png) ### Configure the Full Page Cache > **Please Note** > The full page cache is disabled by default if you're logged in in the admin interface or in the case > the debug mode ('APP_ENV=dev') is on. The full page cache only works with GET request, it takes the whole response (only for the frontend) including the headers from a request and stores it into the cache. The next request to the same page (hostname and request-uri are used to build the checksum/hash identifier) will be served directly by the cache. You can check if a request is served by the cache or not checking the response headers of the request. If there are X-OpenDxp-Cache-??? (marked orange below) headers in the response they the page is coming directly from the cache, otherwise not. If you have specified a lifetime, the response also contains the Cache-Control and the Expires header (perfect for HTTP accelerators like Varnish, ... ). You can configure full page cache in `config/config.yaml`, as in e.g.: ```yaml # config/config.yaml opendxp: full_page_cache: enabled: true lifetime: 120 exclude_cookie: 'opendxp_admin_sid' exclude_patterns: '@^/test/de@' ``` | Option | Description | | ------ | ----------- | | Enable | Set to true to enable to full page cache. | | Lifetime | You can optionally define a lifetime (in seconds) for the full page cache. If you don't do, the cache is evicted automatically when there is a modification in the OpenDXP Backend UI. If there is a lifetime the item stays in the cache even when it is changed until the TTL is over. The lifetime is useful if you have embedded some items which are not directly in the cms, like rss feeds, or twitter messages over the API. It is also highly recommended to specify a lifetime on high traffic websites so that the frontend (caches) isn't affected by changes in the admin-UI. Otherwise on every change in the admin-UI the whole output-cache is flushed, what can have drastic effects to the server environment. | | Exclude Patterns | You can define some exclude patterns where the cache doesn't affect. The patterns have to be valid regular expressions (including delimiters) and different patterns should be seperated by `,` | | Disable Cookie | You can define an additional cookie-name which disables the cache. The cookie "opendxp_admin_sid" (used for the OpenDXP admin UI) ALWAYS disables the output-cache to make editor's life easier ;-) ### Disable the Full Page Cache in your Code Sometimes it is more useful to deactivate the full page cache directly in the code, for example when it's not possible to define an exclude-regex, or for similar reasons. #### Disable caching via the response headers Adding the `Cache-Control: no-store` header to your response will disable the full page cache as well as any other middleware and browser caching: ```php headers->addCacheControlDirective('no-store'); ``` #### Disable the full page cache via an event listener The full page cache can be disabled via an event listener on `FullPageCacheEvents::CACHE_RESPONSE`: ```php getResponse(); if (true) { // Replace with your custom condition $event->setCache(false); } } } ``` #### Disable the full page cache listener entirely You can obtain the full page cache service from the container and disable it, e.g. in a Controller via DI: ```php disable('Your disable reason'); return $this->redirect('de'); } ``` ### Disable the Full Page Cache via your request #### Disable the Full Page Cache for a Single Request (only in DEBUG MODE) Just add the parameter `?opendxp_outputfilters_disabled=true` to the URL. #### Disable the Full Page Cache with a Cookie and a Bookmarklet Per default the disable-cookie configuration is set to `opendxp_admin_sid`. That means that if you're logged into OpenDXP (have a session-id cookie) you will always get the content live and not from the cache. ##### Bookmarklet If you have the cookie `opendxp_admin_sid` in your system configuration you can use the following bookmarklet to disable the full page cache without having an active admin session in another tab. To use the bookmarklet, just drag the following Link into your bookmark toolbar (any browser): * Disable OpenDXP Cache * Enable OpenDXP Cache --- ## Cache OpenDXP uses extensively caches for differently types of data. The primary cache is a pure object cache where every element (document, asset, object) in OpenDXP is cached as it is (serialized objects). Every cache item is tagged with dependencies so the system is able to evict dependent objects if a referenced object changes. The second cache is the output cache, which you can use either as pure page cache (configurable in system settings), or as in-template cache (see more at [template extensions](../../02_MVC/02_Template/02_Template_Extensions/README.md)). The third cache is used for add-ons like the glossary, translations, database schemes, and so on. The behavior of the caches is controlled by the add-on itself. All of the described caches are utilizing the `OpenDxp\Cache` interface to store their objects. `OpenDxp\Cache` utilizes a `OpenDxp\Cache\Core\CoreCacheHandler` to apply OpenDxp's caching logic on top of a [`PSR-6`](http://www.php-fig.org/psr/psr-6/) cache implementation which needs to implement [cache tagging](https://github.com/php-cache/tag-interop). ### Configuring the cache OpenDxp uses the `opendxp.cache.pool` Symfony cache pool, you can configure it according to your needs, but it's crucial that the pool supports tags. ```yaml # config/packages/cache.yaml framework: cache: pools: opendxp.cache.pool: public: true #tags: true default_lifetime: 31536000 # 1 year #adapter: opendxp.cache.adapter.doctrine_dbal #provider: 'doctrine.dbal.default_connection' adapter: cache.adapter.redis_tag_aware provider: 'redis://localhost' ``` By default, the cache will reuse the Doctrine connection and write to your DB's `cache_items` tables. You can override the used connection by setting `connection` setting to a known Doctrine connection (see [DoctrineBundle Reference](https://symfony.com/doc/current/reference/configuration/doctrine.html#doctrine-dbal-configuration) for further information). If you enable the `redis` cache configuration, the Redis cache will be used instead of the Doctrine one, even if Doctrine is enabled as well. > **IMPORTANT!** It is crucial to test and verify your Redis configuration, if OpenDXP is unable to connect to Redis, the entire system will stop working. #### Recommended Redis Configuration (`redis.conf`) ``` # select an appropriate value for your data maxmemory 768mb # IMPORTANT! Other policies will cause random inconsistencies of your data! maxmemory-policy volatile-lru save "" ``` > With the default settings, the minimum supported Redis version is 3.0. ### Using the Cache for your Application Use the `OpenDxp\Cache` facade to interact with the core cache or directly use the `OpenDxp\Cache\Core\CoreCacheHandler` service. You can use this functionality for your own application, and also to control the behavior of the OpenDXP cache (but be careful!). If you don't need the transactional tagging functionality as used in the core you're free to use a custom cache system as [provided by Symfony](https://symfony.com/doc/current/components/cache.html) but be aware that custom caches are not integrated with OpenDXP's cache clearing functionality. ##### Example of custom usage in an action ```php $lifetime = 99999; $cacheKey = md5($uri); if(!$data = \OpenDxp\Cache::load($cacheKey)) { $data = \OpenDxp\Tool::getHttpData('http://www.opendxp.io/...'); \OpenDxp\Cache::save( $data, $cacheKey, ["output","tag1","tag2"], $lifetime); } ``` ##### Overview of functionalities ```php // disable the cache globally \OpenDxp\Cache::disable(); // enable the cache globally \OpenDxp\Cache::enable(); // invalidate caches using a tag \OpenDxp\Cache::clearTag("mytag"); // invalidate caches using tags \OpenDxp\Cache::clearTags(["mytag","output"]); // clear the whole cache \OpenDxp\Cache::clearAll(); // disable the queue and limit and write immediately \OpenDxp\Cache::setForceImmediateWrite(true); ``` ##### Disable the Cache for a Single Request Sometimes it's useful to deactivate the cache for testing purposes for a single request. You can do this by passing the URL parameter `opendxp_nocache=true`. Note: This is only possible if you are in [DEBUG MODE](../13_Debugging.md#debug-mode) For example: `http://opendxp.io/download?opendxp_nocache=true` This will disable the entire cache, not only the output-cache. To disable only the output-cache you can add this URL parameter: `?opendxp_outputfilters_disabled=true` Here you can find more [magic parameters](../15_Magic_Parameters.md). If you want to disable the cache in your code, you can use: ```php \OpenDxp\Cache::disable(); ``` This will disable the entire cache, not only the output-cache. WARNING: Do not use this in production code! It is also possible to just disable the output-cache in your code, read more [here](./03_Full_Page_Cache.md). ### Further Reading * Details about output-cache - see [Output Cache](./03_Full_Page_Cache.md). --- ## Configure Password Hashing Algorithm OpenDXP uses PHP's default password hashing algorithm by default, which currently equals to `BCrypt` with a cost of `10` (see [`PASSWORD_DEFAULT`](https://www.php.net/manual/en/password.constants.php#constant.password-default)), but the algorithm can also be configured (see here for [possible algorithms and their options](https://www.php.net/manual/en/password.constants.php)), for example: ```yaml opendxp: security: password: algorithm: !php/const PASSWORD_BCRYPT options: cost: 13 ``` This config will be used for OpenDXP's backend users and [fields of type `Password` in custom OpenDXP Objects](./01_Authenticate_OpenDxp_Objects.md). --- ## Authenticate Against OpenDXP Objects As Symfony's security component is quite complex, OpenDXP provides base implementations to facilitate integrating the security configuration with users stored as OpenDXP objects. As example, assume we have a user object which is defined in a `App\Model\DataObject\User` class and stores its password in a field named `password` (field type `Password`). The password field is configured to use the `password_hash` algorithm which is the standard way to handle passwords in PHP these days (internally it uses bcrypt). The class definition looks like this (you can find a working example in the `demo-basic` install profile): ![App\Model\DataObject\User](../../img/security_authentication_class_definition.png) As a user object needs to implement the `UserInterface` provided by Symfony, we override the generated class and implement the remaining methods which are not implemented by field getters: ```php getClass()->getFieldDefinition('password'); $field->getDataForResource($this->getPassword(), $this); } } ``` Next, we configure OpenDXP to use our overridden class: ```yaml # config/config.yaml opendxp: models: class_overrides: 'OpenDxp\Model\DataObject\User': 'App\Model\DataObject\User' ``` ### Loading users with a User Provider A user provider is responsible for finding matching user objects for a given username. OpenDXP ships an `ObjectUserProvider` which loads users from a defined class type and searches the username for a configured property. In our case, we want to load users from the `App\Model\DataObject\User` and query the `username` field. To be able to use our user class in the security configuration, we define a user provider service which is configured to load our user implementation (make sure your bundle is able to load service definitions, see [Loading Service Definitions](../../20_Extending_OpenDxp/13_Bundle_Developers_Guide/01_Loading_Service_Definitions.md)): ```yaml # config/services.yaml services: # The user provider loads users by Username. # OpenDXP provides a simple ObjectUserProvider which is able to load users from a specified class by a configured # field. The website_demo.security.user_provider will load users from the App\Model\DataObject\User by looking at # their username field. website_demo.security.user_provider: class: OpenDxp\Security\User\ObjectUserProvider arguments: ['App\Model\DataObject\User', 'username'] ``` We'll use this service later in our security configuration to tell the firewall where to load its users from. For details have a look at `ObjectUserProvider` which is basically calling `User::getByUsername($username, 1)` internally. If you have more complex use cases you can extend the `ObjectUserProvider` or ship your completely custom implementation. For more information see [How to Create a custom User Provider](https://symfony.com/doc/current/security/custom_provider.html) on the Symfony docs. ### Password hashing The standard approach of hashing and verifying a user's password in Symfony is to delegate the logic to a `PasswordHasherInterface` which is responsible for calculating and verifying password hashes. As OpenDXP's `Password` field definition already provides this logic, the password hasher needs to be configured to delegate the logic to the user object. Symfony builds and caches one password hasher instance per user type (class). To be able to delegate the calculation to the user object it is necessary to build an password hasher instance which is scoped to the user object and can access the user's properties at runtime. OpenDXP adds this as additional layer of configuration which allows to specify a password hasher factory per user type which in turn can decide if it needs to build dedicated instances of password hashers per user. To be able to integrate our user object, we need 2 integration points: * A `PasswordFieldHasher` which has access to the user instance and delegates calculation and verification of the password hash to the password field definition. The password hasher needs to be configured with the name of the field it should operate on (`password` in our case). * A `UserAwarePasswordHasherFactory` which builds a dedicated instance of a `PasswordFieldHasher` per user object. To achieve this, we define a factory service which builds `PasswordFieldHasher` instances as specified above: ```yaml # The password hasher factory is responsible for verifying the password hash for a given user. As we need some special # handling to be able to work with the password field, we use the UserAwarePasswordHasherFactory to build a dedicated # hasher per user. This service is configured in opendxp.security.password_hasher_factories to handle our user model. services: website_demo.security.password_hasher_factory: class: OpenDxp\Security\Hasher\Factory\UserAwarePasswordHasherFactory arguments: - OpenDxp\Security\Hasher\PasswordFieldHasher - ['password'] ``` Now, instead of configuring the password hasher in `security.password_hashers` as it is the standard Symfony way, configure your password hasher factory service instead in `opendxp.security.password_hasher_factories`. This is just an additional way of building password hashers - if you don't need any user specific handling, just stick to the standard Symfony way. ```yaml opendxp: security: # the password hasher factory as defined in services.yaml password_hasher_factories: App\Model\DataObject\User: website_demo.security.password_hasher_factory ``` When a password hasher is loaded for a `App\Model\DataObject\User` object, the UserAwarePasswordHasherFactory will build a dedicated instance of `PasswordFieldHasher` instead of always returning the same instance for all users. ### Configuring the firewall As all our needed services are in place, we can start to use them from the firewall configuration. As an example, let's configure a simple firewall which authenticates via HTTP basic auth. Our final configuration looks like the following: ```yaml opendxp: security: # the password hasher factory as defined in services.yaml password_hasher_factories: App\Model\DataObject\User: website_demo.security.password_hasher_factory security: providers: # the user provider as defined in services.yaml demo_cms_provider: id: website_demo.security.user_provider firewalls: # demo_cms firewall is valid for the whole site demo_cms_fw: # the provider defined above provider: demo_cms_provider http_basic: ~ ``` This should get you started with a custom authentication system based on OpenDXP objects. For further information see: * The [Symfony Security Component documentation](https://symfony.com/doc/current/security.html) --- ## Authenticator Based Security As OpenDXP uses the Symfony Security Component for authentication/authorization of Admin interface and also provides the capabilities to use the same security component on frontend websites. It is important to adapt the ongoing changes in Symfony security component. ### Points to consider when moving to new Authenticator: - New authentication system works with `Password Hasher Factory` instead of `Encoder Factory`. - `BruteforceProtectionHandler` will be replaced with `Login Throttling`. - `Custom Guard Authenticator` will be replaced with `Http\Authenticator`. - Anonymous user no longer exist. For more information on new Authenticator Based Security, please read the [Symfony Security Component documentation](https://symfony.com/doc/current/security.html). --- ## Restrict Deserialization Classes Some places in OpenDXP call PHP's `unserialize()` on data the reading code doesn't fully control the shape of, for example an object stored via `TmpStore` or the admin session's security token. Reconstructing an arbitrary class from such data is a known PHP security risk (object injection), so these places restrict which classes `unserialize()` is allowed to reconstruct. The allowed classes are configurable per scope under `opendxp.serialization`: ```yaml opendxp: serialization: authentication: allowed_classes: App\Security\MyCustomToken: true tmp_store: allowed_classes: App\Model\MyStoredObject: true ``` A project only ever adds entries here. OpenDXP's own built-in classes for each scope stay in place regardless of what a project configures, so a project can't accidentally remove them. ### Scopes | Scope | Config key | Used for | |----------------|------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Authentication | `authentication` | The admin session's security token (`\OpenDxp\Tool\Authentication`). Add a class here if you register a custom authenticator or two-factor provider for the admin firewall with its own token class. | | TmpStore | `tmp_store` | Objects stored via `\OpenDxp\Model\Tool\TmpStore::add()`/`set()`. Add a class here if you store an object, not just scalars or arrays, through TmpStore. | ### In code `\OpenDxp\Tool\Serialize::unserializeWithScope()` reads a scope's configured classes and restricts `unserialize()` to them: ```php use OpenDxp\Tool\SerializationScope; use OpenDxp\Tool\Serialize; $value = Serialize::unserializeWithScope(SerializationScope::TmpStore, $data); ``` Use this whenever new code needs to deserialize data it doesn't fully control the shape of, instead of calling `unserialize()` or `Serialize::unserialize()` directly. If the data contains a class that isn't allowed, anywhere in it, `unserializeWithScope()` returns `null` rather than a value with a broken class hidden a few properties deep in it. --- ## Permission Voters OpenDXP bridges its own permission checks (`User::isAllowed()` and `ElementInterface::isAllowed()`) into Symfony's authorization layer, so you can use `#[IsGranted]` and `Security::isGranted()`. ### Two voters to rule them all #### UserPermissionVoter Flat/global permission check, same as `$user->isAllowed($key)`. Keys come from `OpenDxp\Security\CorePermission` or any bundle's own permission enum (see below). #### ElementPermissionVoter Element ACL check, same as `$element->isAllowed($type, $user)`. Keys come from `OpenDxp\Security\ElementPermission` (`View`, `Publish`, `Delete`, `Rename`, `Create`, `Settings`, `Versions`, `Properties`, `List`). Per-language edit/view permissions and layout restrictions are a separate, non-boolean mechanism and not part of this enum. *** ### Flat permission check ```php #[IsGranted(CorePermission::Assets->value)] class MyController extends AdminAbstractController { } ``` ### Element ACL check Declarative, with the element resolved from a controller argument: ```php #[IsGranted(ElementPermission::View->value, subject: 'asset')] public function myAction(Asset $asset): Response { } ``` Imperative: ```php if ($security->isGranted(ElementPermission::View->value, $element)) { // ... } $security->denyAccessUnlessGranted(ElementPermission::Publish->value, $element); ``` --- ## Security and Authentication You can make full use of the [Symfony Security Component](https://symfony.com/doc/current/security.html) to handle complex authentication/authorization scenarios. Please be aware that also the OpenDXP admin UI uses the Security component, so be careful when changing/modifying the configuration. ### Login example A simplified guide to this setup is illustrated in [Authenticate against OpenDXP Objects](./01_Authenticate_OpenDxp_Objects.md). For more complex examples, custom user providers and a full configuration reference please read the [Symfony Security Component documentation](https://symfony.com/doc/current/security.html). To use `#[IsGranted]`/`Security::isGranted()` against OpenDXP's own permission checks, see [Permission Voters](./10_Permission_Voters.md). If you register a custom authenticator or store your own objects via `TmpStore`, see [Restrict Deserialization Classes](./06_Restrict_Deserialization_Classes.md) to make sure they still deserialize correctly. --- ## CLI and OpenDXP Console OpenDXP can be executed headless and has a very powerful PHP API. As a consequence of these two aspects, it is possible to automate pretty much every task within OpenDXP. OpenDXP implements the `Symfony\Console` component and provides `bin/console` as single entry point to console commands registered to the `Symfony\Console` application. #### Implementing Own Commands Have a look at the `Symfony\Console` [documentation](https://symfony.com/doc/5.2/console.html) for details how commands are implemented. However, it makes sense to let your command classes extend `OpenDxp\Console\AbstractCommand` to get some defaults like a helper for the [Symfony VarDumper Component](https://symfony.com/doc/5.2/components/var_dumper/index.html) set up automatically (see below). #### Registering Commands Command must be registered as services and tagged with the `console.command` tag. If you're using the default `services.yaml` of OpenDXP skeleton (or demos) for configuration, this is already done for you for the `App`. , thanks to autoconfiguration. #### Helpers Provided By `OpenDxp\Console\AbstractCommand` The `AbstractCommand` base class provides helpers which make your life easier. ###### `--ignore-maintenance-mode` The console application implicitly adds the `--ignore-maintenance-mode` option to all commands. OpenDXP checks for the option and prevents starting the command if the system is in maintenance mode and the option is not set. ###### `--maintenance-mode` The console application implicitly adds the `--maintenance-mode` option to all commands. With this option set, OpenDXP is set into maintenance mode while that command is executed. ###### `dump()` and `dumpVerbose()` Better `var_dump` through [`VarDumper`](https://symfony.com/doc/5.2/components/var_dumper/introduction.html). ### Example ```php dump("Isn't that awesome?"); // add newlines through flags $this->dump("Dump #2"); // only dump in verbose mode $this->dumpVerbose("Dump verbose"); // Output as white text on red background. $this->writeError('oh noes!'); // Output as green text. $this->writeInfo('info'); // Output as blue text. $this->writeComment('comment'); // Output as yellow text. $this->writeQuestion('question'); } } ``` #### Usage Call `bin/console list` script from the command line to get a list of available commands. To call a command, use `bin/console `. > Be sure to run the console with the PHP user to prevent writing permissions issues later by switching to the appropriate user, for instance on Debian system `su -l www-data -s /bin/bash`. ###### Examples: ```php # get a list of all registered commands $ ./bin/console list # call the foo:bar command $ ./bin/console foo:bar ``` --- ## Error Messages An error message helps its reader to find the cause of an error. Developers find error messages in the log. Editors see them in the admin interface whenever a request fails. Console commands print them in the terminal. ### Structure A message has two or three sentences: 1. The first sentence names the subject and what failed. 2. The second sentence names the reason. 3. An optional third sentence says what the reader can do. ```php throw new Exception(sprintf( '%s cannot be saved. Its parent %d does not exist.', Element\Service::getMessageSubject($this), $this->getParentId() )); ``` The message reads: ```text Object /products/shoe (ID 123) cannot be saved. Its parent 4711 does not exist. ``` ### Rules - Write full English sentences. Every sentence ends with a period. - Build the message with `sprintf()`. - Put a value in double quotes when the caller passed it, for example a key or an option: `The key "a/b" is invalid.` - Write IDs, paths and numbers without quotes. - Name a limit together with the actual value: `The full path has 812 characters. The limit is 765.` - Name an unexpected type with `get_debug_type()`: `The value must be an array. A string was given.` ### Name the subject | Subject | Form | Example | |-----------------------------|-----------------------------------------|-----------------------------------------------------------| | Element with an ID | `Element\Service::getMessageSubject()` | `Object /products/shoe (ID 123)` | | New element without an ID | `Element\Service::getMessageSubject()` | `New object "shoe"` | | Class definition | Name and ID of the class | `Class Product (ID prod)` | | Field of a class | Name of the field and name of the class | `Field price of class Product` | | Configuration | Full path of the key | `The option opendxp.assets.thumbnails.max_scaling_factor` | | Option of a console command | Name of the option with dashes | `The option --thumbnails` | ### Keep out of a message - Passwords, tokens, API keys and session IDs - SQL statements and their parameters - Whole objects and arrays - Personal data such as names or email addresses. An ID identifies a user or a customer. - In a permission error, the ID or the path of an element. The user may not be allowed to see it. The log holds this context instead. ### Context in the log Every log entry carries the current user, the route of the request and the console command. See [Logging](./07_Logging.md#context-of-a-log-entry). A message does not repeat this context. An exception message is plain text, so `sprintf()` builds it. A log call follows PSR-3. It keeps the message as a template with placeholders and passes the values as context. Log tools group entries by the template and index the values as fields: ```php $this->logger->error('Object {id} cannot be indexed. The index {index} does not exist.', [ 'id' => $object->getId(), 'index' => $indexName, ]); ``` ### Exception classes When you change a message, keep the class of the exception. Projects catch exceptions by their class. New code throws the most specific class that fits: | Error | Class | |---------------------------------------|----------------------------------------------------| | The caller passed an invalid argument | `InvalidArgumentException` | | An element holds invalid data | `OpenDxp\Model\Element\ValidationException` | | A path is already taken | `OpenDxp\Model\Element\DuplicateFullPathException` | | The code reaches an impossible state | `LogicException` | --- ## Debugging OpenDXP In this chapter, a few insights, tips and tricks for debugging OpenDXP are shown. This should give you a head start when developing with OpenDXP. ### Debug Mode In order to include some specific debugging tools (profiler, toolbar, ...), OpenDXP relies on environment variable `APP_ENV` in `.env` file in your project root directory. `APP_ENV=dev` Additionally you can set the debug flag on the kernel by using `APP_DEBUG=1`. More details on that see [Symfony docs](https://symfony.com/doc/current/configuration/front_controllers_and_kernel.html#debug-mode) ### Dev Mode The development mode enables some debugging features. This is useful if you're developing on the core of OpenDXP or when creating a bundle. Please don't activate it in production systems! What exactly does the dev mode: * Loading the source javascript files (uncompressed & commented) * Disables some caches (Cache, ...) * extensive logging into log files * ... and some more little things Add the following line to your `.env` file to enable dev mode. `OPENDXP_DEV_MODE=true` ### Server-Side Debugging For server side debugging, standard php and Symfony framework debugging tools like the following can be used. * Reading log files as described [here](07_Logging.md) * Using Symfony profiler console depending on the active environment. Details see [Symfony docs](https://symfony.com/doc/current/reference/configuration/web_profiler.html) * Using Xdebug and a proper IDE for stepwise debugging, more information see [Xdebug docs](https://xdebug.org/) ### Client-Side Debugging For proper debugging of OpenDXP backend UI activate the DEV-Mode in [system settings](../18_Tools_and_Features/25_System_Settings.md). By doing so, all javascript files are delivered uncompressed and commented. Thus debugging tools provided by browsers (like actual error lines, debugger, stack trace, etc.) can be used. ### HTTP Headers OpenDxp might add following headers to its responses to provide additional debug information, especially concerning full page cache: If response is delivered directly from full page cache: * `X-OpenDxp-Output-Cache-Tag:output_`: Cache tag of delivered information. * `X-OpenDxp-Cache-Date:`: Date when information was stored to cache. If response could be delivered from full page cache, but is not: * `X-OpenDxp-Output-Cache-Disable-Reason:`: Describes reason why response is not delivered directly from full page cache. Reasons can be `in debug mode`, `backend user is logged in`, `exclude path patter in system-settings matches`, `exclude cookie in system-setings matches`, etc. One additional header to identify that response is sent by OpenDXP. * `X-Powered-By:opendxp`: Added to every request. --- ## Magic Parameters OpenDXP supports some *magic parameters* which can be added as parameter to every request. #### opendxp_nocache Setting this parameter disables every kind of cache, eg.: `http://www.example.com/my/page?opendxp_nocache` This parameter only works if [`DEBUG MODE`](../18_Tools_and_Features/25_System_Settings.md) is on. #### opendxp_outputfilters_disabled Disables all output filters, incl. the output-cache. But this doesn't disable the internal object cache, eg.: `http://www.example.com/my/page?opendxp_outputfilters_disabled=1` This parameter only works if [`DEBUG MODE`](../18_Tools_and_Features/25_System_Settings.md) is on. #### unminified_js Disables the JavaScript minifier. Useful for ExtJS debugging. Disabled by default if in [`DEV MODE`](../18_Tools_and_Features/25_System_Settings.md). This parameter only works if [`DEBUG MODE`](../18_Tools_and_Features/25_System_Settings.md) is on. #### opendxp_disable_host_redirect Disables the "redirect to main domain" feature. This is especially useful when using OpenDXP behind a reverse proxy. #### opendxp_debug_translations Configures the translator to return the given translation key instead of actually translating the message. This can be useful to debug translations or to get an overview over used translation keys. Example: http://www.example.com/my/page?opendxp_debug_translations=1 This parameter is only available when debug mode is active or an active admin session is present. It is possible to disable this feature completely or individualize the name of the GET parameter using the following configuration options. ```yaml opendxp: translations: debugging: enabled: false # you could also change the parameter from opendxp_debug_translations to something else parameter: my_custom_parameter ``` --- ## Static Helpers OpenDXP offers some static helpers: ### OpenDXP Tool The `OpenDxp\Tool` class is a collection of general service methods. Their names should be self-explaining, just have a look at the [class source file](https://github.com/open-dxp/opendxp/blob/1.x/lib/Tool.php). Particular useful can be following methods: * `isValidPath()` * `getValidLanguages()` * `getHostname()` * `getHostUrl()` * `classExists()` * `getMail()` #### E-Mail There is a convenience function which allows any OpenDXP system component or plugin to use a preconfigured `Symfony\Component\Mime\Email` instance based on the OpenDXP system settings' email configuration. ```php $mail = OpenDxp\Tool::getMail($recipients, $subject); // For any plugin or website applications it might be convenient to use this mail configuration instead of having to care for these settings themselves. ``` ### Element Service The `OpenDxp\Model\Element\Service` class is a collection of service methods for elements (documents, assets, objects). Their names should be self-explaining, just have a look at the [class source file](https://github.com/open-dxp/opendxp/blob/1.x/models/Element/Service.php). Particular useful can be following methods: * `getElementByPath()` * `getSafeCopyName()` * `pathExists()` * `getElementById()` * `getElementType()` * `createFolderByPath()` * `getValidKey()` Also have a look at the sub classes `OpenDxp\Model\Asset\Service`, `OpenDxp\Model\Document\Service` and `OpenDxp\Model\DataObject\Service`. #### Document-Service A useful service method for documents is `OpenDxp\Model\Document\Service::render()`. You can use this helper to render a page outside of a view, for example to send mails. ###### Example: ```php $optionalParams = ['foo' => 'bar', 'hum'=>'bug']; $useLayout = true; $content = Document\Service::render(Document::getById(2), $optionalParams, $useLayout); echo $content; ``` --- ## UUID Support > **Note** > This feature requires UUID bundle to be active. Please make sure that you have `\OpenDxp\Bundle\UuidBundle\OpenDxpUuidBundle::class` entry in your `config/bundles.php` and make sure that the bundle is installed and enabled. OpenDXP provides a toolkit for UUID-support. To activate the UUID-support, an instance identifier has to be set manually in the config.yaml file. ```yaml opendxp_uuid: instance_identifier: 'your_unique_instance_identifier' ``` Once set, OpenDXP automatically creates an UUID for each newly created document, asset, class and object. With the class `Tool\UUID` you have access to the UUIDs as follows: ```php use OpenDxp\Bundle\UuidBundle\Model\Tool; //get UUID for given element (document, asset, class, object) $uuid = Tool\UUID::getByItem($document); //get element for given UUID $document = Tool\UUID::getByUuid($uuid); //create and save uuid for given element $uuid = Tool\UUID::create($document); ``` --- ## Static Page Generator OpenDXP offers a Static Page Generator service, which is used to generate HTML pages from OpenDXP documents. This generator service works by taking a OpenDXP document with content and templates and renders them into a full HTML page, that can served directly from the server without the intervention of templating engine. ### Enable Static Page generator for a Document To enable automatic static page generation on document save or by CLI command, go to Document -> Settings -> Satic Page Generator. ![Static Page Settings](../img/static_page1.png) Mark enable checkbox and define optional lifetime for static pages (which regenerates static page after lifetime) and save document. Once, the static page generator is enabled, the document icon changes to grey icon. and last generated information is displayed in document settings, when the generation is requested from frontend or cli command. ![Static Page Detail](../img/static_page3.png) In addition, if you are using default local storage for static pages, then make sure your project `.htaccess` has this below section (after the `# Thumbnails` section), which is responsible for looking up static page before passing to templating engine. ```apache # static pages SetEnvIf Request_URI ^(.*)$ STATIC_PAGE_URI=$1 SetEnvIf Request_URI / STATIC_PAGE_URI=/%home RewriteCond %{REQUEST_METHOD} ^(GET|HEAD) RewriteCond %{QUERY_STRING} !(opendxp_editmode=true|opendxp_preview|opendxp_version) RewriteCond %{DOCUMENT_ROOT}/var/tmp/pages%{STATIC_PAGE_URI}.html -f RewriteRule ^(.*)$ /var/tmp/pages%{STATIC_PAGE_URI}.html [PT,L] ``` If you are using NGINX as web server, this must be added **before** the `server` block ```nginx map $args $static_page_root { default /var/tmp/pages; "~*(^|&)opendxp_editmode=true(&|$)" /var/nonexistent; "~*(^|&)opendxp_preview=true(&|$)" /var/nonexistent; "~*(^|&)opendxp_version=[^&]+(&|$)" /var/nonexistent; } map $uri $static_page_uri { default $uri; "/" /%home; } ``` and the following modification must be done to the location block that matches all requests ```nginx server { ... location / { error_page 404 /meta/404; try_files $static_page_root$static_page_uri.html $uri /index.php$is_args$args; } ... } ``` ### Processing Once the static generator option is enabled, OpenDXP generates static pages on following actions: - First request to the page, after updating and saving the document in admin. - Maintenance job - CLI command In background, maintenance job takes care of generating static pages for documents on regular intervals. However, you can also use CLI command to generate static pages on demand: `php bin/console opendxp:documents:generate-static-pages` also, you can filter the documents by parent path, which should processed for static generation: `php bin/console opendxp:documents:generate-static-pages -p /en/Magazine` #### Absolute URLs and HTTPS If you are generating absolute URLs via CLI command, please keep in mind that due to the nature of CLI not being executed in the HTTP context, you may need to set the `default_uri` or the request context parameters. ```yaml framework: router: default_uri: 'https://example.org/my/path/' ``` source: https://symfony.com/doc/7.4/routing.html#generating-urls-in-commands ```yaml # config/services.yaml parameters: router.request_context.scheme: 'https' asset.request_context.secure: true ``` source: https://symfony.com/doc/7.4/routing.html#forcing-https-on-generated-urls #### SSI If you want to add NGINX SSI module for generating the static pages, you can add following config: ```yaml opendxp: document: static_page_generator: headers: - { name: "Surrogate-Capability", value: 'device="SSI/1.0"' } ``` Now the maintenance command can generate SSI includes in the static files like a normal page load. ### Storage By default, OpenDXP stores the generated HTML pages on local path: `'document_root/public/var/tmp/pages'`. It is possible to customize the local storage path for static pages by defining Flysystem config in config.yaml: ```yaml flysystem: storages: opendxp.document_static.storage: # Storage for generated static document pages, e.g. .html files generated out of OpenDXP documents # which are then delivered directly by the web-server adapter: 'local' visibility: public options: directory: '%kernel.project_dir%/public/var/tmp/pages' ``` ### Static Page Generate Router In case, you are using custom remote storage for static pages and need to serve pages from this remote location, then you would need to enable the static page router with following configuration in config.yaml: ```yaml opendxp: documents: static_page_router: enabled: true route_pattern: '@^/(en/Magazine|de/Magazin)@' ``` | config | Description | |----------------|---------------------------------------------------------------| | enabled | Set it true to enable Static Page Router | | route_pattern | Regular expression to match routes for static page rendering | ### Use Static Page HTML files with mainDomain instead path Enable the main domain option to get the static pages with starting main domain instead of the keys from OpenDXP documents. ```yaml opendxp: documents: static_page_generator: use_main_domain: true ``` | config | Description | |----------------|---------------------------------------------------------------| | use_main_domain| Use tmp path like /public/var/tmp/pages/my-domain.com/en.html | NGINX Config Changes: ```nginx map $args $static_page_root { default /var/tmp/pages/$host; "~*(^|&)opendxp_editmode=true(&|$)" /var/nonexistent; "~*(^|&)opendxp_preview=true(&|$)" /var/nonexistent; "~*(^|&)opendxp_version=[^&]+(&|$)" /var/nonexistent; } map $uri $static_page_uri { default $uri; "/" /%home; } ``` ### Static Page Generation With Ajax Request The static pages with XMLHttpRequest fetches the data and displays it on the page, just like a standard document page. However, if you are using the Fetch API to request the data, then must add the `XMLHttpRequest` header as shown below, otherwise the sub-request will replace the content of the generated static page. ```js fetch('/test/page', { headers: { 'X-Requested-With': 'XMLHttpRequest', } }) ``` --- ## Adaptive Design Helper The DeviceDetector helper makes it easy to implement the adaptive design approach in OpenDXP. #### Using It Anywhere in Your Code ```php use OpenDxp\Tool\DeviceDetector; use Symfony\Component\HttpFoundation\Response; class TestController extends Action { public function testAction(): Response { $device = DeviceDetector::getInstance(); $device->getDevice(); // returns "phone", "tablet" or "desktop" if($device->isDesktop() || $device->isTablet()) { // do something } // ... } } ``` #### Force a Device Type Sometimes it's necessary to force a device type. A typical use case is a "Back to Desktop Version" or vice versa link. To do so, just add the parameter `forceDeviceType` to your request: ``` /your/link?forceDeviceType=desktop /another/link?forceDeviceType=tablet /a/mobile/link?forceDeviceType=phone ``` This will set the device to the specified value and OpenDXP will remember this setting using a cookie (name: `forceDeviceType`) till the browser session ends. #### Caching The OpenDXP output-cache is aware of this feature and just works as expected. If you're using a caching proxy like Varnish you have to take the value of the cookie `forceDeviceType` into the hash calculation, otherwise there's just one hash for different contents of an URL (phone, tablet, desktop). --- ## OpenDXP Mail The `OpenDxp\Mail` Class extends the [`Symfony\Component\Mime\Email`](https://symfony.com/doc/current/mailer.html#email-addresses) Class and adds some features for the usage with OpenDXP. If email settings are configured in your `config/config.yaml` then on initializing `OpenDxp\Mail` object, these settings applied automatically. It is required to configure [email settings](./README.md#general-information) prior to using OpenDxp\Mail. The `OpenDxp\Mail` Class automatically takes care of the nasty stuff (embedding CSS, normalizing URLs and Twig expressions ...). Note that all CSS files are embedded to the html with a `