如何将未绑定字段添加到 Symfony 中的表单,否则该字段绑定到实体? [英] How do I add an unbound field to a form in Symfony which is otherwise bound to an entity?

查看:19
本文介绍了如何将未绑定字段添加到 Symfony 中的表单,否则该字段绑定到实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我遗漏了显而易见的东西,但我如何(或者我可以)向 Symfony 表单添加一个额外的未绑定"字段,否则绑定到一个实体?

Maybe I'm missing the obvious but how do I (or can I) add an extra "unbound" field to a Symfony form that is otherwise bound to an entity?

假设我有一个包含字段 first_namelast_name 的实体.我在我的表单类 buildForm 方法中做典型的事情.

Let's say I have an entity with fields first_name and last_name. I do the typical thing in my form class buildForm method.

$builder
    ->add('first_name')
    ->add('last_name')
;

这在我的控制器中:

$editForm = $this->createForm(new MyType(), $entity);

这很好用,但我想添加另一个文本框,我们称之为额外",并在 POST 操作中接收值.如果我执行 $builder->add('extra')‍,它会抱怨

That works nicely but I'd like to add another text box, let's call it "extra", and receive the value in the POST action. If I do $builder->add('extra')‍, it complains that

PropertyAccessor.php 第 479 行中的 NoSuchPropertyException:

NoSuchPropertyException in PropertyAccessor.php line 479:

属性extra"和方法getExtra()"、extra()"、isExtra()"、hasExtra()"、__get()"都不存在并且在类中具有公共访问权限...

Neither the property "extra" nor one of the methods "getExtra()", "extra()", "isExtra()", "hasExtra()", "__get()" exist and have public access in class...

这是正确的.我只是想用它从用户那里收集一些额外的信息,并用它做一些事情,而不是将它存储在实体中.

Which is correct. I just want to use it to collect some extra info from the user and do something with it other than storing it with the entity.

我知道如何制作一个完全独立的表单,而不是一个混合"的表单.这可能吗?

I know how to make a completely standalone form but not one that's "mixed". Is this possible?

推荐答案

在您的表单中添加一个带有 false property_path 的文本字段:

In your form add a text field with a false property_path:

$builder->add('extra', 'text', array('property_path' => false));

然后您可以访问控制器中的数据:

You can then access the data in your controller:

$extra = $form->get('extra')->getData();

更新

自 Symfony 2.1 以来的新方法是使用 mapped 选项并将其设置为 false.

The new way since Symfony 2.1 is to use the mapped option and set that to false.

->add('extra', null, array('mapped' => false))

感谢 Henrik Bjørnskov 的更新信息(下方评论)

Credits for the update info to Henrik Bjørnskov ( comment below )

这篇关于如何将未绑定字段添加到 Symfony 中的表单,否则该字段绑定到实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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