Fluid ViewHelper Reference

Version

13.4

Language

en

Author

TYPO3 contributors

License

This document is published under the Creative Commons BY 4.0 license.

Rendered

Tue, 20 May 2025 01:30:25 +0000


This is a complete reference of all available Fluid view helpers in the TYPO3 Core.

Fluid is a PHP template engine and is the de facto standard for any HTML-based output in the TYPO3 CMS. However, it is not dependent on TYPO3 and can be used in any PHP project. See the Fluid standalone documentation.

Note: This documentation was generated from the PHP source code of TYPO3.


Table of Contents:

Global (f:*)

Asset.css ViewHelper <f:asset.css>

ViewHelper to add CSS to the TYPO3 AssetCollector. Either a file or inline CSS can be added.

Go to the source code of this ViewHelper: Asset\CssViewHelper.php (GitHub).

Arguments

The following arguments are available for the asset.css ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

disabled

disabled
Type
bool
Define whether or not the described stylesheet should be loaded and applied to the document.

identifier

identifier
Type
string
Required
1
Use this identifier within templates to only inject your CSS once, even though it is added multiple times.

inline

inline
Type
bool
Default
false
Define whether or not the referenced file should be loaded as inline styles (Only to be used if 'href' is set).

priority

priority
Type
boolean
Default
false
Define whether the CSS should be included before other CSS. CSS will always be output in the <head> tag.

useNonce

useNonce
Type
bool
Default
false
Whether to use the global nonce value

Examples

<f:asset.css identifier="identifier123" href="EXT:my_ext/Resources/Public/Css/foo.css" />
<f:asset.css identifier="identifier123">
   .foo { color: black; }
</f:asset.css>
Copied!

Details

In the AssetCollector, the "identifier" attribute is used as a unique identifier. Thus, if assets are added multiple times using the same identifier, the asset will only be served once (the last added overrides previous assets).

Some available attributes are defaults but do not make sense for this ViewHelper. Relevant attributes specific for this ViewHelper are: as, crossorigin, disabled, href, hreflang, importance, integrity, media, referrerpolicy, sizes, type, nonce.

Using the "inline" argument, the file content of the referenced file is added as inline style.

Asset.module ViewHelper <f:asset.module>

ViewHelper to add JavaScript modules to the TYPO3 AssetCollector.

Examples

<f:asset.module identifier="@my/package/filename.js"/>
Copied!

Details

In the AssetCollector, the "identifier" attribute is used as a unique identifier. Thus, if modules are added multiple times using the same module identifier, the asset will only be served once.

Go to the source code of this ViewHelper: Asset\ModuleViewHelper.php (GitHub).

Arguments

The following arguments are available for the asset.module ViewHelper:

identifier

identifier
Type
string
Required
1
Bare module identifier like "@my/package/filename.js".

Asset.script ViewHelper <f:asset.script>

ViewHelper to add JavaScript to the TYPO3 AssetCollector. Either a file or inline JavaScript can be added.

Go to the source code of this ViewHelper: Asset\ScriptViewHelper.php (GitHub).

Arguments

The following arguments are available for the asset.script ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

async

async
Type
bool
Define that the script will be fetched in parallel to parsing and evaluation.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

defer

defer
Type
bool
Define that the script is meant to be executed after the document has been parsed.

identifier

identifier
Type
string
Required
1
Use this identifier within templates to only inject your JS once, even though it is added multiple times.

inline

inline
Type
bool
Default
false
Define whether or not the referenced file should be loaded as inline script (Only to be used if 'src' is set).

nomodule

nomodule
Type
bool
Define that the script should not be executed in browsers that support ES2015 modules.

priority

priority
Type
boolean
Default
false
Define whether the JavaScript should be put in the <head> tag above-the-fold or somewhere in the body part.

useNonce

useNonce
Type
bool
Default
false
Whether to use the global nonce value

Examples

<f:asset.script identifier="identifier123" src="EXT:my_ext/Resources/Public/JavaScript/foo.js" />
<f:asset.script identifier="identifier123">
   alert('hello world');
</f:asset.script>
Copied!

Details

In the AssetCollector, the "identifier" attribute is used as a unique identifier. Thus, if assets are added multiple times using the same identifier, the asset will only be served once (the last added overrides previous assets).

Some available attributes are defaults but do not make sense for this ViewHelper. Relevant attributes specific for this ViewHelper are: async, crossorigin, defer, integrity, nomodule, nonce, referrerpolicy, src, type.

Using the "inline" argument, the file content of the referenced file is added as inline script.

Be.menus.actionMenu ViewHelper <f:be.menus.actionMenu>

ViewHelper which returns a select box that can be used to switch between multiple actions and controllers and looks similar to TYPO3s "funcMenu".

Note: This ViewHelper is experimental and tailored to be used only in extbase context.

Go to the source code of this ViewHelper: Be\Menus\ActionMenuViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.menus.actionMenu ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

defaultController

defaultController
Type
string
The default controller to be used

Examples

Simple:

<f:be.menus.actionMenu>
   <f:be.menus.actionMenuItem label="Overview" controller="Blog" action="index" />
   <f:be.menus.actionMenuItem label="Create new Blog" controller="Blog" action="new" />
   <f:be.menus.actionMenuItem label="List Posts" controller="Post" action="index" arguments="{blog: blog}" />
</f:be.menus.actionMenu>
Copied!

Select box with the options "Overview", "Create new Blog" and "List Posts".

Localized:

<f:be.menus.actionMenu>
   <f:be.menus.actionMenuItem label="{f:translate(key:'overview')}" controller="Blog" action="index" />
   <f:be.menus.actionMenuItem label="{f:translate(key:'create_blog')}" controller="Blog" action="new" />
</f:be.menus.actionMenu>
Copied!

Localized select box.

Be.menus.actionMenuItem ViewHelper <f:be.menus.actionMenuItem>

ViewHelper which returns an option tag within a <f:be.menus.actionMenu> group.

Note: This ViewHelper is experimental and tailored to be used only in extbase context.

Go to the source code of this ViewHelper: Be\Menus\ActionMenuItemViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.menus.actionMenuItem ViewHelper:

action

action
Type
string
Required
1
the action to be associated with this ActionMenuItem

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

arguments

arguments
Type
array
Default
array ( )
additional controller arguments to be passed to the action when this ActionMenuItem is selected

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

controller

controller
Type
string
Required
1
controller to be associated with this ActionMenuItem

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

label

label
Type
string
Required
1
label of the option tag

Examples

Simple:

<f:be.menus.actionMenu>
   <f:be.menus.actionMenuItem label="Overview" controller="Blog" action="index" />
   <f:be.menus.actionMenuItem label="Create new Blog" controller="Blog" action="new" />
   <f:be.menus.actionMenuItem label="List Posts" controller="Post" action="index" arguments="{blog: blog}" />
</f:be.menus.actionMenu>
Copied!

Select box with the options "Overview", "Create new Blog" and "List Posts".

Localized:

<f:be.menus.actionMenu>
   <f:be.menus.actionMenuItem label="{f:translate(key='overview')}" controller="Blog" action="index" />
   <f:be.menus.actionMenuItem label="{f:translate(key='create_blog')}" controller="Blog" action="new" />
</f:be.menus.actionMenu>
Copied!

Localized select box.

Be.menus.actionMenuItemGroup ViewHelper <f:be.menus.actionMenuItemGroup>

ViewHelper which groups options within a <f:be.menus.actionMenu> group.

NOTE: This ViewHelper is experimental and tailored to be used only in extbase context.

Go to the source code of this ViewHelper: Be\Menus\ActionMenuItemGroupViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.menus.actionMenuItemGroup ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

defaultController

defaultController
Type
string
Unused

label

label
Type
string
Default
''
The label of the option group

Example

<f:be.menus.actionMenu>
    <f:be.menus.actionMenuItem label="Default: Welcome" controller="Default" action="index" />
    <f:be.menus.actionMenuItem label="Community: get in touch" controller="Community" action="index" />

    <f:be.menus.actionMenuItemGroup label="Information">
        <f:be.menus.actionMenuItem label="PHP Information" controller="Information" action="listPhpInfo" />
        <f:be.menus.actionMenuItem label="Documentation" controller="Information" action="documentation" />
        <f:be.menus.actionMenuItem label="Hooks" controller="Information" action="hooks" />
        <f:be.menus.actionMenuItem label="Signals" controller="Information" action="signals" />
        <f:be.menus.actionMenuItem label="XClasses" controller="Information" action="xclass" />
    </f:be.menus.actionMenuItemGroup>
</f:be.menus.actionMenu>
Copied!

Be.security.ifAuthenticated ViewHelper <f:be.security.ifAuthenticated>

ViewHelper implementing an ifAuthenticated/else condition for backend users and backend groups.

Go to the source code of this ViewHelper: Be\Security\IfAuthenticatedViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.security.ifAuthenticated ViewHelper:

else

else
Type
mixed
Value to be returned if the condition if not met.

then

then
Type
mixed
Value to be returned if the condition if met.

Examples

Basic usage:

<f:be.security.ifAuthenticated>
   This is being shown whenever a BE user is logged in
</f:be.security.ifAuthenticated>
Copied!

Everything inside the <f:be.ifAuthenticated> tag is being displayed if the user is authenticated with any backend user account.

IfAuthenticated / then / else:

<f:be.security.ifAuthenticated>
   <f:then>
      This is being shown in case you have access.
   </f:then>
   <f:else>
      This is being displayed in case you do not have access.
   </f:else>
</f:be.security.ifAuthenticated>
Copied!

Everything inside the <f:then></f:then> is displayed the backend user is logged in. <f:else></f:else> is displayed if no backend user is logged in.

Be.security.ifHasRole ViewHelper <f:be.security.ifHasRole>

ViewHelper implementing an ifHasRole/else condition for backend users and backend groups ("Role").

Go to the source code of this ViewHelper: Be\Security\IfHasRoleViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.security.ifHasRole ViewHelper:

else

else
Type
mixed
Value to be returned if the condition if not met.

role

role
Type
string
The usergroup (either the usergroup uid or its title).

then

then
Type
mixed
Value to be returned if the condition if met.

Examples

Basic usage:

<f:be.security.ifHasRole role="Administrator">
   This is being shown in case the current BE user belongs to a BE usergroup (aka role) titled "Administrator" (case sensitive)
</f:be.security.ifHasRole>
Copied!

Everything inside the <f:ifHasRole> tag is being displayed if the logged in backend user belongs to the specified backend group.

Using the usergroup uid as role identifier:

<f:be.security.ifHasRole role="1">
   This is being shown in case the current BE user belongs to a BE usergroup (aka role) with the uid "1"
</f:be.security.ifHasRole>
Copied!

Everything inside the <f:ifHasRole> tag is being displayed if the logged in backend user belongs to the specified backend group.

IfRole / then / else:

<f:be.security.ifHasRole role="Administrator">
   <f:then>
      This is being shown in case you have the role.
   </f:then>
   <f:else>
      This is being displayed in case you do not have the role.
   </f:else>
</f:be.security.ifHasRole>
Copied!

Everything inside the <f:then></f:then> tag is displayed if the logged in backend user belongs to the specified backend group. Otherwise, everything inside the <f:else></f:else> tag is displayed.

Be.infobox ViewHelper <f:be.infobox>

A screenshot demonstrating a complex infobox with HTML content

See example Infobox with HTML content, icon and links

ViewHelper for rendering a styled content infobox markup.

Go to the source code of this ViewHelper: Be\InfoboxViewHelper.php (GitHub).

Severity states of the Be.infobox ViewHelper

The Infobox provides different context-sensitive states that can be used to provide an additional visual feedback to the

user to underline the meaning of the information.

Possible values are in range from -2 to 2. Please choose a meaningful value from the following list.

A screenshot demonstrating all possible infobox colors and states.

A demonstration of all possible states

-2
Notices (Default)
-1
Information
0
Positive feedback
1
Warnings
2
Error

It is considered best practice to use the states from \TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper together with the Constant ViewHelper <f:constant>:

EXT:my_extension/Resources/Private/Backend/Templates/MyModule.html
<f:be.infobox
    title="Some Info"
    message="The message"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_NOTICE')}"
/>
<f:be.infobox
    title="Some Notice"
    message="The message"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_INFO')}"
/>
<f:be.infobox
    title="Some sucess message"
    message="The message"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_OK')}"
/>
<f:be.infobox
    title="Some Warning"
    message="The message"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_WARNING')}"
/>
<f:be.infobox
    title="Some Error"
    message="The message"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_ERROR')}"
/>
Copied!

Examples

Info box of level notice with a static title and a static text:

EXT:my_extension/Resources/Private/Backend/Templates/MyModule.html
<f:be.infobox title="Message title">your box content</f:be.infobox>
Copied!

Warning box with disabled icon:

EXT:my_extension/Resources/Private/Backend/Templates/MyModule.html
<f:be.infobox
    title="Message title"
    message="your box content"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_WARNING')}"
    disableIcon="true"
/>
Copied!

Success box with custom icon:

EXT:my_extension/Resources/Private/Backend/Templates/MyModule.html
<f:be.infobox
    title="Message title"
    message="your box content"
    state="{f:constant(name: 'TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper::STATE_OK')}"
    iconName="check"
/>
Copied!

Arguments

disableIcon

disableIcon
Type
bool
Default
false
If set to TRUE, the icon is not rendered.

iconName

iconName
Type
string
Identifier of the icon as registered in the Icon Registry. NULL sets default icon

message

message
Type
string
The message of the info box, if NULL tag content is used

state

state
Type
int
Default
-2
The state of the box, InfoboxViewHelper::STATE_*

title

title
Type
string
The title of the info box

Be.pageInfo ViewHelper <f:be.pageInfo>

ViewHelper which returns the page info icon as known from TYPO3 backend modules.

Note: This ViewHelper is experimental!

Go to the source code of this ViewHelper: Be\PageInfoViewHelper.php (GitHub).

Examples

Default:

<f:be.pageInfo />
Copied!

Page info icon with context menu

Be.pagePath ViewHelper <f:be.pagePath>

ViewHelper which returns the current page path as known from TYPO3 backend modules.

Note: This ViewHelper is experimental!

Go to the source code of this ViewHelper: Be\PagePathViewHelper.php (GitHub).

Examples

Default:

<f:be.pagePath />
Copied!

Current page path, prefixed with "Path:" and wrapped in a span with the class typo3-docheader-pagePath.

Be.pageRenderer ViewHelper <f:be.pageRenderer>

ViewHelper to register backend module resources like CSS and JavaScript using the PageRenderer.

Go to the source code of this ViewHelper: Be\PageRendererViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.pageRenderer ViewHelper:

addInlineSettings

addInlineSettings
Type
array
Adds Javascript Inline Setting

addJsInlineLabels

addJsInlineLabels
Type
array
Custom labels to add to JavaScript inline labels

includeCssFiles

includeCssFiles
Type
array
List of custom CSS file to be loaded

includeJavaScriptModules

includeJavaScriptModules
Type
array
List of JavaScript modules to be loaded

includeJsFiles

includeJsFiles
Type
array
List of custom JavaScript file to be loaded

pageTitle

pageTitle
Type
string
Default
''
title tag of the module. Not required by default, as BE modules are shown in a frame

Examples

All options:

<f:be.pageRenderer
    pageTitle="foo"
    includeCssFiles="{0: 'EXT:my_ext/Resources/Public/Css/Stylesheet.css'}"
    includeJsFiles="{0: 'EXT:my_ext/Resources/Public/JavaScript/Library1.js', 1: 'EXT:my_ext/Resources/Public/JavaScript/Library2.js'}"
    addJsInlineLabels="{'my_ext.label1': 'LLL:EXT:my_ext/Resources/Private/Language/locallang.xlf:label1'}"
    includeJavaScriptModules="{0: '@my-vendor/my-ext/my-module.js'}"
    addInlineSettings="{'some.setting.key': 'some.setting.value'}"
/>
Copied!

This will load the specified css, js files and JavaScript modules, adds a custom js inline setting, and adds a resolved label to be used in js.

git :navigation-title: be.tableList

Be.tableList ViewHelper <f:be.tableList>

Screenshot of a table of categories.

ViewHelper which renders a record list as known from the TYPO3 list module.

Note: This feature is experimental!

Go to the source code of this ViewHelper: Be\TableListViewHelper.php (GitHub).

Table of contents

Examples

Display and make editable the content elements of page 1 and its direct children:

EXT:my_extension/Resources/Private/Backend/Templates/MyModule.html
<f:be.tableList
    tableName="tt_content"
    fieldList="{0: 'header', 1: 'CType'}"
    storagePid="1"
    levels="2"
    enableControlPanels="1"
/>
Copied!
Screenshot of a table of content elements with edit options.

List all categories on page 5 and make them editable when clicking the title:

EXT:my_extension/Resources/Private/Backend/Templates/MyModule.html
<f:be.tableList
    tableName="sys_category"
    fieldList="{0: 'title', 1: 'parent'}"
    storagePid="4"
    clickTitleMode="edit"
/>
Copied!
Screenshot of a table of categories.

Arguments

clickTitleMode

clickTitleMode
Type
string
Default
''
one of "edit", "show" (only pages, tt_content), "info

enableClickMenu

enableClickMenu
Type
bool
Default
true
enables context menu

enableControlPanels

enableControlPanels
Type
bool
Default
false
enables control panels

fieldList

fieldList
Type
array
Default
array ( )
list of fields to be displayed. If empty, only the title column (configured in $TCA[$tableName]['ctrl']['title']) is shown

filter

filter
Type
string
Default
''
corresponds to the "Search String" textbox of the TYPO3 list module. If not empty, only records matching the string will be fetched

levels

levels
Type
int
Default
0
corresponds to the level selector of the TYPO3 list module. By default only records from the current storagePid are fetched

readOnly

readOnly
Type
bool
Default
false
if TRUE, the edit icons won't be shown. Otherwise edit icons will be shown, if the current BE user has edit rights for the specified table!

recordsPerPage

