In Symfony2, how do I get labels from the FormBuilder

故事扮演 提交于 2019-12-07 20:01:41

问题


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

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:

  • Access the formbuilder configuration, but without actually building the form
  • Have a central config file, and lookup from the formbuilder and the twig files into that file

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.


回答1:


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'
));
//.....

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"
    #....

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.



来源:https://stackoverflow.com/questions/10736979/in-symfony2-how-do-i-get-labels-from-the-formbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!