phpsymfonyformbuilder

In Symfony2, how do I get labels from the FormBuilder


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:

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.


Solution

  • 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.