recordsPerPage
Type
int
Default
0
amount of records to be displayed at once. Defaults to $TCA[$tableName]['interface']['maxSingleDBListItems'] or (if that's not set) to 100

sortDescending

sortDescending
Type
bool
Default
false
if TRUE records will be sorted in descending order

sortField

sortField
Type
string
Default
''
table field to sort the results by

storagePid

storagePid
Type
int
by default, records are fetched from the storage PID configured in persistence.storagePid. With this argument, the storage PID can be overwritten

tableName

tableName
Type
string
Required
1
name of the database table

Be.uri ViewHelper <f:be.uri>

ViewHelper for creating URIs to backend modules.

Go to the source code of this ViewHelper: Be\UriViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.uri ViewHelper:

parameters

parameters
Type
array
Default
array ( )
An array of parameters

referenceType

referenceType
Type
string
Default
'absolute'
The type of reference to be generated (one of the constants)

route

route
Type
string
Required
1
The name of the route

Examples

URI to the web_ts module on page 92:

<f:be.uri route="web_ts" parameters="{id: 92}"/>
Copied!

/typo3/module/web/ts?token=b6e9c9f&id=92

Inline notation:

{f:be.uri(route: 'web_ts', parameters: '{id: 92}')}
Copied!

/typo3/module/web/ts?token=b6e9c9f&id=92

Cache.disable ViewHelper <f:cache.disable>

ViewHelper to disable template compiling

Inserting this ViewHelper at any point in the template, including inside conditions which do not get rendered, will forcibly disable the caching/compiling of the full template file to a PHP class.

Use this if for whatever reason your platform is unable to create or load PHP classes (for example on read-only file systems or when using an incompatible default cache backend).

Passes through anything you place inside the ViewHelper, so can safely be used as container tag, as self-closing or with inline syntax - all with the same result.

Examples

Self-closing

<f:cache.disable />
Copied!

Inline mode

{f:cache.disable()}

Copied!

Container tag

<f:cache.disable>
   Some output or Fluid code
</f:cache.disable>
Copied!

Additional output is also not compilable because of the ViewHelper

Go to the source code of this ViewHelper: Cache\DisableViewHelper.php (GitHub).

Cache.static ViewHelper <f:cache.static>

ViewHelper to force compiling to a static string

Used around chunks of template code where you want the output of said template code to be compiled to a static string (rather than a collection of compiled nodes, as is the usual behavior).

The effect is that none of the child ViewHelpers or nodes used inside this tag will be evaluated when rendering the template once it is compiled. It will essentially replace all logic inside the tag with a plain string output.

Works by turning the compile method into a method that renders the child nodes and returns the resulting content directly as a string variable.

You can use this with great effect to further optimise the performance of your templates: in use cases where chunks of template code depend on static variables (like thoese in {settings} for example) and those variables never change, and the template uses no other dynamic variables, forcing the template to compile that chunk to a static string can save a lot of operations when rendering the compiled template.

NB: NOT TO BE USED FOR CACHING ANYTHING OTHER THAN STRING- COMPATIBLE OUTPUT!

USE WITH CARE! WILL PRESERVE EVERYTHING RENDERED, INCLUDING POTENTIALLY SENSITIVE DATA CONTAINED IN OUTPUT!

Examples

Usage and effect

<f:if condition="{var}">Is always evaluated also when compiled</f:if>
<f:cache.static>
    <f:if condition="{othervar}">
        Will only be evaluated once and this output will be
        cached as a static string with no logic attached.
        The compiled template will not contain neither the
        condition ViewHelperNodes or the variable accessor
        that are used inside this node.
    </f:if>
</f:cache.static>
Copied!

This is also evaluated when compiled (static node is closed):

<f:if condition="{var}">Also evaluated; is outside static node</f:if>
Copied!

Go to the source code of this ViewHelper: Cache\StaticViewHelper.php (GitHub).

Cache.warmup ViewHelper <f:cache.warmup>

ViewHelper to insert variables which only apply during cache warmup and only apply if no other variables are specified for the warmup process.

If a chunk of template code is impossible to compile without additional variables, for example when rendering sections or partials using dynamic names, you can use this ViewHelper around that chunk and specify a set of variables which will be assigned only while compiling the template and only when this is done as part of cache warmup. The template chunk can then be compiled using those default variables.

This does not imply that only those variable values will be used by the compiled template. It only means that DEFAULT values of vital variables will be present during compiling.

If you find yourself completely unable to properly warm up a specific template file even with use of this ViewHelper, then you can consider using f:cache.disable ViewHelper to prevent the template compiler from even attempting to compile it.

USE WITH CARE! SOME EDGE CASES OF FOR EXAMPLE VIEWHELPERS WHICH REQUIRE SPECIAL VARIABLE TYPES MAY NOT BE SUPPORTED HERE DUE TO THE RUDIMENTARY NATURE OF VARIABLES YOU DEFINE.

Examples

Usage and effect

<f:cache.warmup variables="{foo: bar}">
   Template code depending on {foo} variable which is not
   assigned when warming up Fluid's caches. {foo} is only
   assigned if the variable does not already exist and the
   assignment only happens if Fluid is in warmup mode.
</f:cache.warmup>
Copied!

Go to the source code of this ViewHelper: Cache\WarmupViewHelper.php (GitHub).

Arguments

The following arguments are available for the cache.warmup ViewHelper:

variables

variables
Type
array
Default
array ( )
Array of variables to assign ONLY when compiling. See main class documentation.

Debug.render ViewHelper <f:debug.render>

ViewHelper for a debuggable version of <f:render>. Performs the same rendering operation, but wraps the output with HTML that can be inspected with the admin panel in the frontend.

  <f:debug.render partial="Partials/SomePartial" arguments="{_all}" />
Copied!

Go to the source code of this ViewHelper: Debug\RenderViewHelper.php (GitHub).

Arguments

The following arguments are available for the debug.render ViewHelper:

arguments

arguments
Type
array
Default
array ( )
Array of variables to be transferred. Use {_all} for all variables

contentAs

contentAs
Type
string
If used, renders the child content and adds it as a template variable with this name for use in the partial/section

debug

debug
Type
boolean
Default
true
If true, the admin panel shows debug information if activated,

default

default
Type
mixed
Value (usually string) to be displayed if the section or partial does not exist

optional

optional
Type
boolean
Default
false
If TRUE, considers the *section* optional. Partial never is.

partial

partial
Type
string
Partial to render, with or without section

section

section
Type
string
Section to render - combine with partial to render section in partial

Form ViewHelper <f:form>

ViewHelper to generate a <form> tag and prepare context for further <f:form> ViewHelpers within that form. Tailored for Extbase plugins, uses Extbase Request.

Go to the source code of this ViewHelper: FormViewHelper.php (GitHub).

Array parameter passed to Extbase controller action

For example a very simplified search form could look like this:

packages/my_extension/Resources/Private/Templates/Search/SearchForm.html
<f:form action="search" method="post" pageUid="{settings.targetPid}">
    <div>
        <label for="sword">Search:</label>
        <f:form.textfield name="search[sword]" value="{sword}" id="sword" />
    </div>
    <div>
        <f:form.submit name="search[submitButton]" value="Submit" />
    </div>
</f:form>
Copied!

The Extbase controller action could for example look like this:

packages/my_extension/Classes/Controller/SearchController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class SearchController extends ActionController
{
    public function searchAction(array $search = []): ResponseInterface
    {
        // TODO: implement search
        return $this->htmlResponse();
    }
}
Copied!

Property mapping - using the form with a model

In most cases you will use the f:form ViewHelper with Extbase models or data objects.

For example, user could add a comment in such a form:

packages/my_extension/Resources/Private/Templates/Comment/_CommentForm.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">

<f:form action="create"
        controller="Comment"
        objectName="comment"
        object="{newComment}"
        method="post">

        <label for="tx-blogexample-email">E-Mail:</label>
        <f:form.textfield property="email"
                          type="email"
                          id="tx-blogexample-email" />

        <label for="tx-blogexample-content">Message:</label>
        <f:form.textarea property="content"
                         id="tx-blogexample-content"
                         rows="8"
                         cols="46" />

        <f:form.submit class="button"
                       value="Submit" />

</f:form>
</html>
Copied!

The Extbase Controller action displaying the form then creates the Domain object and passes it to the view. In the Fluid template above we use argument object to pass any data the object might already contain to the ViewHelper.

By using the argument "property" on the form input elements the properties of the model are automatically bound to the input elements.

The controller could look like this:

packages/my_extension/Classes/Controller/CommentController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use T3docs\BlogExample\Domain\Model\Comment;
use T3docs\BlogExample\Domain\Repository\CommentRepository;
use TYPO3\CMS\Extbase\Annotation\IgnoreValidation;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class CommentController extends ActionController
{
    public function __construct(
        protected readonly CommentRepository $commentRepository,
    ) {}

    #[IgnoreValidation(['argumentName' => 'newComment'])]
    public function commentFormAction(?Comment $newComment = null): ResponseInterface
    {
        if ($newComment === null) {
            $newComment = new Comment();
            $newComment->setDate(new \DateTime());
        }
        // The assigned object will be used in argument object
        $this->view->assign('newComment', $newComment);
        return $this->htmlResponse();
    }

    public function createAction(
        // This parameter must have the same name as argument `objectName` of f:form
        Comment $comment,
    ): ResponseInterface {
        $this->commentRepository->add($comment);
        $this->addFlashMessage('Comment was saved');
        return $this->redirect('show');
    }
}
Copied!

If the model is not valid (see Validation) Extbase will automatically refer the request back to the referring action (here commentFormAction()). By passing the object with the non-validated object to the view again, the user can see their faulty inputs and correct them instead of seeing an empty form.

Security in Fluid forms

Fluid automatically adds several hidden field to forms:

  • __referrer[] with an array of items @extension, @controller, @action, arguments and @request. This holds information about where the form has been created, so that in case of errors, redirection to the originating Extbase controller and action (and extension) is possible.
  • __trustedProperties (string) holds information about all used properties of all Extbase domain models that have been utilized within the related <f:form> context. This is used to ensure only properties will be evaluated for persistence that have an editable form field associated with them.

To prevent tampering with this vital data, the important fields (__referrer[arguments], __referrer[@request], __trustedProperties) are signed with the private TYPO3 encryption key using an HMAC hash.

An example would look like this:

Example HTML rendered after Fluid processing
<form action="/admin/update?token=328190ab378fe49af07d8b6b4ec31f87bd910efc" method="post">
  <div>
    <input type="hidden" name="__referrer[@extension]" value="Beuser">
    <input type="hidden" name="__referrer[@controller]" value="BackendUser">
    <input type="hidden" name="__referrer[@action]" value="list">
    <input type="hidden" name="__referrer[arguments]" value="YTozOntzOjEwOiJjb250cm9sbGVyIjtzOjExOiJCYWNrZW5kVXNlciI7czo2OiJhY3Rpb24iO3M6NToiaW5kZXgiO3M6NToidG9rZW4iO3M6NDA6IjgxNWZhOGI0OGYyZDg0N2NkMzcwYWIzYTkyMjhlNDY2OWI4OTI0MmUiO30=b305f0773528375502f167cde7c6c63f6ba988f9">
    <input type="hidden" name="__referrer[@request]" value="{&quot;@extension&quot;:&quot;Beuser&quot;,&quot;@controller&quot;:&quot;BackendUser&quot;,&quot;@action&quot;:&quot;list&quot;}51b024523b594011fa9054f7fc82c03ead78061b">
    <input type="hidden" name="__trustedProperties" value="{&quot;demand&quot;:{&quot;userName&quot;:1,&quot;userType&quot;:1,&quot;status&quot;:1,&quot;logins&quot;:1,&quot;backendUserGroup&quot;:1},&quot;operation&quot;:1}c25fc9eb44fc0e40e8ec5cf39fc5d21022172ebf">
  </div>
</form>
Copied!

If form fields are added or removed via attacks, Extbase detects the mismatch and blocks further processing.

Form fields can be grouped in an array for efficient processing. An internal Extbase processing action maps the received data to a model, where (optional and configurable) validation occurs. Only valid data is passed on to the action and stored in the database.

Arguments of the form ViewHelper

absolute

absolute
Type
bool
Default
false
If set, an absolute action URI is rendered (only active if $actionUri is not set)

action

action
Type
string
Target action

actionUri

actionUri
Type
string
can be used to overwrite the "action" attribute of the form tag

addQueryString

addQueryString
Type
string
Default
false
If set, the current query parameters will be kept in the URL. If set to "untrusted", then ALL query parameters will be added. Be aware, that this might lead to problems when the generated link is cached.

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

additionalParams

additionalParams
Type
array
Default
array ( )
additional action URI query parameters that won't be prefixed like $arguments (overrule $arguments) (only active if $actionUri is not set)

arguments

arguments
Type
array
Default
array ( )
Arguments (do not use reserved keywords "action", "controller" or "format" if not referring to these internal variables specifically)

argumentsToBeExcludedFromQueryString

argumentsToBeExcludedFromQueryString
Type
array
Default
array ( )
arguments to be removed from the action URI. Only active if $addQueryString = TRUE and $actionUri is not set

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

controller

controller
Type
string
Target controller

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

extensionName

extensionName
Type
string
Target Extension Name (without `tx_` prefix and no underscores). If NULL the current extension name is used

fieldNamePrefix

fieldNamePrefix
Type
string
Prefix that will be added to all field names within this form. If not set the prefix will be tx_yourExtension_plugin

format

format
Type
string
Default
''
The requested format (e.g. ".html") of the target page (only active if $actionUri is not set)

hiddenFieldClassName

hiddenFieldClassName
Type
string
hiddenFieldClassName

method

method
Type
string
Default
'post'
Transfer type (get or post)

name

name
Type
string
Name of form

noCache

noCache
Type
bool
Default
false
set this to disable caching for the target page. You should not need this.

novalidate

novalidate
Type
bool
Indicate that the form is not to be validated on submit.

object

object
Type
mixed
Object to use for the form. Use in conjunction with the "property" attribute on the sub tags

objectName

objectName
Type
string
name of the object that is bound to this form. If this argument is not specified, the name attribute of this form is used to determine the FormObjectName

pageType

pageType
Type
int
Default
0
Target page type

pageUid

pageUid
Type
int
Target page uid

pluginName

pluginName
Type
string
Target plugin. If empty, the current plugin name is used

requestToken

requestToken
Type
mixed
whether to add that request token to the form

section

section
Type
string
Default
''
The anchor to be added to the action URI (only active if $actionUri is not set)

signingType

signingType
Type
string
which signing type to be used on the request token (falls back to "nonce")

ViewHelpers for form input elements

Form.button ViewHelper <f:form.button>

This ViewHelper creates a <button> HTML element within the Form ViewHelper <f:form>.

Unlike the Form.submit ViewHelper <f:form.submit>, the Form.button ViewHelper can contain HTML content — for example, an icon.

By using the type argument, you can create button types other than submit, such as button or reset.

Go to the source code of this ViewHelper: Form\ButtonViewHelper.php (GitHub).

A Fluid form with a submit button containing an icon

You can use the <f:form.button> ViewHelper within an Extbase form to render a <button type="submit"> element that allows HTML content.

This is especially useful when you want to include custom elements inside the button, such as icons or styled spans.

When the user clicks the button, the action specified by the surrounding <f:form> is triggered.

packages/my_extension/Resources/Private/Templates/Comment/Edit.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">
<f:form action="submit" controller="Comment" objectName="comment" object="{comment}" method="post">
    <label for="tx-blogexample-content">Message:</label>
    <f:form.textarea property="content" id="tx-blogexample-content" rows="8" cols="46" />

    <f:form.button>
        <i class="fa fa-paper-plane"></i> Submit
    </f:form.button>
</f:form>
</html>
Copied!

You can use the same Extbase controller as in the example A Fluid form with a single submit button, which uses the <f:form.submit> ViewHelper.

A Fluid form with multiple buttons of different types

The <f:form.button> ViewHelper supports the type attribute, allowing you to render buttons of type submit, reset, or button. This is useful when you want to offer multiple actions within the same form, each with a distinct purpose and custom styling or icons.

Unlike <f:form.submit>, you can include inline HTML (e.g. icons, spans) in each button.

packages/my_extension/Resources/Private/Templates/Comment/Edit.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">
<f:form action="submit" controller="Comment" object="{comment}" objectName="comment" method="post">
    <label for="tx-comment-content">Message:</label>
    <f:form.textarea property="content" id="tx-comment-content" rows="6" cols="50" />

    <f:form.button type="submit" name="action" value="save">
        <i class="fa fa-save" aria-hidden="true"></i> Save
    </f:form.button>

    <f:form.button type="reset">
        <i class="fa fa-undo" aria-hidden="true"></i> Reset
    </f:form.button>

    <f:form.button type="button" name="preview" value="1" onclick="alert('Preview not implemented!')">
        <i class="fa fa-eye" aria-hidden="true"></i> Preview
    </f:form.button>
</f:form>
</html>
Copied!

A single Extbase controller action can be used to differentiate the submitted action based on the button name or value.

packages/my_extension/Classes/Controller/CommentController.php
<?php

namespace Vendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\Comment;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class CommentController extends ActionController
{
    public function submitAction(Comment $comment, string $action): ResponseInterface
    {
        switch ($action) {
            case 'save':
                // Save logic here
                $this->addFlashMessage('Comment saved!');
                return $this->redirect('edit');

            case 'preview':
                // Assign preview-related data and render the same view
                $this->view->assign('preview', true);
                $this->view->assign('comment', $comment);
                return $this->htmlResponse();

            default:
                $this->addFlashMessage('Unknown action');
                return $this->redirect('edit');
        }
    }
}
Copied!

A button with additional HTML5 attributes

The <f:form.button> ViewHelper allows you to pass through standard HTML5 button attributes such as disabled, formmethod, and formnovalidate.

This is useful when you need more control over how the button behaves in relation to form submission and validation.

packages/my_extension/Resources/Private/Templates/Comment/Edit.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">
<f:form action="submit" controller="Comment" method="post">
    <f:form.button type="reset"
                   name="cancel"
                   value="cancel"
                   disabled="disabled"
                   formmethod="post"
                   formnovalidate="formnovalidate">
        Cancel
    </f:form.button>
</f:form>
</html>
Copied!

A button with accessibility attributes

The <f:form.button> ViewHelper supports accessibility attributes like aria-label, aria-disabled, or aria-describedby.

These attributes are passed directly to the rendered <button> tag, allowing you to make your forms more accessible for assistive technologies such as screen readers.

For convenience, you can also use the aria attribute and pass an array to it.

Fluid will automatically generate the corresponding aria-* attributes based on the key-value pairs in the array.

packages/my_extension/Resources/Private/Templates/Comment/Edit.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">
<f:form action="submit" controller="Comment" object="{comment}" objectName="comment" method="post">
    <label for="tx-comment-content">Message:</label>
    <f:form.textarea property="content" id="tx-comment-content" rows="6" cols="50" />
    <p id="commentHint" class="form-text">
        Press the send button to submit your comment.
    </p>

    <f:form.button type="submit" aria="{label: 'Send comment', describedby: 'commentHint'}">
        <i class="fa fa-paper-plane" aria-hidden="true"></i> Send
    </f:form.button>
</f:form>
</html>
Copied!

Arguments of the form.button ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

type

type
Type
string
Default
'submit'
Specifies the type of button (e.g. "button", "reset" or "submit")

value

value
Type
mixed
Value of input tag

Form.checkbox ViewHelper <f:form.checkbox>

ViewHelper which renders a simple checkbox <input type="checkbox">.

Go to the source code of this ViewHelper: Form\CheckboxViewHelper.php (GitHub).

Single checkboxes

A single checkbox is usually mapped to a boolean property or controller argument.

However due to how checkboxes work in HTML a non-checked checkbox does not appear in the request sent by the form submission. Therefore properties and arguments need to default to false. They will then be set to true if the checkbox was checked.

While the value does not play a role when you are working with a checkbox, the argument must still be supplied.

Single optional checkbox tied to an action argument

Checkboxes in HTML work a little different from other input fields in that multiple or none at all can be checked.

Fluid outputs a normal HTML <input type="checkbox" ...> and some of the pitfalls also apply here. Especially a check box that is not sends no argument to the request.

packages/my_extension/Resources/Private/Templates/Comment/Newsletter.html
<f:form action="orderNewsletter" method="post">
    <div>
        <f:form.checkbox name="orderNewsletter" id="orderNewsletter" value="yes" />
        <label for="orderNewsletter">Order newsletter</label>
    </div>
    <div>
        <f:form.submit value="Submit" />
    </div>
</f:form>
Copied!

Then the controller action can then look like this:

packages/my_extension/Classes/Controller/NewsletterController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        // If the checkbox is not checked, no argument is provided.
        // Default to false
        bool $orderNewsletter = false,
    ): ResponseInterface {
        if ($orderNewsletter) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
}
Copied!

The checkbox should already by checked / preselected

<f:form.checkbox name="accept" value="yes" checked="true" />
Copied!

You can also use a variable to determine whether the field should be checked:

<f:form.checkbox name="accept" value="yes" checked="{myVariable} == 5" />
Copied!

Property mapping - domain model property bound to single checkbox

If you are using the form with a model you can use the argument property to map the checkbox to a property of your domain model or data object:

packages/my_extension/Resources/Private/Templates/Newsletter/SomeForm.html
<f:form action="orderNewsletter" method="post" object="user" objectName="user">
    <div>
        <f:form.checkbox property="orderNewsletter" id="orderNewsletter" value="yes" />
        <label for="orderNewsletter">Order newsletter</label>
    </div>
    <div>
        <f:form.submit value="Submit" />
    </div>
</f:form>
Copied!

Then the controller action can look like this:

packages/my_extension/Classes/Controller/NewsletterController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\User;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        User $user,
    ): ResponseInterface {
        if ($user->isOrderNewsletter()) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
}
Copied!

An unchecked checkbox results in the property not being set. It should therefore default to false.

packages/my_extension/Classes/Domain/Model/User.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class User extends AbstractEntity
{
    protected bool $orderNewsletter = false;

    public function isOrderNewsletter(): bool
    {
        return $this->orderNewsletter;
    }

    public function setOrderNewsletter(bool $orderNewsletter): void
    {
        $this->orderNewsletter = $orderNewsletter;
    }

}
Copied!

If the property in the domain model is true when the form is displayed, the checkbox is preselected.

Multiple checkboxes for the same property

Unlike other input elements, multiple checkboxes can be used for the same property or action argument.

In this case they share the same name or property binding property but have distinct values.

If you are working with action arguments, multiple must be set.

Multiple checkboxes mapped to an array in a controller action

Multiple checkboxes are usually mapped to an array. It would however be possible, for example, to map them to an integer using binaries or such.

Therefore when working with multiple checkboxes and arrays, you have to tell Extbase how to map the data from the request to your controller action in an initialize action.

packages/my_extension/Resources/Private/Templates/Newsletter/SomeForm.html
<f:form action="orderNewsletter" method="post">
    <f:for each="{newsletterList}" as="newsletter" iteration="i">
        <div>
            <f:form.checkbox name="orderNewsletters" id="newsletter{i.cycle}" value="{newsletter.uid}" />
            <label for="newsletter{i.cycle}">{newsletter.title}</label>
        </div>
    </f:for>
    <div><f:form.submit value="Submit" /></div>
</f:form>
Copied!

Then the controller action can look like this:

packages/my_extension/Classes/Controller/NewsletterController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Property\TypeConverter\ArrayConverter;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        // This argument is mapped in initializeOrderNewsletterAction()
        array $orderNewsletters = [],
    ): ResponseInterface {
        if ($orderNewsletters !== []) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
    public function initializeOrderNewsletterAction()
    {
        if ($this->request->hasArgument('orderNewsletters')) {
            $this->arguments['orderNewsletters']
                ->getPropertyMappingConfiguration()
                ->setTypeConverterOption(
                    ArrayConverter::class,
                    ArrayConverter::CONFIGURATION_DELIMITER,
                    ',',
                );
        }
    }
}
Copied!

Property mapping of multiple checkboxes

When working with multiple checkboxes mapped to the property of an Extbase model or data object, the same property is used for all checkboxes to be mapped to that property.

Multiple checkboxes for multiple independent properties

When multiple checkboxes should be used independently they must have unique name properties to map to multiple action arguments or unique property values to bind to multiple properties.

Mandatory checkboxes - require a checkbox to be set

On the browser side you can use the HTML 5 "required" Attribute. As the <f:form.checkbox> ViewHelper allows arbitrary arguments, using the required property is possible even though it is not listed.

packages/my_extension/Resources/Private/Templates/Newsletter/SomeForm.html
<f:flashMessages/>
<f:form action="orderNewsletter" method="post" object="user" objectName="user">
    <div>
        <f:form.checkbox property="consentGiven" id="consentGiven" value="yes" required="required"/>
        <label for="consentGiven">I have accepted the terms and conditions</label>
    </div>
    <div>
        <f:form.submit value="Submit" />
    </div>
</f:form>
Copied!

Then the controller action can then look like this:

packages/my_extension/Classes/Controller/NewsletterController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\User;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        User $user,
    ): ResponseInterface {
        if ($user->isOrderNewsletter()) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
}
Copied!

You should also validate the model for the property to be true:

packages/my_extension/Classes/Domain/Model/User.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\Annotation\Validate;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class User extends AbstractEntity
{
    #[Validate([
        'validator' => 'Boolean',
        'options' => ['is' => true],
    ])]
    protected bool $consentGiven = false;

    public function isConsentGiven(): bool
    {
        return $this->consentGiven;
    }

    public function setConsentGiven(bool $consentGiven): void
    {
        $this->consentGiven = $consentGiven;
    }
}
Copied!

If the server side validation on the model fails, the request is forwarded to the originating request with an error message.

Arguments

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

checked

checked
Type
bool
Specifies that the input element should be preselected

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

multiple

multiple
Type
bool
Default
false
Specifies whether this checkbox belongs to a multivalue (is part of a checkbox group)

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
string
Required
1
Value of input tag. Required for checkboxes

Form.countrySelect ViewHelper <f:form.countrySelect>

ViewHelper which renders a <select> tag with all or specific countries as options.

Go to the source code of this ViewHelper: Form\CountrySelectViewHelper.php (GitHub).

Examples

Basic usage

<f:form.countrySelect name="country" value="{defaultCountry}" />
Copied!

Output:

<select name="country">
  <option value="BE">Belgium</option>
  <option value="FR">France</option>
  ....
</select>
Copied!

Prioritize countries

Define a list of countries which should be listed as first options in the form element:

  <f:form.countrySelect
    name="country"
    value="AT"
    prioritizedCountries="{0: 'DE', 1: 'AT', 2: 'CH'}"
  />

Additionally, Austria is pre-selected.
Copied!

Display another language

A combination of optionLabelField and alternativeLanguage is possible. For instance, if you want to show the localized official names but not in your default language but in French. You can achieve this by using the following combination:

<f:form.countrySelect
  name="country"
  optionLabelField="localizedOfficialName"
  alternativeLanguage="fr"
  sortByOptionLabel="true"
/>
Copied!

Bind an object

You can also use the "property" attribute if you have bound an object to the form. See <f:form> for more documentation.

Arguments of f:form.countrySelect

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

alternativeLanguage

alternativeLanguage
Type
string
If specified, the country list will be shown in the given language.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

excludeCountries

excludeCountries
Type
array
Default
array ( )
Array with country codes that should not be shown.

multiple

multiple
Type
boolean
Default
false
If set multiple options may be selected.

name

name
Type
string
Name of input tag

onlyCountries

onlyCountries
Type
array
Default
array ( )
If set, only the country codes in the list are rendered.

optionLabelField

optionLabelField
Type
string
Default
'localizedName'
If specified, will call the appropriate getter on each object to determine the label. Use "name", "localizedName", "officialName" or "localizedOfficialName"

prependOptionLabel

prependOptionLabel
Type
string
If specified, will provide an option at first position with the specified label.

prependOptionValue

prependOptionValue
Type
string
If specified, will provide an option at first position with the specified value.

prioritizedCountries

prioritizedCountries
Type
array
Default
array ( )
A list of country codes which should be listed on top of the list.

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

required

required
Type
boolean
Default
false
If set no empty value is allowed.

sortByOptionLabel

sortByOptionLabel
Type
boolean
Default
false
If true, List will be sorted by label.

value

value
Type
mixed
Value of input tag

Form.hidden ViewHelper <f:form.hidden>

ViewHelper which renders an <input type="hidden" ...> tag.

Go to the source code of this ViewHelper: Form\HiddenViewHelper.php (GitHub).

Hidden field bound to a controller argument

Hidden fields can be used to pass additional arguments to a controller action.

The form includes a hidden field to pass the blog post UID:

