Reputation: 5129
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
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
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
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