Symfony form: customize the setter that is called

后端 未结 2 1584
死守一世寂寞
死守一世寂寞 2021-01-13 01:36

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,

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 02:06

    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.

提交回复
热议问题