packages/my_extension/Resources/Private/Templates/Comment/Form.html
<f:form action="save" controller="Comment" method="post">
    <f:form.hidden name="commentId" value="{comment.id}" />
    <f:form.textfield name="message" value="{comment.message}" />
    <f:form.submit value="Save" />
</f:form>
Copied!

The controller action can then look like this:

packages/my_extension/Classes/Controller/CommentController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        // If the checkbox is not checked, no argument is provided.
        // Default to false
        bool $orderNewsletter = false,
    ): ResponseInterface {
        if ($orderNewsletter) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
}
Copied!

Use case: Creating a comment for a specific blog post

You have:

  • A Comment domain model that relates to a BlogPost
  • A BlogPost detail page that includes a comment form
  • The property blogPost is set automatically and not selectable by the user
packages/my_extension/Resources/Private/Templates/Comment/CreateForm.html
<f:form action="create" controller="Comment" method="post" object="{comment}">
    <f:form.hidden property="blogPost" value="{blogPost.uid}" />
    <f:form.textfield property="authorName" />
    <f:form.textarea property="content" />
    <f:form.submit value="Submit Comment" />
</f:form>
Copied!

The domain model includes a relation to the BlogPost entity:

packages/my_extension/Classes/Domain/Model/Comment.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class Comment extends AbstractEntity
{
    protected string $authorName = '';
    protected string $content = '';
    protected BlogPost $blogPost;

    // Getters and setters...
}
Copied!

The controller saves the comment and redirects to the related blog post:

packages/my_extension/Classes/Controller/CommentController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\Comment;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class CommentController extends ActionController
{
    public function createAction(Comment $comment): ResponseInterface
    {
        // $comment->getBlogPost() returns the associated BlogPost object
        $this->commentRepository->add($comment);
        $this->addFlashMessage('Your comment was submitted!');
        return $this->redirect('show', 'BlogPost', null, ['blogPost' => $comment->getBlogPost()]);
    }
}
Copied!

Arguments of the form hidden ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

respectSubmittedDataValue

respectSubmittedDataValue
Type
bool
Default
true
enable or disable the usage of the submitted values

value

value
Type
mixed
Value of input tag

Form.password ViewHelper <f:form.password>

ViewHelper which renders a simple password text box <input type="password">.

Go to the source code of this ViewHelper: Form\PasswordViewHelper.php (GitHub).

A basic password field

The basic usage sets a name and renders a password input:

Resources/Private/Templates/User/LoginForm.html
<f:form action="login" controller="User" method="post">
    <label for="password">Password:</label>
    <f:form.password name="myPassword" id="password" />
    <f:form.submit value="Login" />
</f:form>
Copied!
<input type="password" name="myPassword" value="" />
Copied!

Binding to a model property

You can bind the password field to a property in an Extbase model. This requires the form to define the object and objectName as well.

Resources/Private/Templates/User/RegisterForm.html
<f:form action="register" controller="User" method="post"
        objectName="user" object="{newUser}">

    <label for="username">Username:</label>
    <f:form.textfield property="username" id="username" />

    <label for="password">Password:</label>
    <f:form.password property="password"
                     id="password"
                     aria="{required: 'true'}"
                     autocomplete="new-password" />

    <f:form.submit value="Register" />
</f:form>
Copied!

Excursion: Validation and hashing of password fields

A password should be validated against the Password policy and must always be hashed before saving. Never save a plain text password to the database.

Classes/Domain/Model/User.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\Annotation\ORM\Transient;
use TYPO3\CMS\Extbase\Annotation\Validate;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class User extends AbstractEntity
{
    #[Validate(['validator' => 'NotEmpty'])]
    public string $username = '';

    // Never save a plaintext password to the database. Make it transient to
    // prevent saving
    #[Transient]
    #[Validate(['validator' => 'NotEmpty'])]
    #[Validate(['validator' => 'StringLength', 'options' => ['minimum' => 8]])]
    public string $plainTextPassword = '';

    // Saved the hashed password to the database
    public string $password = '';
}
Copied!
Classes/Controller/UserController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\User;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory;
use TYPO3\CMS\Core\PasswordPolicy\PasswordPolicyAction;
use TYPO3\CMS\Core\PasswordPolicy\PasswordPolicyValidator;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class UserController extends ActionController
{
    public function __construct(
        private readonly PasswordHashFactory $passwordHashFactory,
        private readonly UserRepository $userRepository,
    ) {}

    public function registerFormAction(?User $user = null): ResponseInterface
    {
        $this->view->assign('newUser', $user ?? new User());
        return $this->htmlResponse();
    }

    public function registerAction(User $user): ResponseInterface
    {
        $passwordValidator = new PasswordPolicyValidator(
            PasswordPolicyAction::NEW_USER_PASSWORD,
        );
        // validate password against password policy
        if (!$passwordValidator->isValidPassword($user->plainTextPassword)) {
            foreach ($passwordValidator->getValidationErrors() as $error) {
                $this->addFlashMessage('Password is not correct: ' . $error);
            }
            // Unset the plain text password before returning it to the view
            $user->plainTextPassword = '';
            return $this->redirect('registerForm', null, null, ['user' => $user]);
        }

        // Hash password using the default hash instance for the Frontend
        // NEVER save a plain text password to the database!
        $user->password = $this->passwordHashFactory
            ->getDefaultHashInstance('FE')
            ->getHashedPassword($user->plainTextPassword);
        $this->userRepository->update($user);

        $this->addFlashMessage('Password was saved.');
        return $this->redirect('registerForm');
    }
}
Copied!

The example above shows validation inlined in an action of the controller for brevity. For re-usability and better architecture following best practices, you can create a custom validator for this: Custom Extbase validator implementation.

ARIA and data attributes

You can pass aria-* and data-* attributes as arrays to the aria and data arguments for accessibility and JavaScript validation support.

<f:form.password property="password"
                 aria="{required: 'true'}"
                 data="{toggle: 'password'}" />
Copied!

Arguments

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
mixed
Value of input tag

Form.radio ViewHelper <f:form.radio>

ViewHelper which renders a simple radio button <input type="radio">.

Go to the source code of this ViewHelper: Form\RadioViewHelper.php (GitHub).

Basic yes/no radio buttons tied to an action argument

The following shows two radio buttons, the one labeled "No" is preselected.

packages/my_extension/Resources/Private/Templates/Comment/Newsletter.html
<f:form action="orderNewsletter" method="post">
    <div>
        <f:form.checkbox name="orderNewsletter" id="orderNewsletter" value="yes" />
        <label for="orderNewsletter">Order newsletter</label>
    </div>
    <div>
        <f:form.submit value="Submit" />
    </div>
</f:form>
Copied!

The controller action can then look like this:

packages/my_extension/Classes/Controller/NewsletterController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        // If the checkbox is not checked, no argument is provided.
        // Default to false
        bool $orderNewsletter = false,
    ): ResponseInterface {
        if ($orderNewsletter) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
}
Copied!

Property mapping - Radio buttons bound to a model

The radio buttons from this example look the same as those from the previous example, however an object of type User is now provided as parameter for the Extbase action.

packages/my_extension/Resources/Private/Templates/Newsletter/SomeForm.html
<f:form action="orderNewsletter" method="post" object="user" objectName="user">
    <div>
        <f:form.checkbox property="orderNewsletter" id="orderNewsletter" value="yes" />
        <label for="orderNewsletter">Order newsletter</label>
    </div>
    <div>
        <f:form.submit value="Submit" />
    </div>
</f:form>
Copied!

Then the controller action can look like this:

packages/my_extension/Classes/Controller/NewsletterController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\User;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class NewsletterController extends ActionController
{
    public function orderNewsletterAction(
        User $user,
    ): ResponseInterface {
        if ($user->isOrderNewsletter()) {
            // TODO: Newsletter ordering
        }
        return $this->htmlResponse();
    }
}
Copied!
packages/my_extension/Classes/Domain/Model/User.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class User extends AbstractEntity
{
    protected bool $orderNewsletter = false;

    public function isOrderNewsletter(): bool
    {
        return $this->orderNewsletter;
    }

    public function setOrderNewsletter(bool $orderNewsletter): void
    {
        $this->orderNewsletter = $orderNewsletter;
    }

}
Copied!

Radio buttons with options from an array or query result

The form radio ViewHelper does not supply an argument that creates it from an array as you might have seen for the form select ViewHelper (Select field for selecting (persisted) models).

You can however just use the For ViewHelper <f:for> to iterate your items and display them one by one. If you use the objects uid for the key, the radio button can be matched to the model in use.

The Fluid template can be left unchanged even though we are dealing with a different data source:

packages/my_extension/Resources/Private/Templates/User/PaymentForm.html
<f:form action="selectPayment">
    <f:form.select name="payment" options="{paymentOptions}" value="{myPayment}" />
    <f:form.submit value="Submit"/>
</f:form>
Copied!
packages/my_extension/Classes/Domain/Model/PaymentMethod.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class PaymentMethod extends AbstractEntity implements \Stringable
{
    protected string $title;
    protected string $paymentIdentifier;

    // Getters and setters

    // If the model implement the __toString() method
    // The result of that method is displayed in the select form
    public function __toString(): string
    {
        return $this->title;
    }
}
Copied!

In the controller we can get all payment methods from the Repository now and pass it to the view as variable:

packages/my_extension/Classes/Controller/UserController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class UserController extends ActionController
{
    public function __construct(
        protected readonly PaymentMethodRepository $paymentMethodRepository,
    ) {}

    public function paymentFormAction(): ResponseInterface
    {
        $paymentOptions = $this->paymentMethodRepository->findAll();
        $this->view->assign('paymentOptions', $paymentOptions);
        $this->view->assign('myPayment', 'visa');
        return $this->htmlResponse();
    }
    public function selectPaymentAction(PaymentMethod $payment): ResponseInterface
    {
        // do something
        return $this->redirect('show');
    }
}
Copied!

Multiple radio button groups

Only one radio button per group can be checked at a time. Each group has the same name or property.

Arguments of the form radio ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

checked

checked
Type
bool
Specifies that the input element should be preselected

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
string
Required
1
Value of input tag. Required for radio buttons

Form.select ViewHelper <f:form.select>

ViewHelper which renders a <select> dropdown list for use within a form.

Go to the source code of this ViewHelper: Form\SelectViewHelper.php (GitHub).

Select field with hardcoded options

Using the options parameter, you can pass a hardcoded array to the form.select ViewHelper.

The key of that array is used as option key, and the value is used as human-readable name.

packages/my_extension/Resources/Private/Templates/User/GenderForm.html
<f:form action="selectGender">
    <f:form.select name="gender" options="{1: 'female', 2: 'male', 3: 'diverse'}" />
    <f:form.submit value="Submit"/>
</f:form>
Copied!

The argument will have the key of the chosen entry as value.

packages/my_extension/Classes/Controller/UserController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class UserController extends ActionController
{
    public function genderFormAction(): ResponseInterface
    {
        return $this->htmlResponse();
    }
    public function selectGenderAction(int $gender): ResponseInterface
    {
        // do something
        return $this->redirect('show');
    }
}
Copied!

Preselected field with options supplied by the controller

Most options will be supplied by the controller. You can pass an associative array with the options to the view:

packages/my_extension/Resources/Private/Templates/User/PaymentForm.html
<f:form action="selectPayment">
    <f:form.select name="payment" options="{paymentOptions}" value="{myPayment}" />
    <f:form.submit value="Submit"/>
</f:form>
Copied!

The argument for the select field will have the key of the chosen entry as value.

packages/my_extension/Classes/Controller/UserController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class UserController extends ActionController
{
    public function paymentFormAction(): ResponseInterface
    {
        $paymentOptions =
            ['payPal' => 'PayPal International Services', 'visa' => 'VISA Card'];
        $this->view->assign('paymentOptions', $paymentOptions);
        $this->view->assign('myPayment', 'visa');
        return $this->htmlResponse();
    }
    public function selectPaymentAction(string $payment): ResponseInterface
    {
        // do something
        return $this->redirect('show');
    }
}
Copied!

To pre-select a value, use the argument value.

Select field for selecting (persisted) models

Consider we have the payment options from the previous example in the database and in an Extbase model:

packages/my_extension/Classes/Domain/Model/PaymentMethod.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class PaymentMethod extends AbstractEntity implements \Stringable
{
    protected string $title;
    protected string $paymentIdentifier;

    // Getters and setters

    // If the model implement the __toString() method
    // The result of that method is displayed in the select form
    public function __toString(): string
    {
        return $this->title;
    }
}
Copied!

In the controller we can get all payment methods from the Repository now and pass it to the view as variable:

packages/my_extension/Classes/Controller/UserController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class UserController extends ActionController
{
    public function __construct(
        protected readonly PaymentMethodRepository $paymentMethodRepository,
    ) {}

    public function paymentFormAction(): ResponseInterface
    {
        $paymentOptions = $this->paymentMethodRepository->findAll();
        $this->view->assign('paymentOptions', $paymentOptions);
        $this->view->assign('myPayment', 'visa');
        return $this->htmlResponse();
    }
    public function selectPaymentAction(PaymentMethod $payment): ResponseInterface
    {
        // do something
        return $this->redirect('show');
    }
}
Copied!

The Fluid template can be left unchanged even though we are dealing with a different data source:

packages/my_extension/Resources/Private/Templates/User/PaymentForm.html
<f:form action="selectPayment">
    <f:form.select name="payment" options="{paymentOptions}" value="{myPayment}" />
    <f:form.submit value="Submit"/>
</f:form>
Copied!

When the form gets submitted, the UID of the chosen model appears in the request data. Extbase will then map that uid back to the model for you.

The ViewHelper will then use the model's UID as data submitted in the form and the result of method __toString() as display text.

optionLabelField: Define another property of the model for the option label

If the model to be displayed has no __toString() method or you want to display the content of a different field, use option optionLabelField

<f:form.select name="payment" value="{myPayment}"
    options="{paymentOptions}" optionLabelField="someLabel"/>
Copied!

The options may contain an array or anything else Traversable including

optionValueField: Define another property of the model as value

If you are dealing with non-persisted models or Data-Transfer-Objects (DTO) there is no valid identifier that could be used to automatically map the user's selection in your controller. In this case, you must provide the name of the field to be used to identify the object:

<f:form.select name="payment" value="{myPayment}"
    options="{paymentOptions}" optionValueField="paymentIdentifier"/>
Copied!

The controller action will then be called with the content of that field:

// Variable $payment contains the paymentIdentifier from the model
public function selectPaymentAction(String $payment): ResponseInterface
Copied!

Binding the select field to an object property

When the surrounding <f:form> uses Property mapping we can also map the selected option to the model:

packages/my_extension/Resources/Private/Templates/User/PaymentForm.html
<f:form action="selectPreferredPayment" object="{user}" objectName="user">
    <f:form.select options="{user.availablePaymentOptions}"
                   property="preferredPayment"
    />
    <f:form.submit value="Submit"/>
</f:form>
Copied!

The user model could have the following fields

packages/my_extension/Classes/Domain/Model/User.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use MyVendor\MyExtension\Domain\Model\PaymentMethod;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;

class User extends AbstractEntity
{
    //Other fields
    protected ?PaymentMethod $preferredPayment;
    /** @var ObjectStorage<PaymentMethod>  */
    protected ObjectStorage $availablePaymentOptions;

    // initialize method, getters and setters
}
Copied!

The controller action will then be called with the user object:

public function selectPreferredPaymentAction(User $user): ResponseInterface
Copied!

Working with options and option groups

Form.select.option ViewHelper <f:form.select.option>

ViewHelper for adding custom <option> tags inside a <f:form.select>.

Go to the source code of this ViewHelper: Form\Select\OptionViewHelper.php (GitHub).

The <f:form.select.option> ViewHelper can be used to create a completely <f:form.select.option> <option> tags in a way compatible with the HMAC generation. To do so, leave out the options argument and use child ViewHelpers:

<f:form.select name="myproperty">
  <f:form.select.option value="1">Option one</f:form.select.option>
  <f:form.select.option value="2" selected="1">Option two</f:form.select.option>
</f:form.select>
Copied!

Form.select.optgroup ViewHelper <f:form.select.optgroup>

ViewHelper for adding custom <optgroup> tags inside a <f:form.select>, supports further child <f:form.select.option> tags.

Go to the source code of this ViewHelper: Form\Select\OptgroupViewHelper.php (GitHub).

The <f:form.select.option> can be grouped with the <f:form.select.optgroup> to produce <optgroup> in the HTML output.

<f:form.select name="myproperty">
   <f:form.select.option value="1">Option one</f:form.select.option>
   <f:form.select.option value="2">Option two</f:form.select.option>
   <f:form.select.optgroup>
      <f:form.select.option value="3">Grouped option one</f:form.select.option>
      <f:form.select.option value="4">Grouped option twi</f:form.select.option>
   </f:form.select.optgroup>
</f:form.select>
Copied!

Using an "Please select an option" placeholder

In HTML, the <select> element always selects the first option, if nothing else is selected. If the field is mandatory and the user should be forced to make a selection or if an empty value should be possible, you need an empty option as first option. You can use the argument prependOptionLabel to set a label for this object. The value of the option will be an empty string. If you need another value, for example 0 because you are expecting an integer, you can use prependOptionValue.

<f:form.select options="{user.availablePaymentOptions}"
               property="preferredPayment"
               prependOptionLabel="Ask me every time!"
               prependOptionValue="ask"
/>
Copied!

You can achieve the same effect by combining the options argument with one (or several) <form.select.option> <f:form.select.option>:

<f:form.select options="{user.availablePaymentOptions}"
               property="preferredPayment"
               optionsAfterContent="true"
               required="1"
>
   <f:form.select.option value="">Please Chose *</f:form.select.option>
   <f:form.select.option value="ask">Ask me every time!</f:form.select.option>
</f:form.select>
Copied!

It is possible to put the additional options last and combine the two:

<f:form.select options="{user.availablePaymentOptions}"
               property="preferredPayment"
               prependOptionLabel="Please Chose *"
               required="1"
>
   <f:form.select.option value="ask">Ask me every time!</f:form.select.option>
</f:form.select>
Copied!

Arguments of the Form.select ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

multiple

multiple
Type
boolean
Default
false
If set multiple options may be selected.

name

name
Type
string
Name of input tag

optionLabelField

optionLabelField
Type
string
If specified, will call the appropriate getter on each object to determine the label.

optionValueField

optionValueField
Type
string
If specified, will call the appropriate getter on each object to determine the value.

options

options
Type
array
Associative array with internal IDs as key, and the values are displayed in the select box. Can be combined with or replaced by child f:form.select.* nodes.

optionsAfterContent

optionsAfterContent
Type
boolean
Default
false
If true, places auto-generated option tags after those rendered in the tag content. If false, automatic options come first.

prependOptionLabel

prependOptionLabel
Type
string
If specified, will provide an option at first position with the specified label.

prependOptionValue

prependOptionValue
Type
string
If specified, will provide an option at first position with the specified value.

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

required

required
Type
boolean
Default
false
If set no empty value is allowed.

selectAllByDefault

selectAllByDefault
Type
boolean
Default
false
If specified options are selected if none was set before.

sortByOptionLabel

sortByOptionLabel
Type
boolean
Default
false
If true, List will be sorted by label.

value

value
Type
mixed
Value of input tag

Arguments of the Form.select.option ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

selected

selected
Type
boolean
If set, overrides automatic detection of selected state for this option.

value

value
Type
mixed
Value to be inserted in HTML tag - must be convertible to string!

Arguments of the Form.select.optgroup ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

disabled

disabled
Type
boolean
Default
false
If true, option group is rendered as disabled

Form.submit ViewHelper <f:form.submit>

ViewHelper which renders a form submit button.

Go to the source code of this ViewHelper: Form\SubmitViewHelper.php (GitHub).

Arguments

The following arguments are available for the form.submit ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
mixed
Value of input tag

Examples

Defaults

<f:form.submit value="Send Mail" />
Copied!

Output:

<input type="submit" />
Copied!

Dummy content for template preview

<f:form.submit name="mySubmit" value="Send Mail"><button>dummy button</button></f:form.submit>
Copied!

Output:

<input type="submit" name="mySubmit" value="Send Mail" />
Copied!

Form.textarea ViewHelper <f:form.textarea>

ViewHelper which renders a <textarea> large text input area inside a form.

The value of the text area needs to be set via the value attribute, as with all other f:form ViewHelpers.

Go to the source code of this ViewHelper: Form\TextareaViewHelper.php (GitHub).

A basic text area bound to an action argument

This example shows how to bind a textarea to an Extbase controller action argument.

This approach is appropriate when you want to handle input directly in a controller action, without relying on a domain model or Data Transfer Object (DTO).

packages/my_extension/Resources/Private/Templates/Contact/ShowForm.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">

<f:form action="sendMessage" controller="Contact" method="post">

    <label for="tx-contact-name">Your Name:</label>
    <f:form.textfield name="name" id="tx-contact-name" required="true" />
    <label for="tx-contact-message">Message:</label>
    <f:form.textarea name="message" id="tx-contact-message" required="true" />

    <f:form.submit class="button" value="Send" />
</f:form>

</html>
Copied!

The controller action can then look like this:

packages/my_extension/Classes/Controller/ContactController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class ContactController extends ActionController
{
    public function sendMessageAction(string $name, string $message): ResponseInterface
    {
        // Process data
        $this->addFlashMessage('Your message was received.');
        return $this->redirect('showForm');
    }
    // ...
}
Copied!

Property binding: A text area bound to a model property

Using the property argument, a text field can be bound to the property of an Extbase model.

For this, the surrounding form must also define the object property. As the textarea ViewHelper may provide texts longer than 255 chars, the TCA for the field should be of type Text areas & RTE. This ensures that the auto-generated database field will also be of type TEXT, which is suitable for longer content.”

packages/my_extension/Resources/Private/Templates/Blog/Comment.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">

<f:form action="create"
        controller="Comment"
        objectName="comment"
        object="{newComment}"
        method="post">

        <label for="tx-blogexample-email">E-Mail:</label>
        <f:form.textfield property="email"
                          type="email"
                          id="tx-blogexample-email" />

        <label for="tx-blogexample-content">Message:</label>
        <f:form.textarea property="content"
                         id="tx-blogexample-content"
                         rows="8"
                         cols="46" />

        <f:form.submit class="button"
                       value="Submit" />

</f:form>
</html>
Copied!

The controller action can then look like this:

packages/my_extension/Classes/Controller/CommentController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use T3docs\BlogExample\Domain\Model\Comment;
use T3docs\BlogExample\Domain\Repository\CommentRepository;
use TYPO3\CMS\Extbase\Annotation\IgnoreValidation;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class CommentController extends ActionController
{
    public function __construct(
        protected readonly CommentRepository $commentRepository,
    ) {}

    #[IgnoreValidation(['argumentName' => 'newComment'])]
    public function commentFormAction(?Comment $newComment = null): ResponseInterface
    {
        if ($newComment === null) {
            $newComment = new Comment();
            $newComment->setDate(new \DateTime());
        }
        // The assigned object will be used in argument object
        $this->view->assign('newComment', $newComment);
        return $this->htmlResponse();
    }

    public function createAction(
        // This parameter must have the same name as argument `objectName` of f:form
        Comment $comment,
    ): ResponseInterface {
        $this->commentRepository->add($comment);
        $this->addFlashMessage('Comment was saved');
        return $this->redirect('show');
    }
}
Copied!
packages/my_extension/Classes/Domain/Model/Comment.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\Annotation\Validate;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class Comment extends AbstractEntity
{
    #[Validate(['validator' => 'EmailAddress'])]
    protected string $email = '';

    #[Validate(['validator' => 'StringLength', 'options' => ['maximum' => 500]])]
    protected string $content = '';

    // Getters and setters ...
}
Copied!
packages/my_extension/Configuration/TCA/tx_myextension_domain_model_comment.php
<?php

