Home » Php » php – How to dynamically build a form based on TreeBuilder object?

php – How to dynamically build a form based on TreeBuilder object?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to define configuration schema for my class and override them with admin choices.
In order to do this I need a form to capture data from admin.

In Symfony Configuration Component, the TreeBuilder class is responsible for defining configuration schema. and as you know Form Component has tree like structure similar to TreeBuilder.

How can dynamically make a Form object based on TreeBuilder instance?

How to&Answers:

Your treebuilder, or a part of it, will have to be iterable. So by letting it represent a form as strict as possible you can use it to easily map the configuration to the builder. It would be easiest to use the yml format:

form:
    name: 'exampleForm'
    path: 'target_path'
    fields:
        fieldName:
            type: 'TextType'
            attr:
                # some additional options
        otherFieldName:
            type: 'TextType'
            attr:
                # some additional options

See the processing section of the config component for more info: http://symfony.com/doc/current/components/config/definition.html#processing-configuration-values

The processed configuration then could be handled with the form factory and would probably look like this:

$config = $configuration->processConfiguration($config, FormType::class, null, $config['path']);
$formBuilder = $container->get('form.factory')->createNamedBuilder($config['name');

foreach ($config['fields'] as $field) {
    $formBuilder->add($fieldName, $field['type'], $field['attr']);
}
$form = $formBuilder->createForm();