在 Symfony2 中,如何从 FormBuilder 获取标签 [英] In Symfony2, how do I get labels from the FormBuilder

查看:27
本文介绍了在 Symfony2 中,如何从 FormBuilder 获取标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Symfony2 中,我使用的是 formbuilder.我正在根据文档在表单中设置标签.

In Symfony2, I'm using formbuilder. I'm setting the labels in the form, as per the documentation.

但是,当我在显示"和索引"页面上时,我必须将标签复制到 Twig 中.

However, when I'm on the 'show' and 'index' pages, I have to copy the labels into Twig.

有没有办法在所有地方都使用相同的标签?我想到的选项:

Is there a way to have the same labels used everywhere? The options I have thought of:

  • 访问表单构建器配置,但不实际构建表单
  • 有一个中央配置文件,并从表单构建器和树枝文件中查找到该文件

然而,无论哪种方式都需要我做"一些我在 Symfony 中不习惯的事情.这似乎是已经解决的问题,但我不确定如何解决.

However, either way requires me to 'do' something, which I'm not used to in Symfony. It seems like this is something that would already have been solved, but I'm not sure how.

推荐答案

您可以利用翻译系统来解决这个问题.确保您在 config.yml 中启用了翻译.

You can utilize translation system to overcome this problem. Make sure that you have enabled translation in config.yml.

如果您在表单类型中添加了这样的字段

If you have added field in your formtype like this

$builder->add('title', 'text', array(
    'label'=> 'model.title'
));
//.....

在您的 bundles Resources/translations 目录中创建一个名为 messages.en.yml 的文件(将 en 替换为您的默认语言环境并创建多个文件基于区域设置.检查translation 书的章节.)并输入以下内容

Create a file named messages.en.yml in your bundles Resources/translations directory (replace en with your default locale and create multiple files based on the locales. Check translation chapter of the book.) and put following

#src/YourBundle/Resources/translation/messages.en.yml
model:
    title: "Title"
    field: "Field"
    #....

添加和编辑表单标签将显示Title.在索引和显示页面中,您可以执行

Add and edit forms label will show Title. In index and show pages you can do

{{ "model.title" | trans([], 'messages') }}

虽然这个过程有点冗长,但它是一次,您可以通过更改翻译文件来更改标签的值.

Though this process is a bit lengthy but it is one time and you can change the value of the labels by changing the translation files.

这篇关于在 Symfony2 中,如何从 FormBuilder 获取标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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