return [
    'ctrl' => [
        'title' => 'Comment',
        'label' => 'email',
        // ...
    ],
    'types' => [
        '1' => ['showitem' => 'email, content'],
    ],
    'columns' => [
        'email' => [
            'label' => 'Email',
            'config' => [
                'type' => 'email',
            ],
        ],
        'content' => [
            'label' => 'Message',
            'config' => [
                'type' => 'text',
            ],
        ],
    ],
];
Copied!

Arguments of the textarea form field ViewHelper

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

required

required
Type
bool
Default
false
Specifies whether the textarea is required

value

value
Type
mixed
Value of input tag

Form.textfield ViewHelper <f:form.textfield>

ViewHelper which renders a text field <input type="text">.

Go to the source code of this ViewHelper: Form\TextfieldViewHelper.php (GitHub).

A basic text input bound to an action argument

For example a very simplified search form could look like this:

packages/my_extension/Resources/Private/Templates/Search/SearchForm.html
<f:form action="search" method="post" pageUid="{settings.targetPid}">
    <div>
        <label for="sword">Search:</label>
        <f:form.textfield name="search[sword]" value="{sword}" id="sword" />
    </div>
    <div>
        <f:form.submit name="search[submitButton]" value="Submit" />
    </div>
</f:form>
Copied!

The Extbase controller action could for example look like this:

packages/my_extension/Classes/Controller/SearchController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class SearchController extends ActionController
{
    public function searchAction(array $search = []): ResponseInterface
    {
        // TODO: implement search
        return $this->htmlResponse();
    }
}
Copied!

A text input bound to a model property

Using the property argument, a text field can be bound to the property of an Extbase model.

For this, the surrounding form must also define the object property.

packages/my_extension/Resources/Private/Templates/Blog/Comment.html
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers"
      data-namespace-typo3-fluid="true">

<f:form action="create"
        controller="Comment"
        objectName="comment"
        object="{newComment}"
        method="post">

        <label for="tx-blogexample-email">E-Mail:</label>
        <f:form.textfield property="email"
                          type="email"
                          id="tx-blogexample-email" />

        <label for="tx-blogexample-content">Message:</label>
        <f:form.textarea property="content"
                         id="tx-blogexample-content"
                         rows="8"
                         cols="46" />

        <f:form.submit class="button"
                       value="Submit" />

</f:form>
</html>
Copied!

Validation of plain text input fields

User input often requires validation. For text fields, some common cases include:

  • The name should not be empty
  • The email address must be a valid email address and it is required.
  • The link to the user's homepage must be a valid URL if it is entered at all.

Using arbitrary arguments

As the Form.textfield ViewHelper allows arbitrary arguments, you can use any additional argument that you would also use on an HTML input element, including HTML 5 arguments like required and autocomplete.

ARIA arguments for improved accessibility

You have the choice of defining each aria-* attribute separately as you would do in HTML, or by passing them as an array to the Fluid argument aria.

Data arguments for JavaScript validation etc

Same goes with data-* attributes. They can also be set with the Fluid argument data as an array. data-* attributes are commonly used with JavaScript libraries for frontend validation like Parsley.

Server side validation

Always use Validation for Extbase models and controllers or validate the input on server-side manually.

Example with validation and aria-attributes

packages/my_extension/Resources/Private/Templates/Comment/CommentForm.html
<f:form action="create" controller="Comment"
        objectName="comment" object="{newComment}" method="post">

    <label for="name">Name:</label>
    <f:form.textfield property="name" id="name"
                      autocomplete="name" required="required"
                      aria-required="true" />

    <label for="email">E-Mail (*):</label>
    <f:form.textfield property="email" id="email" type="email"
                      autocomplete="email" required="required"
                      aria="{required: 'true', describedby: 'email-hint'}" />

    <label for="homepage">Website:</label>
    <f:form.textfield property="homepage" id="homepage" type="url"
                      autocomplete="url" />

    <f:form.submit value="Send" />
</f:form>

<span id="email-hint">
  (*) We will never share your email.
</span>
Copied!

The Extbase controller action commentFormAction() uses the IgnoreValidation argument to disable the validation. Whenever the validation fails in the createAction() the request will be forwarded back to this action. The model still contains the non-valid data so that the user can edit it.

packages/my_extension/Classes/Controller/CommentController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use T3docs\BlogExample\Domain\Model\Comment;
use T3docs\BlogExample\Domain\Repository\CommentRepository;
use TYPO3\CMS\Extbase\Annotation\IgnoreValidation;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class CommentController extends ActionController
{
    public function __construct(
        protected readonly CommentRepository $commentRepository,
    ) {}

    #[IgnoreValidation(['argumentName' => 'newComment'])]
    public function commentFormAction(?Comment $newComment = null): ResponseInterface
    {
        if ($newComment === null) {
            $newComment = new Comment();
            $newComment->setDate(new \DateTime());
        }
        // The assigned object will be used in argument object
        $this->view->assign('newComment', $newComment);
        return $this->htmlResponse();
    }

    public function createAction(
        // This parameter must have the same name as argument `objectName` of f:form
        Comment $comment,
    ): ResponseInterface {
        $this->commentRepository->add($comment);
        $this->addFlashMessage('Comment was saved');
        return $this->redirect('show');
    }
}
Copied!

The Extbase model uses built-in validators:

packages/my_extension/Classes/Domain/Model/Comment.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Domain\Model;

use TYPO3\CMS\Extbase\Annotation\Validate;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;

class Comment extends AbstractEntity
{
    #[Validate(['validator' => 'NotEmpty'])]
    protected string $name = '';

    #[Validate(['validator' => 'NotEmpty'])]
    #[Validate(['validator' => 'EmailAddress'])]
    protected string $email = '';

    #[Validate(['validator' => 'Url'])]
    protected string $homepage = '';
}
Copied!

Arguments

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

required

required
Type
bool
Default
false
If the field is required or not

type

type
Type
string
Default
'text'
The field type, e.g. "text", "email", "url" etc.

value

value
Type
mixed
Value of input tag

Form.upload ViewHelper <f:form.upload>

ViewHelper which renders an <input type="file"> file upload HTML form element. Make sure to set the enctype="multipart/form-data" attribute on the surrounding form!

Go to the source code of this ViewHelper: Form\UploadViewHelper.php (GitHub).

Examples

Example:

<f:form.upload name="file" />
Copied!

Output:

<input type="file" name="file" />
Copied!

Arguments of f:form.upload

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
mixed
Value of input tag

Form.uploadDeleteCheckbox ViewHelper <f:form.uploadDeleteCheckbox>

ViewHelper which renders a checkbox field used for file upload deletion in Extbase forms.

Go to the source code of this ViewHelper: Form\UploadDeleteCheckboxViewHelper.php (GitHub).

Examples

Example:

<f:form.uploadDeleteCheckbox id="file" property="file" fileReference="{myModel.file}" />
Copied!

Output:

<input type="checkbox" id="file" name="tx_extension_plugin[@delete][item][hash]" value="signed-json-string">

Copied!

Argument of the f:form.uploadDeleteCheckbox

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

fileReference

fileReference
Type
TYPO3\CMS\Extbase\Domain\Model\FileReference
Required
1
The file reference object

id

id
Type
string
ID of the generated checkbox element

property

property
Type
string
Required
1
Name of object property

Form.validationResults ViewHelper <f:form.validationResults>

ViewHelper which renders form validation results.

Go to the source code of this ViewHelper: Form\ValidationResultsViewHelper.php (GitHub).

Examples

Output error messages as a list:

<f:form.validationResults>
   <f:if condition="{validationResults.flattenedErrors}">
      <ul class="errors">
         <f:for each="{validationResults.flattenedErrors}" as="errors" key="propertyPath">
            <li>{propertyPath}
               <ul>
                  <f:for each="{errors}" as="error">
                     <li>{error.code}: {error}</li>
                  </f:for>
               </ul>
            </li>
         </f:for>
      </ul>
   </f:if>
</f:form.validationResults>
Copied!

Output:

<ul class="errors">
   <li>1234567890: Validation errors for argument "newBlog"</li>
</ul>
Copied!

Output error messages for a single property:

<f:form.validationResults for="someProperty">
   <f:if condition="{validationResults.flattenedErrors}">
      <ul class="errors">
         <f:for each="{validationResults.errors}" as="error">
            <li>{error.code}: {error}</li>
         </f:for>
      </ul>
   </f:if>
</f:form.validationResults>
Copied!

Output:

<ul class="errors">
  <li>1234567890: Some error message</li>
</ul>

Copied!

Arguments of f:form.validationResults

as

as
Type
string
Default
'validationResults'
The name of the variable to store the current error

for

for
Type
string
Default
''
The name of the error name (e.g. argument name or property name). This can also be a property path (like blog.title), and will then only display the validation errors of that property.

Format.bytes ViewHelper <f:format.bytes>

ViewHelper which formats an integer (byte count) into specific human-readable output.

Go to the source code of this ViewHelper: Format\BytesViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.bytes ViewHelper:

decimalSeparator

decimalSeparator
Type
string
Default
'.'
The decimal point character

decimals

decimals
Type
int
Default
0
The number of digits after the decimal point

thousandsSeparator

thousandsSeparator
Type
string
Default
','
The character for grouping the thousand digits

units

units
Type
string
comma separated list of available units, default is LocalizationUtility::translate('viewhelper.format.bytes.units', 'fluid')

value

value
Type
int
The incoming data to convert, or NULL if VH children should be used

Examples

Simple

{fileSize -> f:format.bytes()}
Copied!

123 KB Depending on the value of {fileSize}.

With arguments

{fileSize -> f:format.bytes(decimals: 2, decimalSeparator: '.', thousandsSeparator: ',')}
Copied!

1,023.00 B Depending on the value of {fileSize}.

You may provide an own set of units, like this: B,KB,MB,GB,TB,PB,EB,ZB,YB.

Custom units

