Can I dynamically add a field to a FormType?

I have a PostType form that extends AbstractType. In the controller, I would like to add a field to it if a certain condition is met. Can I do it somehow or is there another best practice for modifying FormTypes in controllers?

thank

+5
source share
4 answers

You can do this using form Events .

+5
source

Say you have a form like FileType , as shown below:

<?php
namespace EventFlowAnalyser\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class FileType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', 'text', array('label' => 'Name'));
    }

    public function getName()
    {
        return 'file';
    }
}

You can use it in your controller as follows:

$form = $this->createForm(new FileType(), $document);

$document - , (). , , FileType, ; , , , original_name.

<?php
namespace EventFlowAnalyser\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

use EventFlowAnalyser\Form\EventListener\EditFileFieldSubscriber;

class FileEditType extends FileType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add('original_name', 'hidden', array('mapped' => false));
    }
}

:

$form = $this->createForm(new FileEditType(), $document);

:

$form->get('original_name')->setData($document->name);

, somenone: o)

+7

, , Collection . . , .

Link1: Symfony2

2: symfony2

, . .

+4

, . , M (V) C.

+2

All Articles