一个属性的多个字段 [英] Multiple fields for one attribute
问题描述
$ form-> bind()
用户的请求,Symfony会尝试寻找 - > setMonth()
我如何告诉Symfony我想通过来运行输入, strtotime()
(或任何其他任何其他任意代码或方法)之前,然后将新输出映射到 setDate()
?
解决方案首先,您需要告诉symfony这些字段没有相应的Entity属性。这是通过'property_path'选项完成的。
$ builder-> add(field1,text ,数组(
property_path=> false
));
在您的控制器中,一旦您检查了表单是有效的并且在坚持实体之前可以获得这些字段的值使用如下所示:
$ field1 = $ form-> get('field1') - >的getData();
,然后根据需要使用这些值构造您的实体属性,例如:
$ entity-> setWhatever($ field1。$ field2。$ field3);
如果您需要对这些字段进行某种验证,最好的选择是编写一个回调函数验证器。
Say I have three fields for a user to enter a date: day, month, and year. (Likely not the best way, but I'm using it for this example). If I try to $form->bind()
the user's request, Symfony will try and look for a ->setMonth()
method on my model, which doesn't exist.
How do I tell Symfony that I want to run the input through strtotime()
(or any other any other arbitrary code or method) before, and then map the new output to setDate()
?
解决方案 First of all, you need to tell symfony that these fields do not have a corresponding Entity property. This is done with the 'property_path' option doing something like this
$builder->add("field1", "text", array(
"property_path" => false
));
In your controller, once you have checked that the form is valid and before persisting the entity you can get the values of these fields using something like:
$field1 = $form->get('field1')->getData();
and then use these values to construct your entity property as you need, for example:
$entity->setWhatever($field1.$field2.$field3);
If you need to do some sort of validation on these fields, your best option is to write a callback validator.
这篇关于一个属性的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!