{fileSize -> f:format.bytes(units: '{f:translate(\'viewhelper.format.bytes.units\', \'fluid\')}'
Copied!

123 KB Depending on the value of {fileSize}.

Format.case ViewHelper <f:format.case>

Modifies the case of an input string to upper- or lowercase or capitalization. The default transformation will be uppercase as in mb_convert_case.

Possible modes are:

lower
Transforms the input string to lowercase Example: "Hello World" -> "hello world"
upper
Transforms the input string to uppercase Example: "Hello World" -> "HELLO WORLD"
capital
Transforms the first character of the input string to uppercase Example: "hello world" -> "Hello world"
uncapital
Transforms the input string to its first letter lower-cased Example: "Hello World" -> "hello World"
capitalWords
Transforms the input string to capitalize each word Example: "hello world" -> "Hello World"

Note that the behavior will be the same as in the appropriate PHP function mb_convert_case; especially regarding locale and multibyte behavior.

Examples

Default

<f:format.case>Some Text with miXed case</f:format.case>
Copied!

Output:

SOME TEXT WITH MIXED CASE
Copied!

Example with given mode

<f:format.case mode="capital">someString</f:format.case>
Copied!

Output:

SomeString
Copied!

Go to the source code of this ViewHelper: Format\CaseViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.case ViewHelper:

mode

mode
Type
string
Default
'upper'
The case to apply, must be one of this' CASE_* constants. Defaults to uppercase application.

value

value
Type
string
The input value. If not given, the evaluated child nodes will be used.

Format.cdata ViewHelper <f:format.cdata>

Outputs an argument/value without any escaping and wraps it with CDATA tags.

PAY SPECIAL ATTENTION TO SECURITY HERE (especially Cross Site Scripting), as the output is NOT SANITIZED!

Examples

Child nodes

<f:format.cdata>{string}</f:format.cdata>
Copied!

Output:

<![CDATA[(Content of {string} without any conversion/escaping)]]>
Copied!

Value attribute

<f:format.cdata value="{string}" />
Copied!

Output:

<![CDATA[(Content of {string} without any conversion/escaping)]]>
Copied!

Inline notation

{string -> f:format.cdata()}
Copied!

Output:

<![CDATA[(Content of {string} without any conversion/escaping)]]>
Copied!

Go to the source code of this ViewHelper: Format\CdataViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.cdata ViewHelper:

value

value
Type
mixed
The value to output

Format.crop ViewHelper <f:format.crop>

ViewHelper which can crop (shorten) a text. Whitespace within the <f:format.crop> element will be counted as characters.

Go to the source code of this ViewHelper: Format\CropViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.crop ViewHelper:

append

append
Type
string
Default
'&hellip;'
What to append, if truncation happened

maxCharacters

maxCharacters
Type
int
Required
1
Place where to truncate the string

respectHtml

respectHtml
Type
bool
Default
true
If TRUE the cropped string will respect HTML tags and entities. Technically that means, that cropHTML() is called rather than crop()

respectWordBoundaries

respectWordBoundaries
Type
bool
Default
true
If TRUE and division is in the middle of a word, the remains of that word is removed.

Examples

Defaults

<f:format.crop maxCharacters="10">
This is some very long text
</f:format.crop>
Copied!

This is...

The third word "some" does not fit in the 10 character limit, because respectWordBoundaries is true by default.

Custom suffix

<f:format.crop maxCharacters="17" append="&nbsp;[more]">
This is some very long text
</f:format.crop>
Copied!

This is some&nbsp;[more]

Don't respect word boundaries

<f:format.crop maxCharacters="10" respectWordBoundaries="false">
This is some very long text
</f:format.crop>
Copied!

This is s...

Don't respect HTML tags

<f:format.crop maxCharacters="28" respectWordBoundaries="false" respectHtml="false">
This is some text with <strong>HTML</strong> tags
</f:format.crop>
Copied!

This is some text with <stro

Inline notation

{someLongText -> f:format.crop(maxCharacters: 10)}
Copied!

someLongText cropped after 10 characters… Depending on the value of {someLongText}.

Format.currency ViewHelper <f:format.currency>

ViewHelper which formats a given float to a currency representation.

Go to the source code of this ViewHelper: Format\CurrencyViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.currency ViewHelper:

currencySign

currencySign
Type
string
Default
''
The currency sign, eg $ or €.

decimalSeparator

decimalSeparator
Type
string
Default
','
The separator for the decimal point.

decimals

decimals
Type
int
Default
2
Set decimals places.

prependCurrency

prependCurrency
Type
bool
Default
false
Select if the currency sign should be prepended

separateCurrency

separateCurrency
Type
bool
Default
true
Separate the currency sign from the number by a single space, defaults to true due to backwards compatibility

thousandsSeparator

thousandsSeparator
Type
string
Default
'.'
The thousands separator.

useDash

useDash
Type
bool
Default
false
Use the dash instead of decimal 00

Examples

Defaults

<f:format.currency>123.456</f:format.currency>
Copied!

Output:

123,46
Copied!

All parameters

<f:format.currency decimalSeparator="." thousandsSeparator="," decimals="2"
    currencySign="$" prependCurrency="true" separateCurrency="false"
>
    54321
</f:format.currency>
Copied!

Output:

$54,321.00
Copied!

Inline notation

{someNumber -> f:format.currency(thousandsSeparator: ',', currencySign: 'EUR')}
Copied!

Output:

54,321,00 EUR
Copied!

Depending on the value of {someNumber}.

Use dash for decimals without value

<f:format.currency useDash="true">123.00</f:format.currency>
Copied!

Output:

123,-
Copied!

Format.date ViewHelper <f:format.date>

ViewHelper to format an object implementing \DateTimeInterface into human-readable output.

Go to the source code of this ViewHelper: Format\DateViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.date ViewHelper:

base

base
Type
mixed
A base time (an object implementing DateTimeInterface or a string) used if $date is a relative date specification. Defaults to current time.

date

date
Type
mixed
Either an object implementing DateTimeInterface or a string that is accepted by DateTime constructor

format

format
Type
string
Default
''
Format String which is taken to format the Date/Time

locale

locale
Type
string
A locale format such as "nl-NL" to format the date in a specific locale, if none given, uses the current locale of the current request. Only works when pattern argument is given

pattern

pattern
Type
string
Format date based on unicode ICO format pattern given see https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax. If both "pattern" and "format" arguments are given, pattern will be used.

Examples

Defaults

<f:format.date>{dateObject}</f:format.date>
Copied!

1980-12-13 Depending on the current date.

Custom date format

<f:format.date format="H:i">{dateObject}</f:format.date>
Copied!

01:23 Depending on the current time.

Relative date with given time

<f:format.date format="Y" base="{dateObject}">-1 year</f:format.date>
Copied!

2016 Assuming dateObject is in 2017.

strtotime string

<f:format.date format="d.m.Y - H:i:s">+1 week 2 days 4 hours 2 seconds</f:format.date>
Copied!

13.12.1980 - 21:03:42 Depending on the current time, see https://www.php.net/manual/function.strtotime.php.

Localized dates using strftime date format

<f:format.date format="%d. %B %Y">{dateObject}</f:format.date>
Copied!

13. Dezember 1980 Depending on the current date and defined locale. In the example you see the 1980-12-13 in a german locale.

Localized dates using ICU-based date and time formatting

<f:format.date pattern="dd. MMMM yyyy" locale="de-DE">{dateObject}</f:format.date>
Copied!

13. Dezember 1980 Depending on the current date. In the example you see the 1980-12-13 in a german locale.

Localized dates using default formatting patterns

<f:format.date pattern="FULL" locale="fr-FR">{dateObject}</f:format.date>
Copied!

jeudi 9 mars 2023 à 21:40:49 temps universel coordonné Depending on the current date and operating system setting. In the example you see the 2023-03-09 in a french locale.

Inline notation

{f:format.date(date: dateObject)}
Copied!

1980-12-13 Depending on the value of {dateObject}.

Inline notation (2nd variant)

{dateObject -> f:format.date()}
Copied!

1980-12-13 Depending on the value of {dateObject}.

Format.html ViewHelper <f:format.html>

ViewHelper to render a string which can contain HTML markup by passing it to a TYPO3 parseFunc. This can sanitize unwanted HTML tags and attributes, and keep wanted HTML syntax and take care of link substitution and other parsing. Either specify a path to the TypoScript setting or set the parseFunc options directly. By default, lib.parseFunc_RTE is used to parse the string.

  <f:format.html parseFuncTSPath="lib.myCustomParseFunc">
      {$project} is a cool <b>CMS</b> (<a href="https://www.typo3.org">TYPO3</a>).
  </f:format.html>
Copied!

Note: The ViewHelper must not be used in backend context, as it triggers frontend logic. Instead, use <f:sanitize.html> within backend context to secure a given HTML string or <f:transform.html> to parse links in HTML.

Go to the source code of this ViewHelper: Format\HtmlViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.html ViewHelper:

current

current
Type
string
Initialize the content object with this value for current property.

currentValueKey

currentValueKey
Type
string
Define the value key, used to locate the current value for the content object

data

data
Type
mixed
Initialize the content object with this set of data. Either an array or object.

parseFuncTSPath

parseFuncTSPath
Type
string
Default
'lib.parseFunc_RTE'
Path to the TypoScript parseFunc setup.

table

table
Type
string
Default
''
The table name associated with the "data" argument.

Examples

Default parameters

<f:format.html>{$myConstant.project} is a cool <b>CMS</b> (<a href="https://www.typo3.org">TYPO3</a>).</f:format.html>
Copied!

Output:

<p class="bodytext">TYPO3 is a cool <strong>CMS</strong> (<a href="https://www.typo3.org" target="_blank">TYPO3</a>).</p>
Copied!

Depending on TYPO3 constants.

Custom parseFunc

<f:format.html parseFuncTSPath="lib.parseFunc">TYPO3 is a cool <b>CMS</b> (<a href="https://www.typo3.org">TYPO3</a>).</f:format.html>
Copied!

Output:

TYPO3 is a cool <strong>CMS</strong> (<a href="https://www.typo3.org" target="_blank">TYPO3</a>).
Copied!

Data argument

If you work with TypoScript field property, you should add the current record as data to the ViewHelper to allow processing the field and dataWrap properties correctly.

<f:format.html data="{newsRecord}" parseFuncTSPath="lib.news">News title: </f:format.html>
Copied!

After "dataWrap = |<strong>{FIELD:title}</strong>" you may have this Output:

News title: <strong>TYPO3, greatest CMS ever</strong>
Copied!

Current argument

Use the current argument to set the current value of the content object.

<f:format.html current="{strContent}" parseFuncTSPath="lib.info">I'm gone</f:format.html>
Copied!

After setContentToCurrent = 1 you may have this output:

Thanks Kasper for this great CMS
Copied!

CurrentValueKey argument

Use the currentValueKey argument to define a value of data object as the current value.

<f:format.html data="{contentRecord}" currentValueKey="header" parseFuncTSPath="lib.content">Content: </f:format.html>
Copied!

After dataWrap = |{CURRENT:1} you may have this Output:

Content: How to install TYPO3 in under 2 minutes ;-)
Copied!

Inline notation

{someText -> f:format.html(parseFuncTSPath: 'lib.parseFunc')}
Copied!

Output:

TYPO3 is a cool <strong>CMS</strong> (<a href="https://www.typo3.org" target="_blank">TYPO3</a>).
Copied!

Format.htmlentities ViewHelper <f:format.htmlentities>

ViewHelper to apply htmlentities() escaping to a value, transforming all HTML special characters to entity representations (like " to &quot;).

Go to the source code of this ViewHelper: Format\HtmlentitiesViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.htmlentities ViewHelper:

doubleEncode

doubleEncode
Type
bool
Default
true
If FALSE existing html entities won't be encoded, the default is to convert everything.

encoding

encoding
Type
string
Define the encoding used when converting characters (Default: UTF-8

keepQuotes

keepQuotes
Type
bool
Default
false
If TRUE, single and double quotes won't be replaced (sets ENT_NOQUOTES flag).

value

value
Type
string
string to format

Examples

Default notation

<f:format.htmlentities>{text}</f:format.htmlentities>
Copied!

Text containing the following signs & " ' < > will be processed by htmlentities(). These will result in: &amp; &quot; &#039; &lt; &gt;.

Inline notation

{text -> f:format.htmlentities(encoding: 'ISO-8859-1')}
Copied!

Text containing the following signs & " ' < > will be processed by htmlentities(). These will result in: &amp; &quot; &#039; &lt; &gt;.

But encoded as ISO-8859-1.

Format.htmlentitiesDecode ViewHelper <f:format.htmlentitiesDecode>

ViewHelper to apply html_entity_decode() to a value, transforming HTML entity representations back into HTML special characters (like &quot; to ").

Go to the source code of this ViewHelper: Format\HtmlentitiesDecodeViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.htmlentitiesDecode ViewHelper:

encoding

encoding
Type
string
Define the encoding used when converting characters (Default: UTF-8).

keepQuotes

keepQuotes
Type
bool
Default
false
If TRUE, single and double quotes won't be replaced (sets ENT_NOQUOTES flag).

value

value
Type
string
string to format

Examples

Default notation

<f:format.htmlentitiesDecode>{text}</f:format.htmlentitiesDecode>
Copied!

Text containing the following escaped signs: &amp; &quot; &#039; &lt; &gt;, will be processed by html_entity_decode(). These will result in: & " ' < >.

Inline notation

{text -> f:format.htmlentitiesDecode(encoding: 'ISO-8859-1')}
Copied!

Text containing the following escaped signs: &amp; &quot; &#039; &lt; &gt;, will be processed by html_entity_decode(). These will result in: & " ' < >.

But encoded as ISO-8859-1.

Format.htmlspecialchars ViewHelper <f:format.htmlspecialchars>

Applies PHP htmlspecialchars() escaping to a value.

See http://www.php.net/manual/function.htmlspecialchars.php

Examples

Default notation

<f:format.htmlspecialchars>{text}</f:format.htmlspecialchars>
Copied!

Output:

Text with & " ' < > * replaced by HTML entities (htmlspecialchars applied).
Copied!

Inline notation

{text -> f:format.htmlspecialchars(encoding: 'ISO-8859-1')}
Copied!

Output:

Text with & " ' < > * replaced by HTML entities (htmlspecialchars applied).
Copied!

Go to the source code of this ViewHelper: Format\HtmlspecialcharsViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.htmlspecialchars ViewHelper:

doubleEncode

doubleEncode
Type
boolean
Default
true
If false, html entities will not be encoded

encoding

encoding
Type
string
Default
'UTF-8'
Encoding

keepQuotes

keepQuotes
Type
boolean
Default
false
If true quotes will not be replaced (ENT_NOQUOTES)

value

value
Type
string
Value to format

Format.json ViewHelper <f:format.json>

Wrapper for PHPs json_encode function. See https://www.php.net/manual/function.json-encode.php.

Examples

Encoding a view variable

{someArray -> f:format.json()}
Copied!

["array","values"] Depending on the value of {someArray}.

Associative array

{f:format.json(value: {foo: 'bar', bar: 'baz'})}
Copied!

{"foo":"bar","bar":"baz"}

Non associative array with forced object

{f:format.json(value: {0: 'bar', 1: 'baz'}, forceObject: true)}
Copied!

{"0":"bar","1":"baz"}

Go to the source code of this ViewHelper: Format\JsonViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.json ViewHelper:

forceObject

forceObject
Type
bool
Default
false
Outputs an JSON object rather than an array

value

value
Type
mixed
The incoming data to convert, or null if VH children should be used

Format.nl2br ViewHelper <f:format.nl2br>

Wrapper for PHPs nl2br function. See https://www.php.net/manual/function.nl2br.php.

Examples

Default

<f:format.nl2br>{text_with_linebreaks}</f:format.nl2br>
Copied!

Text with line breaks replaced by <br />

Inline notation

{text_with_linebreaks -> f:format.nl2br()}
Copied!

Text with line breaks replaced by <br />

Go to the source code of this ViewHelper: Format\Nl2brViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.nl2br ViewHelper:

value

value
Type
string
string to format

Format.number ViewHelper <f:format.number>

Formats a number with custom precision, decimal point and grouped thousands. See https://www.php.net/manual/function.number-format.php.

Examples

Defaults

<f:format.number>423423.234</f:format.number>
Copied!

423,423.20

With all parameters

<f:format.number decimals="1" decimalSeparator="," thousandsSeparator=".">
    423423.234
</f:format.number>
Copied!

423.423,2

Go to the source code of this ViewHelper: Format\NumberViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.number ViewHelper:

decimalSeparator

decimalSeparator
Type
string
Default
'.'
The decimal point character

decimals

decimals
Type
int
Default
2
The number of digits after the decimal point

thousandsSeparator

thousandsSeparator
Type
string
Default
','
The character for grouping the thousand digits

Format.padding ViewHelper <f:format.padding>

ViewHelper to format a string to specific lengths, by using PHPs str_pad function.

Go to the source code of this ViewHelper: Format\PaddingViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.padding ViewHelper:

padLength

padLength
Type
int
Required
1
Length of the resulting string. If the value of pad_length is negative or less than the length of the input string, no padding takes place.

padString

padString
Type
string
Default
' '
The padding string

padType

padType
Type
string
Default
'right'
Append the padding at this site (Possible values: right,left,both. Default: right)

value

value
Type
string
string to format

Examples

Defaults

<f:format.padding padLength="10">TYPO3</f:format.padding>
Copied!

Output:

TYPO3␠␠␠␠␠
Copied!

TYPO3␠␠␠␠␠

Specify padding string

<f:format.padding padLength="10" padString="-=">TYPO3</f:format.padding>
Copied!

TYPO3-=-=-

Specify padding type

<f:format.padding padLength="10" padString="-" padType="both">TYPO3</f:format.padding>
Copied!

--TYPO3---

Format.printf ViewHelper <f:format.printf>

A ViewHelper for formatting values with printf. Either supply an array for the arguments or a single value.

See http://www.php.net/manual/en/function.sprintf.php

Examples

Scientific notation

<f:format.printf arguments="{number: 362525200}">%.3e</f:format.printf>
Copied!

Output:

3.625e+8
Copied!

Argument swapping

<f:format.printf arguments="{0: 3, 1: 'Kasper'}">%2$s is great, TYPO%1$d too. Yes, TYPO%1$d is great and so is %2$s!</f:format.printf>
Copied!

Output:

Kasper is great, TYPO3 too. Yes, TYPO3 is great and so is Kasper!
Copied!

Single argument

<f:format.printf arguments="{1: 'TYPO3'}">We love %s</f:format.printf>

Copied!

Output:

We love TYPO3
Copied!

Inline notation

{someText -> f:format.printf(arguments: {1: 'TYPO3'})}

Copied!

Output:

We love TYPO3
Copied!

Go to the source code of this ViewHelper: Format\PrintfViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.printf ViewHelper:

arguments

arguments
Type
array
Default
array ( )
The arguments for vsprintf

value

value
Type
string
String to format

Format.raw ViewHelper <f:format.raw>

Outputs an argument/value without any escaping. Is normally used to output an ObjectAccessor which should not be escaped, but output as-is.

PAY SPECIAL ATTENTION TO SECURITY HERE (especially Cross Site Scripting), as the output is NOT SANITIZED!

Examples

Child nodes

<f:format.raw>{string}</f:format.raw>
Copied!

Output:

(Content of ``{string}`` without any conversion/escaping)
Copied!

Value attribute

<f:format.raw value="{string}" />
Copied!

Output:

(Content of ``{string}`` without any conversion/escaping)
Copied!

Inline notation

{string -> f:format.raw()}
Copied!

Output:

(Content of ``{string}`` without any conversion/escaping)
Copied!

Go to the source code of this ViewHelper: Format\RawViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.raw ViewHelper:

value

value
Type
mixed
The value to output

Format.stripTags ViewHelper <f:format.stripTags>

Removes tags from the given string (applying PHPs strip_tags() function) See https://www.php.net/manual/function.strip-tags.php.

Examples

Default notation

<f:format.stripTags>Some Text with <b>Tags</b> and an &Uuml;mlaut.</f:format.stripTags>
Copied!

Some Text with Tags and an &Uuml;mlaut. strip_tags() applied.

Default notation with allowedTags

<f:format.stripTags allowedTags="<p><span><div><script>">
    <p>paragraph</p><span>span</span><div>divider</div><iframe>iframe</iframe><script>script</script>
</f:format.stripTags>
Copied!

Output:

<p>paragraph</p><span>span</span><div>divider</div>iframe<script>script</script>
Copied!

Inline notation

{text -> f:format.stripTags()}
Copied!

Text without tags strip_tags() applied.

Inline notation with allowedTags

{text -> f:format.stripTags(allowedTags: "<p><span><div><script>")}
Copied!

Text with p, span, div and script Tags inside, all other tags are removed.

Go to the source code of this ViewHelper: Format\StripTagsViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.stripTags ViewHelper:

allowedTags

allowedTags
Type
string
Optional string of allowed tags as required by PHPs strip_tags() function

value

value
Type
string
string to format

Format.trim ViewHelper <f:format.trim>

This ViewHelper strips whitespace (or other characters) from the beginning and end of a string.

Possible sides are:

both (default)
Strip whitespace (or other characters) from the beginning and end of a string
left or start
Strip whitespace (or other characters) from the beginning of a string
right or end
Strip whitespace (or other characters) from the end of a string

Examples

Defaults

#<f:format.trim>   String to be trimmed.   </f:format.trim>#
Copied!
#String to be trimmed.#
Copied!

Trim only one side

#<f:format.trim side="right">   String to be trimmed.   </f:format.trim>#
Copied!
#   String to be trimmed.#
Copied!

Trim special characters

#<f:format.trim characters=" St.">   String to be trimmed.   </f:format.trim>#
Copied!
#ring to be trimmed#
Copied!

Go to the source code of this ViewHelper: Format\TrimViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.trim ViewHelper:

characters

characters
Type
string
Optionally, the stripped characters can also be specified using the characters parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

side

side
Type
string
Default
'both'
The side to apply, must be one of this' CASE_* constants. Defaults to both application.

value

value
Type
string
The string value to be trimmed. If not given, the evaluated child nodes will be used.

Format.urlencode ViewHelper <f:format.urlencode>

Encodes the given string according to http://www.faqs.org/rfcs/rfc3986.html Applying PHPs rawurlencode() function. See https://www.php.net/manual/function.rawurlencode.php.

Examples

Default notation

<f:format.urlencode>foo @+%/</f:format.urlencode>
Copied!

foo%20%40%2B%25%2F rawurlencode() applied.

Inline notation

{text -> f:format.urlencode()}
Copied!

Url encoded text rawurlencode() applied.

Go to the source code of this ViewHelper: Format\UrlencodeViewHelper.php (GitHub).

Arguments

The following arguments are available for the format.urlencode ViewHelper:

value

value
Type
string
string to format

Sanitize.html ViewHelper <f:sanitize.html>

ViewHelper to pass a given content through typo3/html-sanitizer to mitigate potential cross-site scripting occurrences. The build option by default uses the class TYPO3\CMS\Core\Html\DefaultSanitizerBuilder, which declares allowed HTML tags, attributes and their values.

Go to the source code of this ViewHelper: Sanitize\HtmlViewHelper.php (GitHub).

Arguments

The following arguments are available for the sanitize.html ViewHelper:

build

build
Type
string
Default
'default'
preset name or class-like name of sanitization builder

Examples

Default parameters

<f:sanitize.html>
  <img src="/img.png" class="image" onmouseover="alert(document.location)">
</f:sanitize.html>
Copied!

Output:

<img src="/img.png" class="image">
Copied!

Inline notation

{richTextFieldContent -> f:sanitize.html(build: 'default')}
Copied!

Security.ifAuthenticated ViewHelper <f:security.ifAuthenticated>

ViewHelper implementing an ifAuthenticated/else condition for frontend users.

Go to the source code of this ViewHelper: Security\IfAuthenticatedViewHelper.php (GitHub).

Arguments

The following arguments are available for the security.ifAuthenticated ViewHelper:

else

else
Type
mixed
Value to be returned if the condition if not met.

then

then
Type
mixed
Value to be returned if the condition if met.

Examples

Basic usage

<f:security.ifAuthenticated>
   This is being shown whenever a FE user is logged in
</f:security.ifAuthenticated>
Copied!

Everything inside the <f:security.ifAuthenticated> tag is being displayed if current frontend user is authenticated.

IfAuthenticated / then / else

<f:security.ifAuthenticated>
   <f:then>
      This is being shown in case you have access.
   </f:then>
   <f:else>
      This is being displayed in case you do not have access.
   </f:else>
</f:security.ifAuthenticated>
Copied!

Everything inside the <f:then></f:then> tag is displayed if frontend user is authenticated. Otherwise, everything inside the <f:else></f:else> tag is displayed.

Security.ifHasRole ViewHelper <f:security.ifHasRole>

ViewHelper implementing an ifHasRole/else condition for frontend groups.

Go to the source code of this ViewHelper: Security\IfHasRoleViewHelper.php (GitHub).

Arguments

The following arguments are available for the security.ifHasRole ViewHelper:

else

else
Type
mixed
Value to be returned if the condition if not met.

role

role
Type
string
The usergroup (either the usergroup uid or its title).

then

then
Type
mixed
Value to be returned if the condition if met.

Examples

Basic usage

<f:security.ifHasRole role="Administrator">
    This is being shown in case the current FE user belongs to a FE usergroup (aka role) titled "Administrator" (case sensitive)
</f:security.ifHasRole>
Copied!

Everything inside the <f:security.ifHasRole> tag is being displayed if the logged in frontend user belongs to the specified frontend user group. Comparison is done by comparing to title of the user groups.

Using the usergroup uid as role identifier

<f:security.ifHasRole role="1">
   This is being shown in case the current FE user belongs to a FE usergroup (aka role) with the uid "1"
</f:security.ifHasRole>
Copied!

Everything inside the <f:security.ifHasRole> tag is being displayed if the logged in frontend user belongs to the specified role. Comparison is done using the uid of frontend user groups.

IfRole / then / else

<f:security.ifHasRole role="Administrator">
   <f:then>
      This is being shown in case you have the role.
   </f:then>
   <f:else>
      This is being displayed in case you do not have the role.
   </f:else>
</f:security.ifHasRole>
Copied!

Everything inside the <f:then></f:then> tag is displayed if the logged in FE user belongs to the specified role. Otherwise, everything inside the <f:else></f:else> tag is displayed.

Security.nonce ViewHelper <f:security.nonce>

ViewHelper to retrieve (and consume) a nonce attribute from the global server request object pool, or from the PolicyProvider service as a fall-back value.

Go to the source code of this ViewHelper: Security\NonceViewHelper.php (GitHub).

Examples

Basic usage

<script nonce="{f:security.nonce()}">const inline = 'script';</script>
Copied!

Transform.html ViewHelper <f:transform.html>

ViewHelper to transform HTML and substitute internal link scheme aspects.

Go to the source code of this ViewHelper: Transform\HtmlViewHelper.php (GitHub).

Arguments

The following arguments are available for the transform.html ViewHelper:

onFailure

onFailure
Type
string
Default
'removeEnclosure'
behavior on failure, either `removeTag`, `removeAttr`, `removeEnclosure` or `null`

selector

selector
Type
string
Default
'a.href'
comma separated list of node attributes to be considered

Examples

Default parameters

<f:transform.html selector="a.href" onFailure="removeEnclosure">
  <a href="t3://page?uid=1" class="home">Home</a>
</f:transform.html>
Copied!

Output:

<a href="https://example.com/home" class="home">Home</a>
Copied!

Inline notation

{content -> f:transform.html(selector:'a.href', onFailure:'removeEnclosure')}
Copied!

Uri.action ViewHelper <f:uri.action>

ViewHelper for creating URIs to Extbase actions (within Controllers). Tailored for Extbase plugins, uses Extbase Request and Extbase UriBuilder.

Go to the source code of this ViewHelper: Uri\ActionViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.action ViewHelper:

absolute

absolute
Type
bool
Default
false
If set, an absolute URI is rendered

action

action
Type
string
Target action

addQueryString

addQueryString
Type
string
Default
false
If set, the current query parameters will be kept in the URL. If set to "untrusted", then ALL query parameters will be added. Be aware, that this might lead to problems when the generated link is cached.

additionalParams

additionalParams
Type
array
Default
array ( )
additional query parameters that won't be prefixed like $arguments (overrule $arguments)

arguments

arguments
Type
array
Default
array ( )
Arguments (do not use reserved keywords "action", "controller" or "format" if not referring to these internal variables specifically)

argumentsToBeExcludedFromQueryString

argumentsToBeExcludedFromQueryString
Type
array
Default
array ( )
arguments to be removed from the URI. Only active if $addQueryString = TRUE

controller

controller
Type
string
Target controller. If NULL current controllerName is used

extensionName

extensionName
Type
string
Target Extension Name (without `tx_` prefix and no underscores). If NULL the current extension name is used

format

format
Type
string
Default
''
The requested format, e.g. ".html

language

language
Type
string
link to a specific language - defaults to the current language, use a language ID or "current" to enforce a specific language

linkAccessRestrictedPages

linkAccessRestrictedPages
Type
bool
Default
false
If set, links pointing to access restricted pages will still link to the page even though the page cannot be accessed.

noCache

noCache
Type
bool
Set this to disable caching for the target page. You should not need this.

pageType

pageType
Type
int
Default
0
Type of the target page. See typolink.parameter

pageUid

pageUid
Type
int
Target page. See TypoLink destination

pluginName

pluginName
Type
string
Target plugin. If empty, the current plugin name is used

section

section
Type
string
Default
''
The anchor to be added to the URI

Examples

URI to the show-action of the current controller:

<f:uri.action action="show" />
Copied!

/page/path/name.html?tx_myextension_plugin[action]=show&tx_myextension_plugin[controller]=Standard&cHash=xyz

Depending on current page, routing and page path configuration.

Uri.external ViewHelper <f:uri.external>

ViewHelper for creating URIs to external targets, enforcing a specific scheme (https by default). The specified URI is passed through without further resolving or transformation.

Go to the source code of this ViewHelper: Uri\ExternalViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.external ViewHelper:

defaultScheme

defaultScheme
Type
string
Default
'https'
scheme the href attribute will be prefixed with if specified $uri does not contain a scheme already

uri

uri
Type
string
Required
1
target URI

Examples

Default

<f:uri.external uri="https://www.typo3.org" />
Copied!

https://www.typo3.org

Custom default scheme

<f:uri.external uri="typo3.org" defaultScheme="ftp" />
Copied!

ftp://typo3.org

Uri.image ViewHelper <f:uri.image>

ViewHelper to resize, crop or convert a given image (if required) and return the URL to this processed file.

This ViewHelper should only be used for images within FAL storages, or where graphical operations shall be performed.

Note that when the contents of a non-FAL image are changed, an image may not show updated processed contents unless either the FAL record is updated/removed, or the temporary processed images are cleared.

Also note that image operations (cropping, scaling, converting) on non-FAL files may be changed in future TYPO3 versions, since those operations are coupled with FAL metadata. Each non-FAL image operation creates a "fake" FAL record, which may lead to problems.

For extension resource files, use <f:uri.resource> instead.

External URLs are not processed and just returned as is.

Go to the source code of this ViewHelper: Uri\ImageViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.image ViewHelper:

absolute

absolute
Type
bool
Default
false
Force absolute URL

base64

base64
Type
bool
Default
false
Return a base64 encoded version of the image

crop

crop
Type
string|bool|array
overrule cropping of image (setting to FALSE disables the cropping set in FileReference)

cropVariant

cropVariant
Type
string
Default
'default'
select a cropping variant, in case multiple croppings have been specified or stored in FileReference

fileExtension

fileExtension
Type
string
Custom file extension to use

height

height
Type
string
height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.

image

image
Type
object
image

maxHeight

maxHeight
Type
int
maximum height of the image

maxWidth

maxWidth
Type
int
maximum width of the image

minHeight

minHeight
Type
int
minimum height of the image

minWidth

minWidth
Type
int
minimum width of the image

src

src
Type
string
Default
''
src

treatIdAsReference

treatIdAsReference
Type
bool
Default
false
given src argument is a sys_file_reference record

width

width
Type
string
width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.

Examples

Default

<f:uri.image src="EXT:myext/Resources/Public/typo3_logo.png" />
Copied!

Results in the following output within TYPO3 frontend:

typo3conf/ext/myext/Resources/Public/typo3_logo.png

and the following output inside TYPO3 backend:

../typo3conf/ext/myext/Resources/Public/typo3_logo.png

Image Object

<f:uri.image image="{imageObject}" />
Copied!

Results in the following output within TYPO3 frontend:

fileadmin/images/image.png

and the following output inside TYPO3 backend:

fileadmin/images/image.png

Inline notation

{f:uri.image(src: 'EXT:myext/Resources/Public/typo3_logo.png', minWidth: 30, maxWidth: 40)}
Copied!

typo3temp/assets/images/[b4c0e7ed5c].png

Depending on your TYPO3s encryption key.

Non existing image

<f:uri.image src="NonExistingImage.png" />
Copied!

Could not get image resource for "NonExistingImage.png".

Base 64

When the base64 argument is set to true, this ViewHelper returns a base 64 encoded version of the ressource.

<img src="{f:uri.image(base64: 'true',
                       src:'EXT:backend/Resources/Public/Images/typo3_logo_orange.svg')}">
Copied!

Will return the image encoded in base64:

<img src="data:image/svg+xml;base64,PHN2...cuODQ4LTYuNzU3Ii8+Cjwvc3ZnPgo=">
Copied!

This can be particularly useful inside FluidEmail or to prevent unneeded HTTP calls.

Uri.page ViewHelper <f:uri.page>

ViewHelper for creating URIs to TYPO3 pages.

Go to the source code of this ViewHelper: Uri\PageViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.page ViewHelper:

absolute

absolute
Type
bool
Default
false
If set, the URI of the rendered link is absolute

addQueryString

addQueryString
Type
string
Default
false
If set, the current query parameters will be kept in the URL. If set to "untrusted", then ALL query parameters will be added. Be aware, that this might lead to problems when the generated link is cached.

additionalParams

additionalParams
Type
array
Default
array ( )
query parameters to be attached to the resulting URI

argumentsToBeExcludedFromQueryString

argumentsToBeExcludedFromQueryString
Type
array
Default
array ( )
arguments to be removed from the URI. Only active if $addQueryString = TRUE

language

language
Type
string
link to a specific language - defaults to the current language, use a language ID or "current" to enforce a specific language

linkAccessRestrictedPages

linkAccessRestrictedPages
Type
bool
Default
false
If set, links pointing to access restricted pages will still link to the page even though the page cannot be accessed.

noCache

noCache
Type
bool
Default
false
set this to disable caching for the target page. You should not need this.

pageType

pageType
Type
int
Default
0
type of the target page. See typolink.parameter

pageUid

pageUid
Type
int
target PID

section

section
Type
string
Default
''
the anchor to be added to the URI

Examples

URI to the current page

<f:uri.page>page link</f:uri.page>
Copied!

/page/path/name.html

Depending on current page, routing and page path configuration.

Query parameters

<f:uri.page pageUid="1" additionalParams="{foo: 'bar'}" />
Copied!

/page/path/name.html?foo=bar

Depending on current page, routing and page path configuration.

Query parameters for extensions

<f:uri.page pageUid="1" additionalParams="{extension_key: {foo: 'bar'}}" />
Copied!

/page/path/name.html?extension_key[foo]=bar

Depending on current page, routing and page path configuration.

Uri.resource ViewHelper <f:uri.resource>

ViewHelper for creating URIs to resources (assets).

This ViewHelper should be used to return public locations to extension resource files for use in the frontend output.

For images within FAL storages, or where graphical operations are performed, use <f:uri.image> instead.

Go to the source code of this ViewHelper: Uri\ResourceViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.resource ViewHelper:

absolute

absolute
Type
bool
Default
false
If set, an absolute URI is rendered

extensionName

extensionName
Type
string
Target extension name. If not set, the current extension name will be used

path

path
Type
string
Required
1
The path and filename of the resource (relative to Public resource directory of the extension).

useCacheBusting

useCacheBusting
Type
bool
Default
true
If set, the URI is rendered with a cache buster

Examples

Best practice with EXT: syntax

<link href="{f:uri.resource(path:'EXT:indexed_search/Resources/Public/Css/Stylesheet.css')}" rel="stylesheet" />
Copied!

Output:

<link href="typo3/sysext/indexed_search/Resources/Public/Css/Stylesheet.css" rel="stylesheet" />
Copied!

Preferred syntax that works in both extbase and non-extbase context.

Defaults

<link href="{f:uri.resource(path:'Css/Stylesheet.css')}" rel="stylesheet" />
Copied!

Output:

<link href="typo3conf/ext/example_extension/Resources/Public/Css/Stylesheet.css" rel="stylesheet" />
Copied!

Works only in extbase context since it uses the extbase request to find current extension, magically adds 'Resources/Public' to path.

With extension name

<link href="{f:uri.resource(path:'Css/Stylesheet.css', extensionName: 'AnotherExtension')}" rel="stylesheet" />
Copied!

Output:

<link href="typo3conf/ext/another_extension/Resources/Public/Css/Stylesheet.css" rel="stylesheet" />
Copied!

Magically adds 'Resources/Public' to path.

Alias ViewHelper <f:alias>

Declares new variables which are aliases of other variables. Takes a "map"-Parameter which is an associative array which defines the shorthand mapping.

The variables are only declared inside the <f:alias>...</f:alias> tag. After the closing tag, all declared variables are removed again.

Using this ViewHelper can be a sign of weak architecture. If you end up using it extensively you might want to fine-tune your "view model" (the data you assign to the view).

Examples

Single alias

<f:alias map="{x: 'foo'}">{x}</f:alias>
Copied!

Output:

foo
Copied!

Multiple mappings

<f:alias map="{x: foo.bar.baz, y: foo.bar.baz.name}">
    {x.name} or {y}
</f:alias>
Copied!

Output:

[name] or [name]
Copied!

Depending on {foo.bar.baz}.

Go to the source code of this ViewHelper: AliasViewHelper.php (GitHub).

Arguments

The following arguments are available for the alias ViewHelper:

map

map
Type
array
Required
1
Array that specifies which variables should be mapped to which alias

Argument ViewHelper <f:argument>

f:argument allows to define requirements and type constraints to variables that are provided to templates and partials. This can be very helpful to document how a template or partial is supposed to be used and which input variables are required.

These requirements are enforced during rendering of the template or partial: If an argument is defined with this ViewHelper which isn't marked as optional, an exception will be thrown if that variable isn't present during rendering. If a variable doesn't match the specified type and can't be converted automatically, an exception will be thrown as well.

Note that f:argument ViewHelpers must be used at the root level of the template, and can't be nested into other ViewHelpers. Also, the usage of variables in any of its arguments is not possible (e. g. you can't define an argument name by using a variable).

Example

For the following partial:

<f:argument name="title" type="string" />
<f:argument name="tags" type="string[]" optional="{true}" />
<f:argument name="user" type="string" optional="{true}" default="admin" />

Title: {title}<br />
<f:if condition="{tags}">
  Tags: {tags -> f:join(separator: ', ')}<br />
</f:if>
User: {user}
Copied!

The following render calls will be successful:

<!-- All arguments supplied -->
<f:render partial="MyPartial" arguments="{title: 'My title', tags: {0: 'tag1', 1: 'tag2'}, user: 'me'}" />
<!-- "user" will fall back to default value -->
<f:render partial="MyPartial" arguments="{title: 'My title', tags: {0: 'tag1', 1: 'tag2'}}" />
<!-- "tags" will be "null", "user" will fall back to default value -->
<f:render partial="MyPartial" arguments="{title: 'My title'}" />
Copied!

The following render calls will result in an exception:

<!-- required "title" has not been supplied -->
<f:render partial="MyPartial" />
<!-- "user" has been supplied as array, not as string -->
<f:render partial="MyPartial" arguments="{title: 'My title', user: {firstName: 'Jane', lastName: 'Doe'}}" />
Copied!

Go to the source code of this ViewHelper: ArgumentViewHelper.php (GitHub).

Arguments

The following arguments are available for the argument ViewHelper:

default

default
Type
mixed
default value for optional argument

description

description
Type
string
description of the template argument

name

name
Type
string
Required
1
name of the template argument

optional

optional
Type
boolean
Default
false
true if the defined argument should be optional

type

type
Type
string
Required
1
type of the template argument

Case ViewHelper <f:case>

Case ViewHelper that is only usable within the f:switch ViewHelper.

Go to the source code of this ViewHelper: CaseViewHelper.php (GitHub).

Arguments

The following arguments are available for the case ViewHelper:

value

value
Type
mixed
Required
1
Value to match in this case

CObject ViewHelper <f:cObject>

ViewHelper to render CObjects (objects containing rendering definitions for records/elements), using the global TypoScript configuration.

  <f:cObject typoscriptObjectPath="lib.someLibObject" />
Copied!

Note: You have to ensure proper escaping (htmlspecialchars/intval/etc.) on your own!

Go to the source code of this ViewHelper: CObjectViewHelper.php (GitHub).

Arguments

The following arguments are available for the cObject ViewHelper:

currentValueKey

currentValueKey
Type
string
currentValueKey

data

data
Type
mixed
the data to be used for rendering the cObject. Can be an object, array or string. If this argument is not set, child nodes will be used

table

table
Type
string
Default
''
the table name associated with "data" argument. Typically tt_content or one of your custom tables. This argument should be set if rendering a FILES cObject where file references are used, or if the data argument is a database record.

typoscriptObjectPath

typoscriptObjectPath
Type
string
Required
1
the TypoScript setup path of the TypoScript object to render

Comment ViewHelper <f:comment>

This ViewHelper prevents rendering of any content inside the tag.

Contents of the comment will not be parsed thus it can be used to comment out invalid Fluid syntax or non-existent ViewHelpers during development.

Using this ViewHelper won't have a notable effect on performance, especially once the template is parsed. However, it can lead to reduced readability. You can use layouts and partials to split a large template into smaller parts. Using self-descriptive names for the partials can make comments redundant.

Examples

Commenting out fluid code

Before
<f:comment>
    This is completely hidden.
    <f:debug>This does not get rendered</f:debug>
</f:comment>
After
Copied!

Output:

Before
After
Copied!

Go to the source code of this ViewHelper: CommentViewHelper.php (GitHub).

Constant ViewHelper <f:constant>

Wrapper for PHPs constant function. See https://www.php.net/manual/function.constant.php.

Go to the source code of this ViewHelper: ConstantViewHelper.php (GitHub).

Displaying global PHP constants in Fluid

You can display global PHP constants using this ViewHelper

Maximal possible number: {f:constant(name: 'PHP_INT_MAX')}

<f:if condition="{f:constant(name: 'PHP_MAJOR_VERSION')} >= 8">
    Using PHP 8.0 or greater
</f:if>
Copied!

Get class constant

You can display any public class constant from a class within TYPO3, for example constants from \TYPO3\CMS\Core\Information\Typo3Information :

Join the <f:link.external uri="{f:constant(name: '\TYPO3\CMS\Core\Information\Typo3Information::URL_COMMUNITY')}">
    TYPO3 Community
</f:link.external>!
Copied!

Using enum cases in Fluid

Cases of enums are objects and not strings or integers. They cannot be directly output in the template. You can however save them into a variable and then use their value. For example you can use values of the enum cases in \TYPO3\CMS\Core\Resource\FileType to compare them with a value of your object:

<f:variable name="imageType"><f:constant name="\TYPO3\CMS\Core\Resource\FileType::IMAGE"/></f:variable>
The image case has the value {imageType.value} and name {imageType.name}:
<f:if condition="{myFile.type} === {imageType.value}">
    This file is an image!
</f:if>
Copied!

Arguments

name

name
Type
string
String representation of a PHP constant or enum

Count ViewHelper <f:count>

This ViewHelper counts elements of the specified array or countable object.

Examples

Count array elements

<f:count subject="{0:1, 1:2, 2:3, 3:4}" />
Copied!

Output:

4
Copied!

inline notation

{objects -> f:count()}
Copied!

Output:

10 (depending on the number of items in ``{objects}``)
Copied!

Go to the source code of this ViewHelper: CountViewHelper.php (GitHub).

Arguments

The following arguments are available for the count ViewHelper:

subject

subject
Type
array
Countable subject, array or \Countable

Cycle ViewHelper <f:cycle>

This ViewHelper cycles through the specified values. This can be often used to specify CSS classes for example.

To achieve the "zebra class" effect in a loop you can also use the "iteration" argument of the for ViewHelper.

Examples

These examples could also be achieved using the "iteration" argument of the ForViewHelper.

Simple

<f:for each="{0:1, 1:2, 2:3, 3:4}" as="foo">
    <f:cycle values="{0: 'foo', 1: 'bar', 2: 'baz'}" as="cycle">
        {cycle}
    </f:cycle>
</f:for>
Copied!

Output:

foobarbazfoo
Copied!

Alternating CSS class

<ul>
    <f:for each="{0:1, 1:2, 2:3, 3:4}" as="foo">
        <f:cycle values="{0: 'odd', 1: 'even'}" as="zebraClass">
            <li class="{zebraClass}">{foo}</li>
        </f:cycle>
    </f:for>
</ul>
Copied!

Output:

<ul>
    <li class="odd">1</li>
    <li class="even">2</li>
    <li class="odd">3</li>
    <li class="even">4</li>
</ul>
Copied!

Go to the source code of this ViewHelper: CycleViewHelper.php (GitHub).

Arguments

The following arguments are available for the cycle ViewHelper:

as

as
Type
string
Required
1
The name of the iteration variable

values

values
Type
array
The array or object implementing \ArrayAccess (for example \SplObjectStorage) to iterated over

Debug ViewHelper <f:debug>

ViewHelper to generate an HTML readable dump of variables or objects. The output can be navigated like a nested tree. The output will be put at the beginning of the HTML response, unless the inline attribute is set, so that the output will be placed at the specific place where it is placed inside a Fluid template.

Go to the source code of this ViewHelper: DebugViewHelper.php (GitHub).

Arguments

The following arguments are available for the debug ViewHelper:

ansiColors

ansiColors
Type
bool
Default
false
If TRUE, ANSI color codes is added to the plaintext output, if FALSE (default) the plaintext debug output not colored.

blacklistedClassNames

blacklistedClassNames
Type
array
An array of class names (RegEx) to be filtered. Default is an array of some common class names.

blacklistedPropertyNames

blacklistedPropertyNames
Type
array
An array of property names and/or array keys (RegEx) to be filtered. Default is an array of some common property names.

inline

inline
Type
bool
Default
false
if TRUE, the dump is rendered at the position of the <f:debug> tag. If FALSE (default), the dump is displayed at the top of the page.

maxDepth

maxDepth
Type
int
Default
8
Sets the max recursion depth of the dump (defaults to 8). De- or increase the number according to your needs and memory limit.

plainText

plainText
Type
bool
Default
false
If TRUE, the dump is in plain text, if FALSE the debug output is in HTML format.

title

title
Type
string
optional custom title for the debug output

Examples

Simple

<f:debug>{myVariable}</f:debug>
Copied!

[A HTML dump of myVariable value]

All Features

<f:debug title="My Title" maxDepth="5"
    blacklistedClassNames="{0:'ACME\BlogExample\Domain\Model\Administrator'}"
    blacklistedPropertyNames="{0:'posts'}"
    plainText="true" ansiColors="false"
    inline="true"
>
    {blogs}
</f:debug>
Copied!

[A HTML view of the var_dump]

DefaultCase ViewHelper <f:defaultCase>

A ViewHelper which specifies the "default" case when used within the f:switch ViewHelper.

Go to the source code of this ViewHelper: DefaultCaseViewHelper.php (GitHub).

Else ViewHelper <f:else>

Else-Branch of a condition. Only has an effect inside of f:if. See the f:if ViewHelper for documentation.

Examples

Output content if condition is not met

<f:if condition="{someCondition}">
    <f:else>
        condition was not true
    </f:else>
</f:if>
Copied!

Output:

Everything inside the "else" tag is displayed if the condition evaluates to false.
Otherwise, nothing is outputted in this example.
Copied!

Go to the source code of this ViewHelper: ElseViewHelper.php (GitHub).

Arguments

The following arguments are available for the else ViewHelper:

if

if
Type
boolean
Condition expression conforming to Fluid boolean rules

Feature ViewHelper <f:feature>

ViewHelper to check if a feature flag is enabled, implemented as a condition like an "if" construct.

Go to the source code of this ViewHelper: FeatureViewHelper.php (GitHub).

Arguments

The following arguments are available for the feature ViewHelper:

else

else
Type
mixed
Value to be returned if the condition if not met.

name

name
Type
string
Required
1
name of the feature flag that should be checked

then

then
Type
mixed
Value to be returned if the condition if met.

Examples

Basic usage

<f:feature name="myFeatureFlag">
   This is being shown if the flag is enabled
</f:feature>
Copied!

feature / then / else

<f:feature name="myFeatureFlag">
   <f:then>
      Flag is enabled
   </f:then>
   <f:else>
      Flag is undefined or not enabled
   </f:else>
</f:feature>
Copied!

First ViewHelper <f:first>

The FirstViewHelper returns the first item of an array.

Example

<f:first value="{0: 'first', 1: 'second'}" />
Copied!
first
Copied!

Go to the source code of this ViewHelper: FirstViewHelper.php (GitHub).

Arguments

The following arguments are available for the first ViewHelper:

value

value
Type
array

FlashMessages ViewHelper <f:flashMessages>

This ViewHelper renders the Flash messages (if there are any) as an unsorted list.

Screenshot of two flash message one with success and one with warning severity

Example for the output of flash messages in an Extbase plugin

Go to the source code of this ViewHelper: FlashMessagesViewHelper.php (GitHub).

Quick start: Simple flash message output

You can use the following tag within any Extbase template:

packages/my_extension/Resources/Private/Templates/Something/DoSomething.html
<f:flashMessages />
Copied!

It displays the flash messages with a standard bootstrap compatible layout.

Adding and displaying flash messages in Extbase

Within an Extbase controller (extending ActionController ) you can call method addFlashMessage() to add flash messages to the message queue:

packages/my_extension/Classes/Controller/MyController.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;

class MyController extends ActionController
{
    public function demonstrateFlashMessagesAction(): ResponseInterface
    {
        $this->addFlashMessage('This is a success message.');
        $this->addFlashMessage('This is a warning.', 'Warning Headline', ContextualFeedbackSeverity::WARNING);
        return $this->htmlResponse();
    }
}
Copied!

As mentioned above, they will be displayed when a <f:flashMessages> is displayed within any action of the same controller:

packages/my_extension/Resources/Private/Templates/My/DemonstrateFlashMessages.html
<f:layout name="MyLayout"/>
<f:section name="Content">
    <f:flashMessages />
</f:section>
Copied!

If you want to display the flash messages in any place outside of the controller you can use the identifier extbase.flashmessages.<pluginNamespace>, for example:

packages/my_extension/Resources/Private/Templates/Other/SomeForm.html
<f:layout name="MyLayout"/>
<f:section name="Content">
    <f:flashMessages queueIdentifier="extbase.flashmessages.tx_myextension_myplugin"/>
</f:section>
Copied!

Using a specific flash message queue in plain classes

When you use the FlashMessages ViewHelper outside of the Extbase context, supplying the queueIdentifier is mandatory.

When you add a message manually to the queue, you can specify an arbitrary identifier:

// private \TYPO3\CMS\Core\Messaging\FlashMessageService $flashMessageService;

$messageQueue = $this->flashMessageService->getMessageQueueByIdentifier('myQueue');
Copied!

You can then display messages of only this one queue using the identifier:

<f:flashMessages queueIdentifier="myQueue" />
Copied!

Output flash messages with a custom layout

Using the argument as you can receive all flash messages in a variable and then handle the rendering yourself within the <f:flashMessages> tag:

packages/my_extension/Resources/Private/Templates/Something/DoSomething.html
<f:flashMessages as="flashMessages">
  <dl class="messages">
    <f:for each="{flashMessages}" as="flashMessage">
      <dt>{flashMessage.code}</dt>
      <dd>{flashMessage.message}</dd>
    </f:for>
  </dl>
</f:flashMessages>
Copied!

Argument of the FlashMessages ViewHelper

as

as
Type
string
The name of the current flashMessage variable for rendering inside

queueIdentifier

queueIdentifier
Type
string
Flash-message queue to use

For ViewHelper <f:for>

Loop ViewHelper which can be used to iterate over arrays. Implements what a basic PHP foreach() does.

Examples

Simple Loop

<f:for each="{0:1, 1:2, 2:3, 3:4}" as="foo">{foo}</f:for>
Copied!

Output:

1234
Copied!

Output array key

<ul>
    <f:for each="{fruit1: 'apple', fruit2: 'pear', fruit3: 'banana', fruit4: 'cherry'}"
        as="fruit" key="label"
    >
        <li>{label}: {fruit}</li>
    </f:for>
</ul>
Copied!

Output:

<ul>
    <li>fruit1: apple</li>
    <li>fruit2: pear</li>
    <li>fruit3: banana</li>
    <li>fruit4: cherry</li>
</ul>
Copied!

Iteration information

<ul>
    <f:for each="{0:1, 1:2, 2:3, 3:4}" as="foo" iteration="fooIterator">
        <li>Index: {fooIterator.index} Cycle: {fooIterator.cycle} Total: {fooIterator.total}{f:if(condition: fooIterator.isEven, then: ' Even')}{f:if(condition: fooIterator.isOdd, then: ' Odd')}{f:if(condition: fooIterator.isFirst, then: ' First')}{f:if(condition: fooIterator.isLast, then: ' Last')}</li>
    </f:for>
</ul>
Copied!

Output:

<ul>
    <li>Index: 0 Cycle: 1 Total: 4 Odd First</li>
    <li>Index: 1 Cycle: 2 Total: 4 Even</li>
    <li>Index: 2 Cycle: 3 Total: 4 Odd</li>
    <li>Index: 3 Cycle: 4 Total: 4 Even Last</li>
</ul>
Copied!

Go to the source code of this ViewHelper: ForViewHelper.php (GitHub).

Arguments

The following arguments are available for the for ViewHelper:

as

as
Type
string
Required
1
The name of the iteration variable

each

each
Type
array
Required
1
The array or \SplObjectStorage to iterated over

iteration

iteration
Type
string
The name of the variable to store iteration information (index, cycle, total, isFirst, isLast, isEven, isOdd)

key

key
Type
string
Variable to assign array key to

reverse

reverse
Type
boolean
Default
false
If true, iterates in reverse

GroupedFor ViewHelper <f:groupedFor>

Grouped loop ViewHelper. Loops through the specified values.

The groupBy argument also supports property paths.

Using this ViewHelper can be a sign of weak architecture. If you end up using it extensively you might want to fine-tune your "view model" (the data you assign to the view).

Examples

Simple

<f:groupedFor each="{0: {name: 'apple', color: 'green'}, 1: {name: 'cherry', color: 'red'}, 2: {name: 'banana', color: 'yellow'}, 3: {name: 'strawberry', color: 'red'}}"
    as="fruitsOfThisColor" groupBy="color"
>
    <f:for each="{fruitsOfThisColor}" as="fruit">
        {fruit.name}
    </f:for>
</f:groupedFor>
Copied!

Output:

apple cherry strawberry banana
Copied!

Two dimensional list

<ul>
    <f:groupedFor each="{0: {name: 'apple', color: 'green'}, 1: {name: 'cherry', color: 'red'}, 2: {name: 'banana', color: 'yellow'}, 3: {name: 'strawberry', color: 'red'}}" as="fruitsOfThisColor" groupBy="color" groupKey="color">
        <li>
            {color} fruits:
            <ul>
                <f:for each="{fruitsOfThisColor}" as="fruit" key="label">
                    <li>{label}: {fruit.name}</li>
                </f:for>
            </ul>
        </li>
    </f:groupedFor>
</ul>
Copied!

Output:

<ul>
    <li>green fruits
        <ul>
            <li>0: apple</li>
        </ul>
    </li>
    <li>red fruits
        <ul>
            <li>1: cherry</li>
        </ul>
        <ul>
            <li>3: strawberry</li>
        </ul>
    </li>
    <li>yellow fruits
        <ul>
            <li>2: banana</li>
        </ul>
    </li>
</ul>
Copied!

Go to the source code of this ViewHelper: GroupedForViewHelper.php (GitHub).

Arguments

The following arguments are available for the groupedFor ViewHelper:

as

as
Type
string
Required
1
The name of the iteration variable

each

each
Type
array
Required
1
The array or \SplObjectStorage to iterated over

groupBy

groupBy
Type
string
Required
1
Group by this property

groupKey

groupKey
Type
string
Default
'groupKey'
The name of the variable to store the current group

If ViewHelper <f:if>

This ViewHelper implements an if/else condition.

Fluid Boolean Rules / Conditions:

A condition is evaluated as a boolean value, so you can use any boolean argument, like a variable. Alternatively, you can use a full boolean expression. The entered expression is evaluated as a PHP expression. You can combine multiple expressions via && (logical AND) and || (logical OR).

An expression can also be prepended with the ! ("not") character, which will negate that expression.

Have a look into the Fluid section of the "TYPO3 Explained" Documentation for more details about complex conditions.

Boolean expressions have the following form:

is true variant: {variable}:

<f:if condition="{foo}">
    Will be shown if foo is truthy.
</f:if>
Copied!

or is false variant: !{variable}:

<f:if condition="!{foo}">
    Will be shown if foo is falsy.
</f:if>
Copied!

or comparisons with expressions:

XX Comparator YY
Copied!

Comparator is one of: ==, !=, <, <=, >, >= and % The % operator (modulo) converts the result of the operation to boolean.

XX and YY can be one of:

  • Number
  • String
  • Object Accessor (object.property)
  • Array
  • a ViewHelper
<f:if condition="{rank} > 100">
    Will be shown if rank is > 100
</f:if>
<f:if condition="{rank} % 2">
    Will be shown if rank % 2 != 0.
</f:if>
<f:if condition="{rank} == {k:bar()}">
    Checks if rank is equal to the result of the ViewHelper "k:bar"
</f:if>
<f:if condition="{object.property} == 'stringToCompare'">
    Will result in true if {object.property}'s represented value
    equals 'stringToCompare'.
</f:if>
Copied!

Examples

Basic usage

<f:if condition="somecondition">
    This is being shown in case the condition matches
</f:if>
Copied!

Output:

Everything inside the <f:if> tag is being displayed if the condition evaluates to true.
Copied!

If / then / else

<f:if condition="somecondition">
    <f:then>
        This is being shown in case the condition matches.
    </f:then>
    <f:else>
        This is being displayed in case the condition evaluates to false.
    </f:else>
</f:if>
Copied!

Output:

Everything inside the "then" tag is displayed if the condition evaluates to true.
Otherwise, everything inside the "else" tag is displayed.
Copied!

Inline notation

{f:if(condition: someCondition, then: 'condition is met', else: 'condition is not met')}
Copied!

Output:

The value of the "then" attribute is displayed if the condition evaluates to true.
Otherwise, everything the value of the "else" attribute is displayed.
Copied!

Combining multiple conditions

<f:if condition="{user.rank} > 100 && {user.type} == 'contributor'">
    <f:then>
        This is being shown in case both conditions match.
    </f:then>
    <f:else if="{user.rank} > 200 && ({user.type} == 'contributor' || {user.type} == 'developer')">
        This is being displayed in case the first block of the condition evaluates to true and any condition in
        the second condition block evaluates to true.
    </f:else>
    <f:else>
        This is being displayed when none of the above conditions evaluated to true.
    </f:else>
</f:if>
Copied!

Output:

Depending on which expression evaluated to true, that value is displayed.
If no expression matched, the contents inside the final "else" tag are displayed.
Copied!

Go to the source code of this ViewHelper: IfViewHelper.php (GitHub).

Arguments

The following arguments are available for the if ViewHelper:

condition

condition
Type
boolean
Default
false
Condition expression conforming to Fluid boolean rules

else

else
Type
mixed
Value to be returned if the condition if not met.

then

then
Type
mixed
Value to be returned if the condition if met.

Image ViewHelper <f:image>

ViewHelper to resize, crop or convert a given image (if required) and render the corresponding HTML <img> tag showing the processed image.

Note that image operations (cropping, scaling, converting) on non-FAL files (i.e. extension resources) may be changed in future TYPO3 versions, since those operations are coupled with FAL metadata. Each non-FAL image operation creates a "fake" FAL record, which may lead to problems.

External URLs are not processed.

Go to the source code of this ViewHelper: ImageViewHelper.php (GitHub).

Argument src - displaying images from extension assets

Images used for design purposes and not content purposes are commonly shipped in an extension. These images cannot be edited by backend users. They can be displayed using the <f:image> ViewHelper using the src argument and EXT: syntax:

<f:image src="EXT:my_site_package/Resources/Public/images/typo3_logo.png" alt="alt text" />
Copied!

In the extension the assets must be stored under Resources/Public/ or a subfolder of this folder.

If you installed the extension via Composer before it had a folder of that exact name, reinstall it so that the symlinks in folder public/_assets are correctly created for you.

Argument image - display images from the folder fileadmin / from FAL

Folders from inside the folder fileadmin are usually accessed using the file abstraction layer (FAL).

For example, if you want to display an image that is attached to a content element, the content element typically stores a reference count of attached images in its media field. Intermediate tables are then used to attach the actual image to the content elements. This allows backend users to move or rename files, without the files connection being lost in the content element.

FLUIDTEMPLATE and data processors and images

In a TypoScript FLUIDTEMPLATE you can use the files data processor to display an image with the <f:image> ViewHelper.

See Example: Render the images stored in field image in the TypoScript reference.

You can then use the image argument to pass the File or FileReference provided by the TypoScript data processor to the ViewHelper.

<f:for each="{images}" as="image">
    <f:image image="{image}" class="something" height="250" alt="Description"/>
</f:for>
Copied!

The FAL will scale the image and convert it to a web format if necessary (for example from a pdf to a png).

The <f:image> ViewHelper generates a HTML <img> tag with the correct paths, etc.

Images from Extbase models in Fluid

In Extbase models you can use fields of type \TYPO3\CMS\Extbase\Persistence\ObjectStorage with the TCA type File.

When you are looping through the object storage, each element will be of type \TYPO3\CMS\Extbase\Domain\Model\FileReference . They can be used with the image argument:

<f:for each="{mymodel.images}" as="image">
    <f:image image="{image}" class="something" height="250"/>
</f:for>
Copied!

If the field should only contain a maximum of one image (maxitems=1), you can display the image simply by selecting the first array element:

<f:if condition="{mymodel.image.0}">
    <f:image image="{mymodel.image.0}" class="something" height="250"/>
</f:if>
Copied!

Using the UID of the database entry directly

If you have the UID of the sys_file_reference table (preferred) you have to set treatIdAsReference to true and pass the UID of the file reference to the src argument.

If only the UID of the sys_file table is available, you can pass this value to the src argument of the ViewHelper and treatIdAsReference can be kept as the default value (false). In this case no data from the file reference, such as default cropping or overrides for alt text and description, will be available.

<f:image src="{reference.uid}" treatIdAsReference="1" height="250"/>
<f:image src="{file.uid}" height="250" alt="My image description"/>

<!-- File with uid 42 -->
<f:image src="42" treatIdAsReference="1" class="something" height="250"/>
Copied!

Embedding SVG files with the base64 attribute

When the base64 argument is set to true, the resulting image tag will contain the source of the image in a base64 encoded form.

<f:image base64="true"
         src="EXT:backend/Resources/Public/Images/typo3_logo_orange.svg"
         class="pr-2"
/>
Copied!

This will result in the HTML tag providing the image encoded in base64.

<img class="pr-2"
     src="data:image/svg+xml;base64,PHN2...cuODQ4LTYuNzU3Ii8+Cjwvc3ZnPgo="
     alt=""
>
Copied!

This can be particularly useful inside FluidEmail or to prevent unnecessary HTTP calls.

Arguments of the <f:image> ViewHelper

absolute

absolute
Type
bool
Default
false
Force absolute URL

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

base64

base64
Type
bool
Default
false
Adds the image data base64-encoded inline to the image‘s "src" attribute. Useful for FluidEmail templates.

crop

crop
Type
string|bool|array
overrule cropping of image (setting to FALSE disables the cropping set in FileReference)

cropVariant

cropVariant
Type
string
Default
'default'
select a cropping variant, in case multiple croppings have been specified or stored in FileReference

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

fileExtension

fileExtension
Type
string
Custom file extension to use

height

height
Type
string
height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.height in the TypoScript Reference https://docs.typo3.org/permalink/t3tsref:confval-imgresource-height for possible options.

image

image
Type
object
a FAL object (\TYPO3\CMS\Core\Resource\File or \TYPO3\CMS\Core\Resource\FileReference)

maxHeight

maxHeight
Type
int
maximum height of the image

maxWidth

maxWidth
Type
int
maximum width of the image

minHeight

minHeight
Type
int
minimum height of the image

minWidth

minWidth
Type
int
minimum width of the image

src

src
Type
string
Default
''
a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead

treatIdAsReference

treatIdAsReference
Type
bool
Default
false
given src argument is a sys_file_reference record

width

width
Type
string
width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width in the TypoScript Reference on https://docs.typo3.org/permalink/t3tsref:confval-imgresource-width for possible options.

Inline ViewHelper <f:inline>

Inline Fluid rendering ViewHelper

Renders Fluid code stored in a variable, which you normally would have to render before assigning it to the view. Instead you can do the following (note, extremely simplified use case):

$view->assign('variable', 'value of my variable');
$view->assign('code', 'My variable: {variable}');
Copied!

And in the template:

{code -> f:inline()}
Copied!

Which outputs:

My variable: value of my variable
Copied!

You can use this to pass smaller and dynamic pieces of Fluid code to templates, as an alternative to creating new partial templates.

Go to the source code of this ViewHelper: InlineViewHelper.php (GitHub).

Arguments

The following arguments are available for the inline ViewHelper:

code

code
Type
string
Fluid code to be rendered as if it were part of the template rendering it. Can be passed as inline argument or tag content

Join ViewHelper <f:join>

The JoinViewHelper combines elements from an array into a single string. You can specify both a general separator and a special one for the last element, which serves as the delimiter between the elements.

Examples

Simple join

<f:join value="{0: '1', 1: '2', 2: '3'}" />
Copied!
123
Copied!

Join with separator

<f:join value="{0: '1', 1: '2', 2: '3'}" separator=", " />
Copied!
1, 2, 3
Copied!

Join with separator, and special one for the last

<f:join value="{0: '1', 1: '2', 2: '3'}" separator=", " separatorLast=" and " />
Copied!
1, 2 and 3
Copied!

Go to the source code of this ViewHelper: JoinViewHelper.php (GitHub).

Arguments

The following arguments are available for the join ViewHelper:

separator

separator
Type
string
Default
''
The separator

separatorLast

separatorLast
Type
string
The separator for the last pair.

value

value
Type
array
An array

Last ViewHelper <f:last>

The LastViewHelper returns the last item of an array.

Example

<f:last value="{0: 'first', 1: 'second'}" />
Copied!
second
Copied!

Go to the source code of this ViewHelper: LastViewHelper.php (GitHub).

Arguments

The following arguments are available for the last ViewHelper:

value

value
Type
array

Layout ViewHelper <f:layout>

With this tag, you can select a layout to be used for the current template.

Examples

<f:layout name="main" />
Copied!

Output:

(no output)
Copied!

Go to the source code of this ViewHelper: LayoutViewHelper.php (GitHub).

Arguments

The following arguments are available for the layout ViewHelper:

name

name
Type
string
Name of layout to use. If none given, "Default" is used.

Media ViewHelper <f:media>

ViewHelper to render a given media file (audio/video/images) with the correct HTML tag.

It utilizes the RendererRegistry to determine the correct Renderer class. When no renderer can be resolved, it will fall back to use the default ImageViewHelper for regular images.

Go to the source code of this ViewHelper: MediaViewHelper.php (GitHub).

Arguments

The following arguments are available for the media ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

additionalConfig

additionalConfig
Type
array
Default
array ( )
This array can hold additional configuration that is passed though to the Renderer object

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

cropVariant

cropVariant
Type
string
Default
'default'
select a cropping variant, in case multiple croppings have been specified or stored in FileReference

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

decoding

decoding
Type
string
Provides an image decoding hint to the browser. Can be "sync", "async" or "auto"

file

file
Type
object
Required
1
File

fileExtension

fileExtension
Type
string
Custom file extension to use for images

height

height
Type
string
This can be a numeric value representing the fixed height in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.

loading

loading
Type
string
Native lazy-loading for images property. Can be "lazy", "eager" or "auto". Used on image files only.

width

width
Type
string
This can be a numeric value representing the fixed width of in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.

Examples

Image Object

<f:media file="{file}" width="400" height="375" />
Copied!

Output:

<img alt="alt set in image record" src="fileadmin/_processed_/323223424.png" width="396" height="375" />
Copied!

MP4 Video Object

<f:media file="{file}" width="400" height="375" />
Copied!

Output:

<video width="400" height="375" controls><source src="fileadmin/user_upload/my-video.mp4" type="video/mp4"></video>
Copied!

MP4 Video Object with loop and autoplay option set

<f:media file="{file}" width="400" height="375" additionalConfig="{loop: '1', autoplay: '1'}" />
Copied!

Output:

<video width="400" height="375" controls loop><source src="fileadmin/user_upload/my-video.mp4" type="video/mp4"></video>
Copied!

Or ViewHelper <f:or>

Or ViewHelper

If content is null use alternative text.

Usage of f:or

{f:variable(name:'fallback',value:'this is not the variable you\'re looking for')}
{undefinedVariable -> f:or(alternative:fallback)}
Copied!

Usage of ternary operator

In some cases (e.g. when you want to check for empty instead of null) it might be more handy to use a ternary operator instead of f:or

{emptyVariable ?: 'this is an alterative text'}
Copied!

Go to the source code of this ViewHelper: OrViewHelper.php (GitHub).

Arguments

The following arguments are available for the or ViewHelper:

alternative

alternative
Type
mixed
Alternative if content is null

arguments

arguments
Type
array
Arguments to be replaced in the resulting string, using sprintf

content

content
Type
mixed
Content to check if null

Render ViewHelper <f:render>

Go to the source code of this ViewHelper: RenderViewHelper.php (GitHub).

Rendering a partial

The render ViewHelper can be used with the argument partial to render the content of a "partial". A partial is a separate Fluid file.

packages/my_site_package/Resources/Private/PageView/Pages/Default.html
<f:render partial="Footer" arguments="{_all}"/>
Copied!

During rendering the content of file packages/my_site_package/Resources/Private/PageView/Partials/Footer.html will be rendered with all variables that are also available in the main template.

It is possible to render a partial within a partial or layout as well. For example the footer partial could look like this:

packages/my_site_package/Resources/Private/PageView/Partials/Footer.html
<footer class="my-footer">
    <f:render partial="Navigation/FooterMenu" arguments="{_all}"/>
</footer>
Copied!

When the argument partial contains a slash / the partial will be searched in a subfolder. The partial from the above example will therefore be expected in file packages/my_site_package/Resources/Private/PageView/Partials/Navigation/FooterMenu.html.

Configuring the path in which to save the partials

Rendering a section

When the render ViewHelper is used with the argument section the content of a Section ViewHelper <f:section> can be rendered.

packages/my_site_package/Resources/Private/PageView/Layouts/PageLayout.html
<f:render section="SomeSection"/>

<f:section name="SomeSection">
    This is the section.
</f:section>
Copied!

Rendering sections in layouts

If the section is rendered from within a layout file the section can be defined in the template using the layout. Since usually several templates use the same layout, it can be helpful to mark the render tag as optional. It is also possible to provide a default value to be displayed if the section was not found in the template. You can use the content of the tag or the argument default.

packages/my_site_package/Resources/Private/PageView/Layouts/PageLayout.html
<f:render section="Header" optional="true">
    <f:render partial="Header" arguments="{_all}"/>
</f:render>
<f:render section="Breadcrumb" optional="true"/>
<f:render section="Main"/>
Copied!

In this example the templates may define a section called "Header" to override the default header rendered from a partial.

If the template defines no section named "Breadcrumb" that section is just ignored.

All templates have to define the section "Main" otherwise there is an error.

Template 1 just defines some content:

packages/my_site_package/Resources/Private/PageView/Pages/Template1.html
<f:layout name="PageLayout"/>
<f:section name="Main">
    <main>Main content of Template 1</main>
</f:section>
Copied!
packages/my_site_package/Resources/Private/PageView/Pages/Template2.html
<f:layout name="PageLayout"/>
<f:section name="Header">
    <header>My Special header</header>
</f:section>
<f:section name="Breadcrumb">
    <f:render partial="Navigation/Breadcrumb" arguments="{_all}">
</f:section>
<f:section name="Main">
    <main>Main content of Template 1</main>
</f:section>
Copied!

Rendering a section from a (different) partial

If both arguments section and partial are used a section found in a partial can be rendered.

Arguments

arguments

arguments
Type
array
Default
array ( )
Array of variables to be transferred. Use {_all} for all variables

contentAs

contentAs
Type
string
If used, renders the child content and adds it as a template variable with this name for use in the partial/section

debug

debug
Type
boolean
Default
true
If true, the admin panel shows debug information if activated,

default

default
Type
mixed
Value (usually string) to be displayed if the section or partial does not exist

delegate

delegate
Type
string
Optional PHP class name of a permanent, included-in-app ParsedTemplateInterface implementation to override partial/section

optional

optional
Type
boolean
Default
false
If true, considers the *section* optional. Partial never is.

partial

partial
Type
string
Partial to render, with or without section

section

section
Type
string
Section to render - combine with partial to render section in partial

Replace ViewHelper <f:replace>

The ReplaceViewHelper replaces one or multiple strings with other strings. This ViewHelper mimicks PHP's str_replace() function. However, it's also possible to provide replace pairs as associative array via the "replace" argument.

Examples

Replace a single string

<f:replace value="Hello World" search="World" replace="Fluid" />
Copied!
Hello Fluid
Copied!

Replace multiple strings

<f:replace value="Hello World" search="{0: 'World', 1: 'Hello'}" replace="{0: 'Fluid', 1: 'Hi'}" />
Copied!
Hi Fluid
Copied!

Replace multiple strings using associative array

<f:replace value="Hello World" replace="{'World': 'Fluid', 'Hello': 'Hi'}" />
Copied!
Hi Fluid
Copied!

Go to the source code of this ViewHelper: ReplaceViewHelper.php (GitHub).

Arguments

The following arguments are available for the replace ViewHelper:

replace

replace
Type
mixed
Required
1

search

Type
mixed

value

value
Type
string

Section ViewHelper <f:section>

A ViewHelper to declare sections in templates for later use with e.g. the f:render ViewHelper.

Examples

Rendering sections

<f:section name="someSection">This is a section. {foo}</f:section>
<f:render section="someSection" arguments="{foo: someVariable}" />
Copied!

Output:

the content of the section "someSection". The content of the variable {someVariable} will be available in the partial as {foo}
Copied!

Rendering recursive sections

<f:section name="mySection">
   <ul>
        <f:for each="{myMenu}" as="menuItem">
             <li>
               {menuItem.text}
               <f:if condition="{menuItem.subItems}">
                   <f:render section="mySection" arguments="{myMenu: menuItem.subItems}" />
               </f:if>
             </li>
        </f:for>
   </ul>
</f:section>
<f:render section="mySection" arguments="{myMenu: menu}" />
Copied!

Output:

<ul>
    <li>menu1
        <ul>
            <li>menu1a</li>
            <li>menu1b</li>
        </ul>
    </li>
[...]
(depending on the value of {menu})
Copied!

Go to the source code of this ViewHelper: SectionViewHelper.php (GitHub).

Arguments

The following arguments are available for the section ViewHelper:

name

name
Type
string
Required
1
Name of the section

Spaceless ViewHelper <f:spaceless>

Space Removal ViewHelper

Removes redundant spaces between HTML tags while preserving the whitespace that may be inside HTML tags. Trims the final result before output.

Heavily inspired by Twig's corresponding node type.

Usage of f:spaceless

<f:spaceless>
    <div>
        <div>
            <div>text

    text</div>
        </div>
    </div>
</f:spaceless>
Copied!

Output:

<div><div><div>text

text</div></div></div>
Copied!

Go to the source code of this ViewHelper: SpacelessViewHelper.php (GitHub).

Split ViewHelper <f:split>

The SplitViewHelper splits a string by the specified separator, which results in an array. The number of values in the resulting array can be limited with the limit parameter, which results in an array where the last item contains the remaining unsplit string.

This ViewHelper mimicks PHP's explode() function.

The following examples store the result in a variable because an array cannot be outputted directly in a template.

Examples

Split with a separator

<f:variable name="result"><f:split value="1,5,8" separator="," /></f:variable>
Copied!
{0: '1', 1: '5', 2: '8'}
Copied!

Split using tag content as value

<f:variable name="result"><f:split separator="-">1-5-8</f:split></f:variable>
Copied!
{0: '1', 1: '5', 2: '8'}
Copied!

Split with a limit

<f:variable name="result"><f:split value="1,5,8" separator="," limit="2" /></f:variable>
Copied!
{0: '1', 1: '5,8'}
Copied!

Go to the source code of this ViewHelper: SplitViewHelper.php (GitHub).

Arguments

The following arguments are available for the split ViewHelper:

limit

limit
Type
int
Default
9223372036854775807
If limit is positive, a maximum of $limit items will be returned. If limit is negative, all items except for the last $limit items will be returned. 0 will be treated as 1.

separator

separator
Type
string
Required
1
Separator string to explode with

value

value
Type
string
The string to explode

Switch ViewHelper <f:switch>

Switch ViewHelper which can be used to render content depending on a value or expression. Implements what a basic PHP switch() does.

An optional default case can be specified which is rendered if none of the case conditions matches.

Using this ViewHelper can be a sign of weak architecture. If you end up using it extensively you might want to consider restructuring your controllers/actions and/or use partials and sections. E.g. the above example could be achieved with <f:render partial="title.{person.gender}" /> and the partials "title.male.html", "title.female.html", ... Depending on the scenario this can be easier to extend and possibly contains less duplication.

Examples

Simple Switch statement

<f:switch expression="{person.gender}">
    <f:case value="male">Mr.</f:case>
    <f:case value="female">Mrs.</f:case>
    <f:defaultCase>Mr. / Mrs.</f:defaultCase>
</f:switch>
Copied!

Output:

"Mr.", "Mrs." or "Mr. / Mrs." (depending on the value of {person.gender})
Copied!

Go to the source code of this ViewHelper: SwitchViewHelper.php (GitHub).

Arguments

The following arguments are available for the switch ViewHelper:

expression

expression
Type
mixed
Required
1
Expression to switch

Then ViewHelper <f:then>

f:then only has an effect inside of f:if. See the f:if ViewHelper for documentation.

Go to the source code of this ViewHelper: ThenViewHelper.php (GitHub).

Translate ViewHelper <f:translate>

ViewHelper to provide a translation for language keys ("locallang"/"LLL"). By default, the files are loaded from the folder Resources/Private/Language/. Placeholder substitution (like PHP's sprintf()) can be evaluated when provided as arguments attribute.

Go to the source code of this ViewHelper: TranslateViewHelper.php (GitHub).

Examples

Short key - Usage in Extbase

The key argument alone works only within the Extbase context.

<f:translate key="domain_model.title" />
Copied!
packages/my_extension/Resources/Private/Language/locallang.xlf
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
	<file source-language="en" datatype="plaintext"
		original="EXT:my_extension/Resources/Private/Language/locallang.xlf"
		date="2020-10-18T18:20:51Z" product-name="my_extension"
	>
		<header />
		<body>
			<trans-unit id="domain_model.title">
				<source>My Model</source>
			</trans-unit>
		</body>
	</file>
</xliff>
Copied!

Alternatively, you can use id instead of key, producing the same output. If both id and key are set, id takes precedence.

If the translate ViewHelper is used with only the language key, the template must be rendered within an Extbase request, usually from an Extbase controller action. The default language file must be located in the same extension as the Extbase controller and must be saved in the file Resources/Private/Language/locallang.xlf.

Short key and extension name

When the ViewHelper is called from outside Extbase, it is mandatory to either pass the extension name or use the full LLL: reference for the key.

<f:translate key="domain_model.title" extension="my_extension" />
Copied!

The default language file must be saved in the extension specified in the argument, in the file Resources/Private/Language/locallang.xlf.

Full LLL: reference key

Using the LLL: language reference syntax, a language key from any .xlf file can be used.

<f:translate
    key="LLL:EXT:my_extension/Resources/Private/Language/my_locallang.xlf:domain_model.title"
/>
Copied!

Keeping HTML tags within translations

HTML in language labels can be used when you surround the translate ViewHelper with a ViewHelper that allows HTML output, such as the Sanitize.html ViewHelper <f:sanitize.html> in the backend or the Format.html ViewHelper <f:format.html> in the frontend.

<f:format.html>
    <f:translate
        key="LLL:EXT:my_extension/Resources/Private/Language/my_locallang.xlf:myKey"
    />
</f:format.html>
Copied!
packages/my_extension/Resources/Private/Language/locallang.xlf
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
	<file source-language="en" datatype="plaintext"
		original="EXT:my_extension/Resources/Private/Language/locallang.xlf"
		date="2020-10-18T18:20:51Z" product-name="my_extension"
	>
		<header />
		<body>
			<trans-unit id="myKey">
				<source>
                    <![CDATA[By default, ordered and unordered lists are formatted
                    with bullets and decimals. <br>
                    By adding <code>class="list-unstyled"</code> to the ol or ul tag, it
                    is possible to structure content in list form without the
                    typical list styling.]]>
				</source>
			</trans-unit>
		</body>
	</file>
</xliff>
Copied!

The entry in the .xlf language file must be surrounded by <![CDATA[...]]>.

Displaying translated labels with placeholders

<f:translate
    key="LLL:EXT:my_extension/Resources/Private/Language/locallang.xlf:domain_model.title"
    arguments="{0: '{myVariable}'}"
/>

Or with several numbered placeholders:

<f:translate
    key="LLL:EXT:my_extension/Resources/Private/Language/locallang.xlf:domain_model.title"
    arguments="{1: '{myVariable}', 2: 'Some String'}"
/>
Copied!
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
	<file source-language="en" datatype="plaintext"
		original="EXT:my_extension/Resources/Private/Language/locallang.xlf"
		date="2020-10-18T18:20:51Z" product-name="my_extension"
	>
		<header />
		<body>
			<label index="domain_model.title">Title of: %s</label>
			<trans-unit id="domain_model.description">
				<source>Some text about a %1$s and a %2$s.</source>
			</trans-unit>
		</body>
	</file>
</xliff>
Copied!

The placeholder %s is used to insert dynamic values, passed as the parameter arguments to the translate ViewHelper. If %s appears multiple times, it references subsequent array entries in order.

To avoid dependency on order, use indexed placeholders like %1$s. This explicitly refers to the first value and ensures that it is treated as a string ($s). This method is based on PHP’s vsprintf function <https://www.php.net/manual/en/function.vsprintf.php>, which allows for more flexible and readable formatting.

Inline notation with arguments and default value

Like all other ViewHelpers, the translate ViewHelper can be used with the Inline syntax.

{f:translate(key: 'someKey', arguments: {0: 'dog', 1: 'fox'}, default: 'default value')}
Copied!

This is especially useful if you want to pass the translated label to another ViewHelper, for example, as the alt parameter of an image:

<f:image src="EXT:my_extension/Resources/Public/icons/Edit.svg"
    alt="{f:translate(key: 'icons.edit', default: 'Edit')}"
/>
Copied!

The translation ViewHelper in console/CLI context

The translation ViewHelper determines the target language based on the current frontend or backend request.

If you are rendering your template from a console/CLI context, for example, when you Send emails with FluidEmail, use the argument languageKey to specify the desired language for the ViewHelper:

Salutation in Danish:
<f:translate
    key="LLL:EXT:my_extension/Resources/Private/Language/my_locallang.xlf:salutation"
    languageKey="da"
/>

Salutation in English:
<f:translate
    key="LLL:EXT:my_extension/Resources/Private/Language/my_locallang.xlf:salutation"
    languageKey="default"
/>
Copied!

Arguments of the f:translate ViewHelper

arguments

arguments
Type
array
Arguments to be replaced in the resulting string

default

default
Type
string
If the given locallang key could not be found, this value is used. If this argument is not set, child nodes will be used to render the default

extensionName

extensionName
Type
string
UpperCamelCased extension key (for example BlogExample)

id

id
Type
string
Translation ID. Same as key.

key

key
Type
string
Translation Key

languageKey

languageKey
Type
string
Language key ("da" for example) or "default" to use. Also a Locale object is possible. If empty, use current locale from the request.

Variable ViewHelper <f:variable>

Variable assigning ViewHelper

Assigns one template variable which will exist also after the ViewHelper is done rendering, i.e. adds template variables.

If you require a variable assignment which does not exist in the template after a piece of Fluid code is rendered, consider using f:alias ViewHelper instead.

Usages:

{f:variable(name: 'myvariable', value: 'some value')}
<f:variable name="myvariable">some value</f:variable>
{oldvariable -> f:format.htmlspecialchars() -> f:variable(name: 'newvariable')}
<f:variable name="myvariable"><f:format.htmlspecialchars>{oldvariable}</f:format.htmlspecialchars></f:variable>
Copied!

Go to the source code of this ViewHelper: VariableViewHelper.php (GitHub).

Arguments

The following arguments are available for the variable ViewHelper:

name

name
Type
string
Required
1
Name of variable to create

value

value
Type
mixed
Value to assign. If not in arguments then taken from tag content

Mfa.ifHasState ViewHelper <be:mfa.ifHasState>

ViewHelper to check if the given provider for the current user has the requested state set.

  <be:mfa.ifHasState state="active" provider="{provider}">
      ...
  </be:mfa.ifHasState>
Copied!

Go to the source code of this ViewHelper: Mfa\IfHasStateViewHelper.php (GitHub).

Arguments

The following arguments are available for the mfa.ifHasState ViewHelper:

else

else
Type
mixed
Value to be returned if the condition if not met.

provider

provider
Type
TYPO3\CMS\Core\Authentication\Mfa\MfaProviderManifestInterface
Required
1
The provider in question

state

state
Type
string
Required
1
The state to check for (e.g. active or locked)

then

then
Type
mixed
Value to be returned if the condition if met.

Toolbar.attributes ViewHelper <be:toolbar.attributes>

ViewHelper to build a "class" attribute string for use in rendered toolbar items.

 <be:toolbar.attributes class="{someToolbarItemInterfaceInstance}" />
Copied!

Go to the source code of this ViewHelper: Toolbar\AttributesViewHelper.php (GitHub).

Arguments

The following arguments are available for the toolbar.attributes ViewHelper:

class

class
Type
TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface
Required
1
Class being converted to a string for usage as id attribute

Toolbar.ifHasDropdown ViewHelper <be:toolbar.ifHasDropdown>

ViewHelper condition to checks whether a toolbar item provides a dropdown menu.

 <be:toolbar.ifHasDropdown class="{toolbarItem}">
     <f:then>...</f:then>
     <f:else>...</f:else>
 </be:toolbar.ifHasDropdown>
Copied!

Go to the source code of this ViewHelper: Toolbar\IfHasDropdownViewHelper.php (GitHub).

Arguments

The following arguments are available for the toolbar.ifHasDropdown ViewHelper:

class

class
Type
TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface
Required
1
The toolbar item class to be checked for providing a drop down

else

else
Type
mixed
Value to be returned if the condition if not met.

then

then
Type
mixed
Value to be returned if the condition if met.

TypoScript.fineDiff ViewHelper <be:typoScript.fineDiff>

ViewHelper to runs two strings through 'FineDiff' on word level.

  <backend:typoScript.fineDiff from="{someTextChunkBefore}" to="{someTextChunkAfter}" />
Copied!

Go to the source code of this ViewHelper: TypoScript\FineDiffViewHelper.php (GitHub).

Arguments

The following arguments are available for the typoScript.fineDiff ViewHelper:

from

from
Type
string
Default
''
Required
1
Source string

to

to
Type
string
Default
''
Required
1
Target string

Uri.editRecord ViewHelper <be:uri.editRecord>

ViewHelper to provide edit links (only the URI) to records. The ViewHelper will pass the uid and table to FormEngine.

The uid must be given as a positive integer. For new records, use <be:uri.newRecord>.

   <be:uri.editRecord uid="42" table="pages" fields="title,subtitle" returnUrl="foo/bar" />
Copied!

Go to the source code of this ViewHelper: Uri\EditRecordViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.editRecord ViewHelper:

fields

fields
Type
string
Edit only these fields (comma separated list)

returnUrl

returnUrl
Type
string
Default
''
return to this URL after closing the edit dialog

table

table
Type
string
Required
1
target database table

uid

uid
Type
int
Required
1
uid of record to be edited, 0 for creation

Uri.newRecord ViewHelper <be:uri.newRecord>

ViewHelper to provide 'create new record' links. The ViewHelper will pass the command to FormEngine.

The pid argument will put the new record on this page, if 0 given it will be placed to the root page.

The uid argument accepts only negative values. If this is given, the new record will be placed (by sorting field) behind the record with the uid. It will end up on the same pid as this given record, so the pid must not be given explicitly by pid argument.

An exception will be thrown, if both uid and pid are given. An exception will be thrown, if the uid argument is not a negative integer.

   <be:uri.newRecord table="a_table" returnUrl="foo/bar" uid="-17"/>
   <be:uri.newRecord table="a_table" returnUrl="foo/bar" pid="17"/>
Copied!

Go to the source code of this ViewHelper: Uri\NewRecordViewHelper.php (GitHub).

Arguments

The following arguments are available for the uri.newRecord ViewHelper:

defaultValues

defaultValues
Type
array
Default
array ( )
default values for fields of the new record

pid

pid
Type
int
the page id where the record will be created

returnUrl

returnUrl
Type
string
Default
''
return to this URL after closing the edit dialog

table

table
Type
string
Required
1
target database table

uid

uid
Type
int
uid < 0 will insert the record after the given uid

Avatar ViewHelper <be:avatar>

ViewHelper to render the avatar markup (including the <img> tag) for a given backend user. If the given backend user hasn't added a custom avatar yet, a default one is used.

   <be:avatar backendUser="{user.uid}" size="32" showIcon="true" />
Copied!

Go to the source code of this ViewHelper: AvatarViewHelper.php (GitHub).

Arguments

The following arguments are available for the avatar ViewHelper:

backendUser

backendUser
Type
int
Default
0
uid of the backend user

showIcon

showIcon
Type
bool
Default
false
show the record icon as well

size

size
Type
int
Default
32
width and height of the image

LanguageColumn ViewHelper <be:languageColumn>

ViewHelper to render a language column in a backend table module.

  <be:languageColumn languageColumn="{someColumn}" columnNumber="{colPos}" />
Copied!

Go to the source code of this ViewHelper: LanguageColumnViewHelper.php (GitHub).

Arguments

The following arguments are available for the languageColumn ViewHelper:

columnNumber

columnNumber
Type
int
Required
1
Number (colPos) of column within LanguageColumn to be returned

languageColumn

languageColumn
Type
TYPO3\CMS\Backend\View\BackendLayout\Grid\LanguageColumn
Required
1
Language column object which is context for column

Thumbnail ViewHelper <be:thumbnail>

ViewHelper for the backend which generates an <img> tag with the special URI to render thumbnails deferred.

   <be:thumbnail image="{file.resource}" width="{thumbnail.width}" height="{thumbnail.height}" />
Copied!

Go to the source code of this ViewHelper: ThumbnailViewHelper.php (GitHub).

Arguments

The following arguments are available for the thumbnail ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

context

context
Type
string
Default
'Image.Preview'
context for image rendering

crop

crop
Type
string|bool
overrule cropping of image (setting to FALSE disables the cropping set in FileReference)

cropVariant

cropVariant
Type
string
Default
'default'
select a cropping variant, in case multiple croppings have been specified or stored in FileReference

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

height

height
Type
string
height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.

image

image
Type
object
a FAL object (\TYPO3\CMS\Core\Resource\File or \TYPO3\CMS\Core\Resource\FileReference)

maxHeight

maxHeight
Type
int
maximum height of the image

maxWidth

maxWidth
Type
int
maximum width of the image

minHeight

minHeight
Type
int
minimum height of the image

minWidth

minWidth
Type
int
minimum width of the image

src

src
Type
string
Default
''
a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead

treatIdAsReference

treatIdAsReference
Type
bool
Default
false
given src argument is a sys_file_reference record

width

width
Type
string
width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.

Icon ViewHelper <core:icon>

ViewHelper to display an icon identified by its icon identifier.

   <core:icon title="Open actions menu" identifier="actions-menu" />
Copied!

Go to the source code of this ViewHelper: IconViewHelper.php (GitHub).

Arguments

The following arguments are available for the icon ViewHelper:

alternativeMarkupIdentifier

alternativeMarkupIdentifier
Type
string
Alternative icon identifier. Takes precedence over the identifier if supported by the IconProvider.

identifier

identifier
Type
string
Required
1
Identifier of the icon as registered in the Icon Registry.

overlay

overlay
Type
string
Identifier of an overlay icon as registered in the Icon Registry.

size

size
Type
string
Default
'small'
Desired size of the icon. All values of the IconSize enum are allowed, these are: "small", "default", "medium", "large" and "mega".

state

state
Type
string
Default
'default'
Sets the state of the icon. All values of the Icons.states enum are allowed, these are: "default" and "disabled".

title

title
Type
string
Title for the icon

IconForRecord ViewHelper <core:iconForRecord>

ViewHelper to display an icon for a record.

   <core:iconForRecord table="tt_content" row="{record}" />
Copied!

Go to the source code of this ViewHelper: IconForRecordViewHelper.php (GitHub).

Arguments

The following arguments are available for the iconForRecord ViewHelper:

alternativeMarkupIdentifier

alternativeMarkupIdentifier
Type
string
alternative markup identifier

row

row
Type
array
Required
1
the record row

size

size
Type
string
Default
'small'
the icon size

table

table
Type
string
Required
1
the table for the record icon

IconForResource ViewHelper <core:iconForResource>

ViewHelper to displays an icon for a FAL resource (file or folder means a TYPO3\CMS\Core\Resource\ResourceInterface).

   <core:iconForResource resource="{file.resource}" />
Copied!

Go to the source code of this ViewHelper: IconForResourceViewHelper.php (GitHub).

Arguments

The following arguments are available for the iconForResource ViewHelper:

alternativeMarkupIdentifier

alternativeMarkupIdentifier
Type
string
Alternative markup identifier

options

options
Type
array
Default
array ( )
An associative array with additional options

overlay

overlay
Type
string
Overlay identifier

resource

resource
Type
TYPO3\CMS\Core\Resource\ResourceInterface
Required
1
Resource

size

size
Type
string
Default
'small'
The icon size

NormalizedUrl ViewHelper <core:normalizedUrl>

ViewHelper to normalize a path that uses EXT: syntax or an absolute URL to an absolute web path.

   <core:normalizedUrl pathOrUrl="https://foo.bar/img.jpg" />
   <core:normalizedUrl pathOrUrl="EXT:core/Resources/Public/Images/typo3_black.svg" />
Copied!

Go to the source code of this ViewHelper: NormalizedUrlViewHelper.php (GitHub).

Arguments

The following arguments are available for the normalizedUrl ViewHelper:

pathOrUrl

pathOrUrl
Type
string
Absolute path to file using EXT: syntax or URL.

Be.maximumFileSize ViewHelper <formvh:be.maximumFileSize>

Return the max file size for use in the form editor

Scope: backend

Go to the source code of this ViewHelper: Be\MaximumFileSizeViewHelper.php (GitHub).

Be.renderContentElementPreview ViewHelper <formvh:be.renderContentElementPreview>

Used by the form editor. Render a content element preview like the page module

Scope: backend

Go to the source code of this ViewHelper: Be\RenderContentElementPreviewViewHelper.php (GitHub).

Arguments

The following arguments are available for the be.renderContentElementPreview ViewHelper:

contentElementUid

contentElementUid
Type
int
The uid of a content element

Form.datePicker ViewHelper <formvh:form.datePicker>

Display a jQuery date picker.

Note: Requires jQuery UI to be included on the page.

Scope: frontend

Go to the source code of this ViewHelper: Form\DatePickerViewHelper.php (GitHub).

Arguments

The following arguments are available for the form.datePicker ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

dateFormat

dateFormat
Type
string
Default
'Y-m-d'
The date format

datePickerInitializationJavaScriptFile

datePickerInitializationJavaScriptFile
Type
string
Default
'EXT:form/Resources/Public/JavaScript/frontend/date-picker.js'
The JavaScript file to initialize the date picker

enableDatePicker

enableDatePicker
Type
bool
Default
true
Enable the Datepicker

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

initialDate

initialDate
Type
string
Initial date (@see http://www.php.net/manual/en/datetime.formats.php for supported formats)

name

name
Type
string
Name of input tag

previewMode

previewMode
Type
bool
Default
false
Required
1
Preview mde flag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
mixed
Value of input tag

Form.timePicker ViewHelper <formvh:form.timePicker>

Displays two select-boxes for hour and minute selection.

Scope: frontend

Go to the source code of this ViewHelper: Form\TimePickerViewHelper.php (GitHub).

Arguments

The following arguments are available for the form.timePicker ViewHelper:

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

initialDate

initialDate
Type
string
Initial time (@see http://www.php.net/manual/en/datetime.formats.php for supported formats)

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

timeType

timeType
Type
string
"hour" or "minute"

value

value
Type
mixed
Value of input tag

Form.uploadedResource ViewHelper <formvh:form.uploadedResource>

This ViewHelper makes the specified Image object available for its childNodes. In case the form is redisplayed because of validation errors, a previously uploaded image will be correctly used.

Scope: frontend

Go to the source code of this ViewHelper: Form\UploadedResourceViewHelper.php (GitHub).

Arguments

The following arguments are available for the form.uploadedResource ViewHelper:

accept

accept
Type
array
Default
array ( )
Values for the accept attribute

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

as

as
Type
string

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

errorClass

errorClass
Type
string
Default
'f3-form-error'
CSS class to set if there are errors for this ViewHelper

name

name
Type
string
Name of input tag

property

property
Type
string
Name of Object Property. If used in conjunction with <f:form object="...">, the "name" property will be ignored, while "value" can be used to specify a default field value instead of the object property value.

value

value
Type
mixed
Value of input tag

Form ViewHelper <formvh:form>

Custom form ViewHelper that renders the form state instead of referrer fields

Scope: frontend

Go to the source code of this ViewHelper: FormViewHelper.php (GitHub).

Arguments

The following arguments are available for the form ViewHelper:

absolute

absolute
Type
bool
Default
false
If set, an absolute action URI is rendered (only active if $actionUri is not set)

action

action
Type
string
Target action

actionUri

actionUri
Type
string
can be used to overwrite the "action" attribute of the form tag

addQueryString

addQueryString
Type
string
Default
false
If set, the current query parameters will be kept in the URL. If set to "untrusted", then ALL query parameters will be added. Be aware, that this might lead to problems when the generated link is cached.

additionalAttributes

additionalAttributes
Type
array
Additional tag attributes. They will be added directly to the resulting HTML tag.

additionalParams

additionalParams
Type
array
Default
array ( )
additional action URI query parameters that won't be prefixed like $arguments (overrule $arguments) (only active if $actionUri is not set)

arguments

arguments
Type
array
Default
array ( )
Arguments (do not use reserved keywords "action", "controller" or "format" if not referring to these internal variables specifically)

argumentsToBeExcludedFromQueryString

argumentsToBeExcludedFromQueryString
Type
array
Default
array ( )
arguments to be removed from the action URI. Only active if $addQueryString = TRUE and $actionUri is not set

aria

aria
Type
array
Additional aria-* attributes. They will each be added with a "aria-" prefix.

controller

controller
Type
string
Target controller

data

data
Type
array
Additional data-* attributes. They will each be added with a "data-" prefix.

extensionName

extensionName
Type
string
Target Extension Name (without `tx_` prefix and no underscores). If NULL the current extension name is used

fieldNamePrefix

fieldNamePrefix
Type
string
Prefix that will be added to all field names within this form. If not set the prefix will be tx_yourExtension_plugin

format

format
Type
string
Default
''
The requested format (e.g. ".html") of the target page (only active if $actionUri is not set)

hiddenFieldClassName

hiddenFieldClassName
Type
string
hiddenFieldClassName

method

method
Type
string
Default
'post'
Transfer type (get or post)

name

name
Type
string
Name of form

noCache

noCache
Type
bool
Default
false
set this to disable caching for the target page. You should not need this.

novalidate

novalidate
Type
bool
Indicate that the form is not to be validated on submit.

object

object
Type
mixed
Object to use for the form. Use in conjunction with the "property" attribute on the sub tags

objectName

objectName
Type
string
name of the object that is bound to this form. If this argument is not specified, the name attribute of this form is used to determine the FormObjectName

pageType

pageType
Type
int
Default
0
Target page type

pageUid

pageUid
Type
int
Target page uid

pluginName

pluginName
Type
string
Target plugin. If empty, the current plugin name is used

requestToken

requestToken
Type
mixed
whether to add that request token to the form

section

section
Type
string
Default
''
The anchor to be added to the action URI (only active if $actionUri is not set)

signingType

signingType
Type
string
which signing type to be used on the request token (falls back to "nonce")

GridColumnClassAutoConfiguration ViewHelper <formvh:gridColumnClassAutoConfiguration>

Scope: frontend

Go to the source code of this ViewHelper: GridColumnClassAutoConfigurationViewHelper.php (GitHub).

Arguments

The following arguments are available for the gridColumnClassAutoConfiguration ViewHelper:

element

element
Type
TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface
Required
1
A RootRenderableInterface instance

Render ViewHelper <formvh:render>

Main Entry Point to render a Form into a Fluid Template

Usage

Default:

{namespace formvh=TYPO3\CMS\Form\ViewHelpers}
<formvh:render factoryClass="NameOfYourCustomFactoryClass" />
Copied!

The factory class must implement \TYPO3\CMS\Form\Domain\Factory\FormFactoryInterface .

Scope: frontend

Go to the source code of this ViewHelper: RenderViewHelper.php (GitHub).

Arguments

The following arguments are available for the render ViewHelper:

factoryClass

factoryClass
Type
string
Default
'TYPO3\\CMS\\Form\\Domain\\Factory\\ArrayFormFactory'
The fully qualified class name of the factory

overrideConfiguration

overrideConfiguration
Type
array
Default
array ( )
factory specific configuration

persistenceIdentifier

persistenceIdentifier
Type
string
The persistence identifier for the form.

prototypeName

prototypeName
Type
string
Name of the prototype to use

RenderAllFormValues ViewHelper <formvh:renderAllFormValues>

Renders the values of a form

Scope: frontend

Go to the source code of this ViewHelper: RenderAllFormValuesViewHelper.php (GitHub).

Arguments

The following arguments are available for the renderAllFormValues ViewHelper:

as

as
Type
string
Default
'formValue'
The name within the template

renderable

renderable
Type
TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface
Required
1
A RootRenderableInterface instance

RenderFormValue ViewHelper <formvh:renderFormValue>

Renders a single value of a form

Scope: frontend

Go to the source code of this ViewHelper: RenderFormValueViewHelper.php (GitHub).

Arguments

The following arguments are available for the renderFormValue ViewHelper:

as

as
Type
string
Default
'formValue'
The name within the template

renderable

renderable
Type
TYPO3\CMS\Form\Domain\Model\Renderable\RenderableInterface
Required
1
A renderable element

RenderRenderable ViewHelper <formvh:renderRenderable>

Render a renderable.

Set the renderable into the TYPO3CMSFormMvcViewFormView and return the rendered content.

Scope: frontend

Go to the source code of this ViewHelper: RenderRenderableViewHelper.php (GitHub).

Arguments

The following arguments are available for the renderRenderable ViewHelper:

renderable

renderable
Type
TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface
Required
1
A RenderableInterface instance

TranslateElementError ViewHelper <formvh:translateElementError>

Translate form element properties.

Scope: frontend / backend

Go to the source code of this ViewHelper: TranslateElementErrorViewHelper.php (GitHub).

Arguments

The following arguments are available for the translateElementError ViewHelper:

element

element
Type
TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface
Required
1
Form Element to translate

error

error
Type
TYPO3\CMS\Extbase\Error\Error
Required
1
Error

TranslateElementProperty ViewHelper <formvh:translateElementProperty>

Translate form element properties.

Scope: frontend / backend

Go to the source code of this ViewHelper: TranslateElementPropertyViewHelper.php (GitHub).

Arguments

The following arguments are available for the translateElementProperty ViewHelper:

element

element
Type
TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface
Required
1
Form Element to translate

property

property
Type
mixed
Property to translate

renderingOptionProperty

renderingOptionProperty
Type
mixed
Property to translate

Contribution

Unlike most official TYPO3 documentation, this manual does not support the popular Edit on GitHub workflow for manual contributions, as these documentation files are automatically generated from the ViewHelper source files - and overwritten on each generation run.

Therefore, contribute to this documentation by editing the appropriate source files at

  1. https://github.com/TYPO3/typo3/tree/main/typo3/sysext/core/Classes/ViewHelpers
  2. https://github.com/TYPO3/typo3/tree/main/typo3/sysext/backend/Classes/ViewHelpers
  3. https://github.com/TYPO3/typo3/tree/main/typo3/sysext/fluid/Classes/ViewHelpers
  4. https://github.com/TYPO3/Fluid/tree/main/src/ViewHelpers

For example, adding a new code sample to the format.number page at

is done by editing the class comment in

To enrich the comment text you can use the common directives of the reST markup language supported by the TYPO3 documentation rendering toolchain.

Sitemap