Study guide · Backend Development
Extending the TYPO3 backend: modules, JavaScript and messages
The backend is where editors and administrators work. On this page you extend it step by step with a module for conference registrations, JavaScript, AJAX, messages, a dashboard widget and the rich text editor.
Modules in the backend
A backend module is a dedicated view that you open from the module menu on the left. Layout, Records and Media are registered modules, too. Only logged-in backend users see modules, while a frontend plugin is a content element for website visitors.
Modules come as main modules and submodules, which TYPO3 14 renamed:
- Web became Content, with the identifier
content. - File became Media, with the identifier
media. - Site Management became Sites, and the identifier
sitestays. - Admin Tools became Administration, with the identifier
admin, for modules meant for administrators only. - System holds tools for system maintainers.
Among the submodules, Page is now Layout, List is now Records, View is now Preview and Workspaces is now Publish. Old identifiers still work through aliases, but a module below the old parent web should switch to content. The upgrade wizard “Migrate module permissions” carries over permissions.
Registering a module
Our extension my_extension gets a module “Conferences”. Modules are registered in Configuration/Backend/Modules.php, which returns an array keyed by module identifier.
return [
'content_conferences' => [
'parent' => 'content',
'access' => 'user',
'workspaces' => 'live',
'labels' => 'my_extension.module',
'iconIdentifier' => 'my-extension-module',
'navigationComponent' => '@typo3/backend/tree/page-tree-element',
'routes' => [
'_default' => ['target' => ConferenceModuleController::class . '::listAction'],
],
],
];parentplaces the module below a main module.accesscontrols who sees it.- Since TYPO3 14,
labelscan simply name a translation domain. The XLIFF file behind it contains the keys title, description and short_description. The short description appears as a tooltip. iconIdentifiernames an icon that you register inConfiguration/Icons.phpwith identifier, provider and source file.navigationComponentshows a tree on the left, here the page tree.workspacesknows an asterisk for everywhere, live, and offline for draft workspaces.
New in TYPO3 14: showSubmoduleOverview shows the allowed submodules as cards. The option dependsOnSubmodules under appearance hides the module when no submodule is available.
Checking what is registered: The system extension lowlevel provides the module System, Configuration. Under Backend Modules you see every module with its configuration, which is fixed at runtime. The old array TBE_MODULES is gone. The module also shows TYPO3_CONF_VARS, the TCA, backend routes and the order of the HTTP middlewares. Event Listeners lists every PSR-14 listener per event, in order. A missing listener usually means a wrong registration or a stale cache. Database credentials are masked. Since TYPO3 14 the Extbase persistence configuration is shown, too. On the command line lowlevel offers cleanup:missingrelations, cleanup:orphanrecords, cleanup:deletedrecords and configuration:show, and since TYPO3 14 also configuration:set and configuration:remove.
Who may see the module
The option access has three built-in values:
user: editors see the module when it is allowed in their backend user group.admin: administrators only. Such modules belong below Administration. Placing them there protects nothing on its own.systemMaintainer: system maintainers only. Such modules belong below System.
Access gates: Since TYPO3 14.2 you can add your own rules. A class implements ModuleAccessGateInterface and answers with Granted, Denied or Abstain. You register it with the attribute AsModuleAccessGate and an identifier such as conferenceManager. With before and after you order the gates. In the module you then set access to conferenceManager.
Sudo mode: For sensitive modules TYPO3 asks for your own password or the install tool password again. You set sudoMode under routeOptions, with a group and a lifetime, and the grant covers the whole group.
'routeOptions' => [
'sudoMode' => ['group' => 'conferenceAdmin', 'lifetime' => AccessLifetime::veryShort],
],Permissions in code: You check single actions yourself. The logged-in user is a BackendUserAuthentication object.
$backendUser = $GLOBALS['BE_USER'];
$isAdmin = $backendUser->isAdmin();
$isAdmin = $context->getPropertyFromAspect('backend.user', 'isAdmin');
$mayEdit = $backendUser->check('tables_modify', 'tx_myextension_registration');
$mayExport = $backendUser->getTSConfig()['options.']['myextension.']['enableExport'] ?? false;check() looks into the merged group permissions such as tables_modify or modules, and always returns true for administrators. The Context API is easier to replace in tests. User TSconfig belongs to users and groups, so it suits switches like “export allowed”.
The module controller
A controller without Extbase is a class with the attribute AsController. It sets the service tag backend.controller, which makes the class public in the container, so TYPO3 can create it with its dependencies. Without the attribute you set the tag in Services.yaml. You still register the module in Modules.php.
Every action receives a PSR-7 request of type ServerRequestInterface and returns a ResponseInterface. You read parameters with getQueryParams() or getParsedBody(), not with echo and superglobals.
The ModuleTemplate gives you the look of the core modules, including the DocHeader with breadcrumb, buttons and menus.
public function listAction(ServerRequestInterface $request): ResponseInterface
{
$view = $this->moduleTemplateFactory->create($request);
$view->assignMultiple(['registrations' => $this->registrationRepository->findAll()]);
return $view->renderResponse('Registration/List');
}With Extbase the controller extends ActionController, and Modules.php uses extensionName and controllerActions instead of routes. You still use the ModuleTemplate, not the controller's own view and not htmlResponse.
Subroutes: Next to the required route _default you add entries such as edit under routes. It is then called content_conferences.edit, that is module identifier, dot, subroute.
Request attributes: module holds the called module as a ModuleInterface. moduleData holds the user's remembered settings for this module. The option of the same name in Modules.php defines the allowed parameters and their defaults.
Buttons: Since TYPO3 14 the injected ComponentFactory creates the buttons in the DocHeader. The make methods of the ButtonBar are deprecated and will be removed in TYPO3 15.
$button = $this->componentFactory->createLinkButton()
->setHref($newUrl)
->setTitle('New registration')
->setIcon($this->iconFactory->getIcon('actions-add', IconSize::SMALL));
$view->getDocHeaderComponent()->getButtonBar()->addButton($button);You get icons from the IconFactory with the enum IconSize. It replaces the old size constants. In Fluid the ViewHelper core:icon does the same.
Pages, records and links
With a page tree, the backend passes the selected page as the parameter id. Anyone can change it in the URL, so you check access.
$id = (int)($request->getQueryParams()['id'] ?? 0);
$page = BackendUtility::readPageAccess($id, $backendUser->getPagePermsClause(Permission::PAGE_SHOW));More helpers from BackendUtility:
getRecord()loads a row by UID without deleted records, but does not check permissions.getRecordTitle()builds the title as the backend does everywhere, from label, label_alt and label_userFunc in the ctrl section.getPagesTSconfig()returns the Page TSconfig of the page, and subpages can override values. TYPO3 14 loads the fileConfiguration/page.tsconfigof an extension automatically.
Links: Backend URLs contain a security token, so you build them with the backend UriBuilder and buildUriFromRoute(). The editing form is the route record_edit. To edit, you pass table, UID and edit. To create, you pass table, page ID and new. The returnUrl decides where closing the form leads.
$newUrl = $this->uriBuilder->buildUriFromRoute('record_edit', [
'edit' => ['tx_myextension_registration' => [12 => 'new']],
'returnUrl' => (string)$request->getUri(),
]);
$editUrl = $this->uriBuilder->buildUriFromRoute('content_conferences.edit');In Fluid you use be:link.editRecord with uid and table. PreviewUriBuilder builds the frontend preview of a page with create and buildUri, including slug and language.
JavaScript in the backend
JavaScript runs in the browser, so it lives in the public folder Resources/Public. Resources/Private is only read by the server.
The backend uses native ES modules with import and export. RequireJS was removed in TYPO3 13. In Configuration/JavaScriptModules.php you register your modules, and TYPO3 builds an import map from it. An entry with a trailing slash maps a prefix to a folder. An entry without one maps a name to a single file, for example chart.js. Under dependencies you list extensions whose import map must be loaded as well. The web server does not deliver the node_modules folder.
return [
'dependencies' => ['core', 'backend'],
'imports' => [
'@my-vendor/my-extension/' => 'EXT:my_extension/Resources/Public/JavaScript/',
'chart.js' => 'EXT:my_extension/Resources/Public/JavaScript/Contrib/chart.js',
],
];Loading: In PHP with loadJavaScriptModule() on the PageRenderer, in Fluid with f:be.pageRenderer and includeJavaScriptModules. TYPO3 only outputs the import map when a module is actually loaded.
import Modal from '@typo3/backend/modal.js';
import DocumentService from '@typo3/core/document-service.js';
import RegularEvent from '@typo3/core/event/regular-event.js';
import DebounceEvent from '@typo3/core/event/debounce-event.js';
import labels from '~labels/my_extension.module';
DocumentService.ready().then(() => {
new RegularEvent('click', (event, button) => {
const modal = Modal.confirm(labels.get('delete.title'), labels.get('delete.text'));
modal.addEventListener('confirm.button.ok', () => { /* delete */ modal.hideModal(); });
}).delegateTo(document.querySelector('#registrations'), '.js-delete');
new DebounceEvent('input', search, 300).bindTo(document.querySelector('#search'));
});- DocumentService waits for the finished DOM, even if your module loads later.
- Modal shows dialogs in the backend style. confirm does not block, it returns the dialog. The dialog fires confirm.button.ok or confirm.button.cancel, and hideModal closes it.
- Labels are imported as a virtual module from the translation domain since TYPO3 14.2. They can be cached per version and language.
- Every import needs the extension .js. Only TypeScript leaves it out.
The Event API wraps addEventListener. bindTo attaches the listener to an element, to document or to window. delegateTo attaches it to a surrounding element and checks a selector, so it also works for rows inserted later. release removes it. There are four strategies:
- RegularEvent is the normal listener.
- DebounceEvent fires only after a pause, good for search fields.
- ThrottleEvent fires at most once per fixed interval, good for scrolling.
- RequestAnimationFrameEvent runs in step with the browser's repaints.
AJAX in the backend
To confirm a registration without reloading, you register a route in Configuration/Backend/AjaxRoutes.php, with path and target. Unlike a custom PHP script in the public folder, it runs in the TYPO3 context, with backend login, dependency injection and configuration.
return [
'myextension_registration_confirm' => [
'path' => '/my-extension/registration/confirm',
'target' => AjaxController::class . '::confirmAction',
'inheritAccessFromModule' => 'content_conferences',
],
];The controller usually returns a JsonResponse, which encodes an array as JSON and sets the content type. After changes, flush the caches. In JavaScript the URL is then available under TYPO3.settings.ajaxUrls with the name of the route.
import AjaxRequest from '@typo3/core/ajax/ajax-request.js';
const response = await new AjaxRequest(TYPO3.settings.ajaxUrls.myextension_registration_confirm)
.withQueryArguments({ registration: 17 })
.get();
const data = await response.resolve();AjaxRequest offers get, post, put and delete, and each returns a promise.
Messages for the user
After saving, a flash message says “Saved”. You choose the severity with the enum ContextualFeedbackSeverity and its five cases NOTICE, INFO, OK, WARNING and ERROR. Success is called OK, not SUCCESS. DEBUG and CRITICAL are PSR-3 log levels.
- In Extbase you call
addFlashMessage()on the controller. By default the message goes into the session and survives a redirect. The queue is called extbase.flashmessages plus the plugin namespace. - With the ModuleTemplate you call its
addFlashMessage(), which also stores in the session by default. - By hand you create a
FlashMessage. You get theFlashMessageServicethrough dependency injection. getMessageQueueByIdentifier without an argument returns the default queuecore.template.flashMessages, and enqueue adds the message.
The ViewHelper f:flashMessages outputs and removes all waiting messages. It works in any context, because it determines a matching renderer. Other queues need the argument queueIdentifier.
For a floating notification from PHP, use the queue FlashMessageQueue::NOTIFICATION_QUEUE.
In JavaScript, the backend-only Notification API reports “Attendance confirmed” after our AJAX call.
import Notification from '@typo3/backend/notification.js';
Notification.success('Confirmed', 'The attendance has been saved.');There are notice, info, success, warning and error. The duration is in seconds, and the default is 5. Errors stay, because 0 switches the timer off. Action buttons in notifications are optional, so for a real decision you use a modal.
Dashboard widgets
The dashboard is usually the first module, a personal start page with widgets such as key figures, lists or charts. Group permissions control which widgets editors may add.
For “Registrations today” you combine a core widget with your own data provider, without a widget class of your own. For a key figure it implements NumberWithIconDataProviderInterface, for a list ListDataProviderInterface. For a bar chart it implements ChartDataProviderInterface and is passed to the BarChartWidget.
You register the widget as a service in Services.yaml with the tag dashboard.widget.
dashboard.widget.my_vendor.my_extension.registrationsToday:
class: 'TYPO3\CMS\Dashboard\Widgets\NumberWithIconWidget'
arguments:
$dataProvider: '@MyVendor\MyExtension\Dashboard\RegistrationsTodayDataProvider'
tags:
- name: dashboard.widget
identifier: 'myExtensionRegistrationsToday'
groupNames: 'conferences'
title: 'my_extension.dashboard:registrationsToday.title'
description: 'my_extension.dashboard:registrationsToday.description'
iconIdentifier: 'content-widget-number'
height: 'small'
width: 'small'Through groupNames a widget belongs to one or more groups, which appear in the dialog for adding widgets. You create your own group in the file DashboardWidgetGroups.php in the folder Configuration, Backend, with identifier and title.
New in TYPO3 14 is the WidgetRendererInterface. With it a widget defines settings per instance in getSettingsDefinitions(), and editors change them right in the dashboard. That is how the RSS widget can run several times with different feeds.
A template for new users: In DashboardPresets.php in the same folder you describe a preset with title, icon and defaultWidgets. You assign it in User TSconfig.
options.dashboard.dashboardPresetsForNewUsers = conferencesThe rich text editor
For formatted text TYPO3 has shipped CKEditor 5 since version 12, through the system extension rte_ckeditor. A field gets the editor when its TCA type is text and enableRichtext is true. There is no type richtext.
A YAML preset decides the toolbar. The core ships default, minimal and full, and custom presets can import them.
$GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['conference'] = 'EXT:my_extension/Configuration/RTE/Conference.yaml';
// Page TSconfig: RTE.default.preset = conference
// TCA of a field: 'richtextConfiguration' => 'conference'The TypoScript lib.parseFunc_RTE outputs the text in the frontend later and has nothing to do with the editor.
Adjusting it in code: With the PSR-14 events BeforePrepareConfigurationForEditorEvent and AfterPrepareConfigurationForEditorEvent you change the editor configuration, for example the toolbar per user. For external plugins there is a Before and an AfterGetExternalPluginsEvent.
A different editor: rte_ckeditor registers a nodeResolver in FormEngine for text fields with enableRichtext. Your own nodeResolver with a higher priority replaces it.
Key points
- Since TYPO3 14 the main modules are Content, Media, Sites, Administration and System.
- Modules live in
Modules.php. After changes, flush the caches. - access knows user, admin and systemMaintainer, and since TYPO3 14.2 also custom access gates.
- Module controllers take a PSR-7 request and respond through the ModuleTemplate.
- The UriBuilder builds links, the ComponentFactory buttons.
- Backend JavaScript uses ES modules and an import map.
- Every logged-in backend user may call an AJAX route.
- The FlashMessage constructor does not store in the session, Extbase and the ModuleTemplate do.
Terms
- Access gate
- Class that decides about access to a module, since TYPO3 14.2.
- ComponentFactory
- Creates buttons and menus for the DocHeader since TYPO3 14.
- Data provider
- Supplies the data for a ready-made dashboard widget.
- DocHeader
- Header bar of a backend module with breadcrumb, buttons and menus.
- Import map
- Maps names of JavaScript modules to real files.
- Notification
- Floating message at the edge of the backend.
- Sudo mode
- Asking for the password again before a sensitive module.