symfony2 文本字段自定义标签
我在使用 symfony2 Field 组件时遇到了一些但令人不快的问题。例如,我想在树枝模板中输出表单字段数组:
{% for field in form %}
{{ form_label( field ) }}: {{ form_field( field ) }}
{% endfor %}
这是文本字段配置:
$field = new TextField( 'FieldName', array(
'label' => 'MyCustomLabel',
) );
但不幸的是,当引擎呈现此输出时,我得到“FieldName”作为标签而不是“MyCustomLabel”。如果我输出的表单字段不在 for 中,我不会有问题(在这种情况下,我可以在模板中为每个字段添加一个标签)。但脚本在执行之前并不知道表单字段的具体数量和配置。所以,我需要实现场渲染的循环方法。我也想保留树枝符号......我会很高兴得到一个好的建议:)
I had a little but unpleasant problem with symfony2 Field component. For example, I would like to output array of form fields in twig template:
{% for field in form %}
{{ form_label( field ) }}: {{ form_field( field ) }}
{% endfor %}
And here is text field configuration:
$field = new TextField( 'FieldName', array(
'label' => 'MyCustomLabel',
) );
But unfortunately when engine renders this output i get 'FieldName' as label instead of 'MyCustomLabel'. I would not have problems if i outputting form fields not in for (in that case i can just add a label in template for each field). But the script doesn't know certain quantity and configuration of form fields before execution. So, I need to implement cycle method for field rendering. And I also want to stay in twig notation...I will be pleased for a good advise :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您想更改标签,请按照以下步骤操作。
1)创建表单类。
2)
add('fieldName',null,array('label' => 'My New Label:'))
请不要更改 fieldName,但您可以在数组中使用 Label。
享受!
If you want to change the label, than follow the steps.
1) Create form class.
2)
add('fieldName',null,array('label' => 'My New Label:'))
please do not change fieldName, but you can play with Label within an array.
Enjoy!
在模板中执行此操作的最简单方法 - 将第二个参数传递给
form_label
The easiest way to do it in template - pass the second argument to the
form_label
对于那些偶然发现这个问题并希望得到答案的 Symfony 2.1 用户来说,这几乎就是 @rikinadhyapak 的答案。
如果您在 buildForm 方法中扩展了某些包(如 FOSUserBundle)的 FormType 类:
An answer for the Symfony 2.1 users who stumble onto this hoping for an answer, it's almost there is the @rikinadhyapak answer.
if you have extended the FormType class of some bundle like FOSUserBundle, in your buildForm method:
老实说,我会推迟几周学习 Symfony Form 组件。 Symfony 开发人员正在对 Form API 进行重大修改。据我了解,大部分工作已经完成,并且 拉取请求已提交到主存储库< /a>.
I would honestly hold off on learning the Symfony Form component for a couple weeks. Symfony devs are doing a major-overhaul on the Form API. From what I understand, most of it is done, and a pull request has been submitted to the main repository.
对于 Symfony 2.3,您可以使用事件替换标签,如下所示:
但我会避免这种情况。
For Symfony 2.3 you can replace the label using the events as the following:
but I would avoid this.
它已添加到 Symfony2 beta2 http://groups.google.com/group /symfony-users/browse_frm/thread/c66165093665809
It is added in Symfony2 beta2 http://groups.google.com/group/symfony-users/browse_frm/thread/c66165093665809