Here is a way to allow you to extend Symfony 2 Form using tagged Service. I think it's the correct way but not yet documented on the book. Symfony 2 is still brand new and the document is not completed yet, I found out this solution while diving into Symfony Form component :(
Well, the code is quite simple. You need to create a service tagged with form.type_extension with alias value is the type of Form element you want to override. Then make the service inherits from Symfony\Component\Form\AbstractTypeExtension, implement the getExtendedType method to return the same value with alias and then override the buildForm method to do whatever you want with the Form. Here is an example to illustrate how to add more field to a form
services.yml
services:
demo.form_extension:
class: Demo\MyBundle\Form\Extension\MyFormExtension
tags:
- {name: form.type_extension, alias: form}
FormExtension.php
namespace Demo\MyBundle\Form\Extension;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\AbstractTypeExtension;
class MyFormExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilder $builder, array $options)
{
// TODO: add some check for the form you want to use here
$data = $options['data'];
// extend the form here, you can also use custom validator
$builder->add('new_item', 'text');
$builder->addEventListener(FormEvents::POST_BIND, function($event) {
$form = $event->getForm();
// do whatever you want here, such as additional data binding
});
}
public function getExtendedType()
{
return 'form';
}
}
Note: Symfony 2 also has form.extension, you can use it to load form type or extension by PHP. Check Symfony/Component/Form/Extension/Csrf namespace for example.
Add new comment