Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting a placeholder attribute with translation in Symfony2 form input

I am using FOSUserBundle for managing my users. In order to register user, I reused the form of the bundle which meets my needs. Nevertheless, I needed to set some attributes of my fields. This is was done easyly by twig like this:

    {{ form_widget(form.username, { 'attr': {'class': "span12",
        'placeholder': "Username"} }) }}

Now, my goal is to make automatic translation on my placeholder, so I proposed this code:

    {{ form_widget(form.username, { 'attr': {'class': "span12",
        'placeholder': "{{'security.login.usernameplaceholder'|trans}}"} }) }}

This previous code produced an input with placeholder value equal to {{'security.login.usernameplaceholder'|trans}}

To get rid of this problem, I tried to set variable for that but symfony generated an error!!!

    {% set usernameplaceholder = {{'security.login.usernameplaceholder'|trans}} %}
    {{ form_widget(form.username, { 'attr': {'class': "span12",
        'placeholder': usernameplaceholder} }) }}

Is there any proposition to solve this problem?

Thanks,

like image 300
Amine Jallouli Avatar asked Jul 21 '13 06:07

Amine Jallouli


3 Answers

In Twig you shouldn't put {{ within {{ (same for {%); think of it as the php tag.

The following should work

{% set usernameplaceholder = 'security.login.usernameplaceholder'|trans %}
{{ form_widget(form.username, { 'attr': {'class': "span12",
    'placeholder': usernameplaceholder} }) }}

OR

{{ form_widget(form.username, { 'attr': {'class': "span12",
    'placeholder': 'security.login.usernameplaceholder'|trans} }) }}
like image 116
Thomas Potaire Avatar answered Oct 27 '22 20:10

Thomas Potaire


For Symfony 3.x, 4.x

Another way to add placeholders (or any attributes for that matter) is by passing an options-array to the form $builder containing another Array attr with attributes as key-value pairs.

// The parameters are column name, form-type and options-array respectively.
$builder->add('field', null, array(
            'attr' => array(
                 'placeholder' => 'support.contact.titleplaceholder'
             )
        ));
like image 33
Niket Pathak Avatar answered Oct 27 '22 22:10

Niket Pathak


You can translate this way as well (Using symfony4) in twig: In a form placeholder wich would be written like this:

{'attr':{'placeholder': "Text to translate"}}

As for a placeholder in html wich would be written like this, you can translate this way:

<input placeholder="{{"Text to translate"|trans }}">
like image 27
Michaeldc Avatar answered Oct 27 '22 20:10

Michaeldc