With the text field type in Symfony there is a trim option. I’m pretty sure that the trim() operation is carried by the Form\Extension\Core\EventListener\TrimListener class. It’s a listener for the PRE_BIND event and calls:
$event->setData(trim($event->getData()));
I’d like to provide my own "normalize_spaces" option:
$builder->add('last_name', 'text', array(
'label' => 'Last name',
'normlize_spaces' => true
));
How can i provide this option with my NormalizeSpacesListener?
class NormalizeSpacesListener implements EventSubscriberInterface
{
public function preBind(FormEvent $event)
{
$data = $event->getData();
if (is_string($data)) {
$event->setData(preg_replace('/[ ]{2,}/', ' ', $data));
}
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
}
I think you would probably override Symfony core FormType Class, especially the buildForm method:
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Core/Type/FormType.php
and add your test for that option just like they do it for the trim option. Something like:
To override that class and have the system use it instead of the default core one, you can use the service container and change the class for the service form.type.form
See how its declared here: https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Resources/config/form.xml
And read this to understand how to actually tell the service container to use your own class instead of the default one:
How to Override any Part of a Bundle
Note: That’s how I would try to do it but I have not tested what I just wrote
Another option would be to attach your listener to each form you build, and not make it a default option. I think that would work as well.