Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically build a form based on TreeBuilder object?

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?

like image 357
Lost Koder Avatar asked Sep 28 '16 13:09

Lost Koder


1 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();
like image 162
Rvanlaak Avatar answered Nov 04 '22 07:11

Rvanlaak