Modify FlexForm fields

FlexForms can be used to store data within an XML structure inside a single DB column.

How to modify FlexForms from PHP

Sometimes it is necessary to modify FlexForms via PHP.

In order to convert a FlexForm to a PHP array while preserving the structure, use the xml2array method in GeneralUtility to read the FlexForm data, then FlexFormTools to write back the changes.

Changed in version 13.0

\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools is now a stateless service and can be injected via Dependency injection. FlexFormTools::flexArray2Xml() is now marked as internal.

EXT:my_extension/Classes/Service/FlexformModificationService.php
<?php

declare(strict_types=1);

namespace MyVendor\MyExtension\Service;

use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
use TYPO3\CMS\Core\Utility\GeneralUtility;

class _FlexformModificationService
{
    public function __construct(
        protected readonly FlexFormTools $flexFormTools,
    ) {}

    public function modifyFlexForm(string $flexFormString): string
    {
        $flexFormArray = GeneralUtility::xml2array($flexFormString);
        $changedFlexFormArray = $this->doSomething($flexFormArray);

        // Attention: flexArray2Xml is internal and subject to
        // be changed without notice. Use at your own risk!
        return $this->flexFormTools->flexArray2Xml($changedFlexFormArray, addPrologue: true);
    }

    private function doSomething(array $flexFormArray): array
    {
        // do something to the array
        return $flexFormArray;
    }
}
Copied!