Widget Creation

Note

Internally, widgets are referred to as shortcodes in the codebase and configuration.

To create a custom widget, ensure your shortcode class:

  • Is registered in services.yaml as a separate service

  • Has the tag visualcms.shortcode.tag.twig in its service definition

  • Implements OxidEsales\VisualCmsModule\ShortCodeCollection\ShortCode\ShortCodeInterface

  • Defines a unique shortCodeTag in its metadata — the identifier used internally, such as "carousel", "image", or "hero"

A working example (GoogleMap shortcode) can be found in the vcms-examples repository.

Register the shortcode as a service in your module’s services.yaml:

OxidEsales\VcmsExamples\ShortCode\GoogleMap:
  class: OxidEsales\VcmsExamples\ShortCode\GoogleMap
  tags: [ 'visualcms.shortcode.tag.twig' ]

BaseShortCode Usage

BaseShortCode is an abstract class that provides a default implementation of common ShortCodeInterface methods, reducing the boilerplate needed when creating a custom shortcode. It is recommended to extend it rather than implementing the interface directly.

ShortCodeInterface

  • public function getMetadata(): ShortCodeMetadataInterface;

    Returns the shortcode metadata. Use the OxidEsales\VisualCmsModule\DTO\ShortCodeMetadata class as the implementation.

  • public function getTemplate(): string;

    The path to the shortcode template. Prefix the path with your module ID, for example: @ddoevisualcms/shortcodes/visualcms_shortcode_tabs

  • public function getOptions(): OptionList;

    Returns the list of configurable options for this shortcode, wrapped in an OxidEsales\VisualCmsModule\DTO\OptionList object. OptionList enforces a consistent structure and prevents misconfiguration.

    Example:

    public function getOptions(): OptionList
    {
        // $this->shopAdapter: injected \OxidEsales\EshopCommunity\Internal\Transition\Adapter\ShopAdapterInterface
        // (Registry::getLang() is deprecated in Visual CMS 12)
    
        return new OptionList([
            'id' => new SelectFromDataOption(
                // Label name
                label: $this->shopAdapter->translateString('DD_VISUAL_EDITOR_WIDGET_ARTICLE'),
                // Route prefix of this shortcode's search controller (see "Shortcode Search API" below)
                apiPath: 'api/vcms-shortcode/article',
                // placeholder name
                placeholder: $this->shopAdapter->translateString('DD_VISUAL_EDITOR_WIDGET_CHOOSE_ARTICLE'),
                // fields that are also taken into account for a selection (only for type "select")
                dataFields: ['name' => 'label']
            ),
            'articletype' => new SelectOption(
                label: $this->shopAdapter->translateString('DD_VISUAL_EDITOR_WIDGET_ARTICLE_TYPE'),
                values: [
                    'grid' => $this->shopAdapter->translateString('DD_VISUAL_EDITOR_WIDGET_ARTICLE_TYPE_GRID'),
                    'line' => $this->shopAdapter->translateString('DD_VISUAL_EDITOR_WIDGET_ARTICLE_TYPE_LINE'),
                ],
                defaultValue: 'grid'
            ),
            'name' => new HiddenOption()
        ]);
    }
    

    Note

    OptionList accepts an array of OxidEsales\VisualCmsModule\ShortCodeCollection\Option\ShortCodeOptionInterface objects. The built-in option types (namespace OxidEsales\VisualCmsModule\ShortCodeCollection\Option\, all extending BaseOption) are TextOption, TextAreaOption, WysiwygOption, ColorOption, CheckboxOption, FileOption, ImageOption, HiddenOption, SelectOption, SelectFromDataOption. The former ShortCodeMultiOptionInterface was removed in Visual CMS 12: ImageOption, SelectOption and SelectFromDataOption keep their isMulti() methods, but multi values are no longer split by the legacy WidgetParser. Custom option types can be implemented and used directly if needed.

  • public function prepareTemplateParams(GridItemInterface $gridItem, GridRenderContextInterface $renderContext): array;

    Prepares variables to be passed to the shortcode template. The returned array is extracted as template variables, making each key directly accessible in the template. The second argument gives more context — see the next sections for details.

ShortCodeMetadataInterface

ShortCodeMetadata accepts the following constructor parameters:

  • shortCodeTag

    The unique identifier of the shortcode, e.g. "carousel", "image", "hero". Must be unique across all registered shortcodes.

  • isWidget

    Boolean. Set to true if the shortcode should appear as a selectable widget in the editor. Set to false for internal shortcodes that are not directly placeable from the widget list.

  • title

    The translation string key for the widget title shown in the editor.

  • previewOptionKey

    The key of the option whose value is shown as a preview text in the admin content grid. For example, the Text widget uses "content", so the text content is shown directly in the grid.

  • backgroundColor

    The background color of the widget tile in the admin content grid, in HTML format, e.g. '#ccbbaa'. Defaults to #ffffff when omitted.

  • icon

    The CSS class for the widget icon in the editor. Any icon class works — by convention the core widgets use Bootstrap Icons (bi-*) as of Visual CMS 10, while the vcms-examples module uses Font Awesome (e.g. fa-solid fa-map). Defaults to bi-star-fill when omitted.

