DavidW
DavidW

Reputation: 5129

Can I dynamically add a field to FormType form?

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

Upvotes: 7

Views: 32783

Answers (4)

Alexandre Mélard
Alexandre Mélard

Reputation: 12679

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)

Upvotes: 7

Mun Mun Das
Mun Mun Das

Reputation: 15002

You can do it by using Form Events.

Upvotes: 6

Asish AP
Asish AP

Reputation: 4441

Sure You can add fields dynamically using Collection Type in form. See the below link, this will helps you how to make fields dynamically.

Link1: Dynamic Field in Symfony2

Link2: Form Collection in symfony2 doc

Hope these two links helps you. Happy coding..

Upvotes: 5

greg0ire
greg0ire

Reputation: 23265

I think you should add a boolean option to your form, and set it in your controller. This way you would have a clean M(V)C separation.

Upvotes: 2

Related Questions