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
General to read
the FlexForm data, then
Flex to write back the
changes.
\TYPO3\ is a stateless
service and can be injected via Dependency injection.
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;
}
}
Note
The method FlexFormTools::flexArray2Xml() is marked as internal and subject to unannounced changes. Use at your own risk.