Example:

public function getMetadata(): ShortCodeMetadataInterface
{
    return new ShortCodeMetadata(
        shortCodeTag: 'text',
        isWidget: true,
        title: 'DD_VISUAL_EDITOR_SHORTCODE_TEXT',
        previewOptionKey: 'content',
        backgroundColor: '#3498db',
        icon: 'bi bi-text-left' // Bootstrap Icons — note the 'bi ' prefix (VCMS 10+); was 'fa-align-left' in earlier versions
    );
}

prepareTemplateParams() Method

The following describes the general process for all widgets, using the Text widget as an example.

prepareTemplateParams() is called for every widget before rendering. The returned array is extracted as template variables, making each key directly accessible in the shortcode template. When extending BaseShortCode, calling parent::prepareTemplateParams($gridItem, $renderContext) already retrieves the option values via $gridItem->getWidgetConfiguration()->getOptionValues() and returns them as an array, so you only need to add or modify values on top of that.

public function prepareTemplateParams(
    GridItemInterface $gridItem,
    GridRenderContextInterface $renderContext
): array {
    $params = parent::prepareTemplateParams($gridItem, $renderContext);

    if (!empty($params['background_image'])) {
        $params['background_image'] = $this->mediaFacade->getMediaUrl(
            $params['background_image'],
            new MediaLookupContext(
                trigger: 'VisualCMS/Shortcode/Text',
                identifier: $gridItem->getContentId()
            )
        );
    }

    if (!empty($params['content'])) {
        $params['content'] = $this->templateRenderer->renderFragment(
            $params['content'],
            md5($params['content']),
            $renderContext->getTriggerContext()
        );
    }

    return $params;
}

Note

Since Visual CMS 12 (with Media Library 6.0), MediaFacadeInterface::getMediaUrl() and getMedia() take an optional MediaLookupContext (OxidEsales\MediaLibrary\Media\DataType\MediaLookupContext). Passing it is optional — callers keep working without it — but recommended: if the requested media cannot be resolved, the Media not found. warning then carries your trigger/identifier, making it easy to trace which widget and content requested the missing media (see Missing-Media Diagnostics). All built-in VCMS shortcodes pass trigger: 'VisualCMS/Shortcode/<Name>' with the content id as identifier.

The raw option values stored for a widget look like this:

{"content":"some example text","background_color":"#ef9d9dff","background_image":"237-536x354.jpg","background_fixed":"","fullwidth":"","class":""}

After being processed by prepareTemplateParams(), the data is available in the template as an array:

[
    'content' => "some example text",
    'background_color' => "#ef9d9dff",
    'background_image' => "237-536x354.jpg",
    'background_fixed' => "",
    'fullwidth' => "",
    'class' => ""
]

In addition to the option values, the template typically has access to these extra variables:

  • shortcode — provided by BaseShortCode when extending it

  • calculatedClasses — provided by ColumnLayoutTemplateParamsDecorator

  • oView and oViewConf — provided by ViewInformationTemplateParamsDecorator (deprecated since v11.0 — avoid relying on these variables)

Both decorators (namespace OxidEsales\VisualCmsModule\ShortCodeCollection\Decorator\) decorate TemplateParamsCalculatorInterface (OxidEsales\VisualCmsModule\Grid\Rendering\Service\TemplateParamsCalculatorInterface, src/Grid/Rendering/Service/) — not the shortcodes themselves; build your own additions the same way.

Additional logic can be added to existing widgets via service decoration.

Render Context

The second argument of prepareTemplateParams() is a GridRenderContextInterface (OxidEsales\VisualCmsModule\Grid\Rendering\DTO\GridRenderContextInterface, src/Grid/Rendering/DTO/) describing the render currently in progress. It is created where the render is triggered and passed unchanged through the whole grid, including nested widgets inside rows and columns.

  • getContent()

    The Content model the grid belongs to. During a preview this is a not yet saved model built from the editor form values, so it may differ from what is stored in the database.

  • getTriggerContext()

    The variables of the template that triggered the render, e.g. oView or any variable the calling template had in scope. For the frontend this is captured by the vetree Twig function, for the preview it comes from the view data of the content controller.

The main use case is passing the trigger context to renderFragment() when a widget renders one of its own option values. Such a value can contain template syntax, which is only resolvable if the variables of the triggering template are handed over with it:

