Symfony 表单:自定义被调用的 setter [英] Symfony form: customize the setter that is called

查看:21
本文介绍了Symfony 表单:自定义被调用的 setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体的 Symfony 表单自定义类型.

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.

例如,Symfony 会默认调用:

For example, Symfony will by default call this:

$entity->setFoo($value);

我想做如下调用:

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

如何在不影响与表单正确映射的所有其他属性的情况下执行此操作?

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

推荐答案

您可以将表单中的 foo 字段定义为 not maps 然后在 not mapping 上添加监听器code>POST_SUBMIT 将调用您的 doSomething() 方法:

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);
        }
    );

它不会调用 $entity->setFoo($value).相反,它会按照您的意愿调用 $entity->doSomething($value, true).

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

这篇关于Symfony 表单:自定义被调用的 setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