Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony form: customize the setter that is called

I have a Symfony form custom type for an entity.

I want to customize the code that is executed when the form is submitted, but only for a field.

For example, Symfony will by default call this:

$entity->setFoo($value);

I want to do call instead something like:

$entity->doSomething($value, true);

How can I do that without affecting all other properties that are correctly mapped with the form?

like image 726
Matthieu Napoli Avatar asked Feb 27 '14 16:02

Matthieu Napoli


2 Answers

You can define your foo field in the form as not mapped and then add listener on the POST_SUBMIT that will call your doSomething() method:

$builder->add('foo', null, array('mapped' => false))
    ;

    $builder->addEventListener(
        FormEvents::POST_SUBMIT,
        function(FormEvent $event) {
            $entity = $event->getForm()->getData();
            $entity->doSomething($event->getForm()->get('foo')->getData(), true);
        }
    );

It will not call $entity->setFoo($value). Instead it will call $entity->doSomething($value, true) as you wished.

like image 145
Michael Sivolobov Avatar answered Oct 12 '22 10:10

Michael Sivolobov


Check this post about DataMapper (it starts from explaining Value Objects, but link will scroll down to Data Mappers header directly). It's very useful but missed in Symfony docs.

like image 35
Arkemlar Avatar answered Oct 12 '22 08:10

Arkemlar