Search code examples
symfonysymfony-3.3

Symfony : strtolower in FORM EVENT


With Symfony 3.3, I want to strtolower all emails form.

I use this extension :

class EmailTypeExtension extends AbstractTypeExtension
{
    public function getExtendedType()
    {
        return EmailType::class;
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->addEventListener(
            FormEvents::POST_SUBMIT,
            [
                $this,
                'onPostSubmit'
            ]
        );
    }

    public function onPostSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();

        $form->setData(strtolower($data));
    }
}

But I have this error "You cannot change the data of a submitted form.". If I use "PRE_SUBMIT" or "SUBMIT" event, my data doesn't change :/

Can you help me ?


Solution

  • You can not modify your form using $form->setData() method.
    You have to modify the data of your FormEvent $event like this:

    public function onPostSubmit(FormEvent $event)
        {
            $data = $event->getData();
    
            // e.g. manipulate submitted data only if it is not empty
            if ($data["email"]) {
                $data["email"] = strtolower($data["email"]);
                $event->setData($data);
            }
        }