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
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)
You can do it by using Form Events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With