Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically add a field to FormType form?

Tags:

symfony

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

Thanks

like image 832
DavidW Avatar asked Feb 18 '12 00:02

DavidW


2 Answers

Let say you have a Form of type FileType as follow:

<?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 like this:

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

Where $document is an object containing one field (name). Now, if you need to add a field to the form object in another function, you can extend the FileType to add the field you need; for example if you want to edit the name field but want still to keep track of the previous state lets add an original_name field.

<?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));
    }
}

Now, you can use the extended form like that:

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

And modify the value of the field like that:

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

I hope this will help somenone :o)

like image 94
Alexandre Mélard Avatar answered Sep 28 '22 01:09

Alexandre Mélard


You can do it by using Form Events.

like image 29
Mun Mun Das Avatar answered Sep 28 '22 02:09

Mun Mun Das