$params['content'] = $this->templateRenderer->renderFragment(
    $params['content'],
    md5($params['content']),
    $renderContext->getTriggerContext()
);

Note

The trigger context is deliberately not merged into the template variables of a shortcode. Shortcode templates should stay predictable and not depend on which template triggered the render. If a widget needs a value from the trigger context in its own template, it has to put it into the returned params explicitly.

Services

Since shortcodes are registered as Symfony services, any other service can be injected via the constructor:

public function __construct(
    protected \OxidEsales\VisualCmsModule\Category\Service\CategoryServiceInterface $categoriesService
) {
}

Note

All built-in widgets are located in src/ShortCodeCollection/ShortCode/. The vcms-examples repository provides additional examples of creating and extending existing widgets.

Overriding an Existing Shortcode

Overriding an existing shortcode replaces its class in the service container. The example below overrides the Text shortcode to add an additional Heading field, as demonstrated in the vcms-examples repository.

OxidEsales\VisualCmsModule\ShortCodeCollection\ShortCode\Text:
  class: OxidEsales\VcmsExamples\ShortCode\Text
  tags: [ 'visualcms.shortcode.tag.twig' ]

Extending an Existing Shortcode

While overriding can technically be used to extend a shortcode, the recommended approach is service decoration — it avoids replacing the original class entirely and is more maintainable.

A concrete example of shortcode decoration can be found in the DecorationExample.php in the vcms-examples repository.

Register the decorator in services.yaml:

OxidEsales\VcmsExamples\DecorationExample:
  decorates: OxidEsales\VisualCmsModule\ShortCodeCollection\ShortCode\Action\Action
  arguments: ['@.inner']

Overriding a Shortcode Template

To override only the template for a shortcode without changing its logic, register a ThemeTemplatesConfiguration service tagged with shortcode.themeTemplates:

vcmsTemplateOverrideForApexTheme:
  class: OxidEsales\VisualCmsModule\DTO\ThemeTemplatesConfiguration
  arguments:
    $themeId: 'apex'
    $templates:
      column: '@@oe_vcmsexamples/shortcodes/vcmsexamples_shortcode_column'
      action: '@@oe_vcmsexamples/some_other_template_for_overwriting_the_original_action_template_for_apex'
  tags: [ 'shortcode.themeTemplates' ]

Shortcode Search API

Widget options of type SelectFromDataOption load their choices from fixed API routes instead of the former admin cl/fnc dispatch. The option’s apiPath (e.g. api/vcms-shortcode/article) defines the prefix; the editor requests:

  • GET <apiPath>/search?search=<term> — while typing in the picker. Responds with a JSON list of objects {"value": "<id>", "label": "<display text>"} (optionally description and icon). The picker triggers the request only after at least one character was entered.

  • GET <apiPath>/item?value=<id> — when an existing widget is loaded. Responds with a single object of the same shape, or null.

A custom shortcode must provide both routes: if only /search exists, the picker finds entries while typing but shows an empty selection when a saved widget is reopened — /item is what restores the stored value’s label.

Every request carries the editor context as query parameters (sid, stoken, shp, editlanguage); routes are guarded by #[AdminSessionUser(roles: ['ROLE_ADMIN'])], so the current shop is resolved from shp and cross-shop access is rejected for non-mall admins. Use ContextInterface::getCurrentShopId() inside your service/repository to keep queries shop-scoped, and Language::getEditLanguage() (or the language-aware database view) to return titles in the editing language.

A minimal controller looks like this (compare TreeViewSearchController in the Visual CMS source):

use OxidEsales\SessionAuthComponent\Security\Attribute\AdminSessionUser;
use OxidEsales\VisualCmsModule\ShortCodeCollection\Transput\ShortCodeSearchRequestInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

class MyShortcodeSearchController
{
    public function __construct(
        private readonly ShortCodeSearchRequestInterface $request,
        private readonly MySearchServiceInterface $service,
    ) {
    }

    #[Route('/api/vcms-shortcode/myshortcode/search', methods: ['GET'])]
    #[AdminSessionUser(roles: ['ROLE_ADMIN'])]
    public function search(): JsonResponse
    {
        return new JsonResponse($this->service->find($this->request->getSearchTerm()));
    }

    #[Route('/api/vcms-shortcode/myshortcode/item', methods: ['GET'])]
    #[AdminSessionUser(roles: ['ROLE_ADMIN'])]
    public function item(): JsonResponse
    {
        return new JsonResponse($this->service->getById($this->request->getValue()));
    }
}

Register the controller as a public service (public: true) in your module’s services.yaml so the routing picks it up, and reference the prefix from the option: apiPath: 'api/vcms-shortcode/myshortcode'. Write the routes with a leading slash in the #[Route] attribute, but set apiPath without one. Build search queries with bound parameters (e.g. Doctrine’s createNamedParameter()) — never inline request values.