Reputation: 65
I'm trying to translate a label in my twig. I have a basic contact form with firstname, lastname, phone, email. I have a collection called "BookContact" in which I'm able to add many contacts. The user can generate a new contact form by clicking the "add contact" button (jQuery event using prototype as explained here : http://symfony.com/fr/doc/current/cookbook/form/form_collections.html, I'm not working with taks and tafgs but with BookContact and Contact ).
When I display my collection in the twig:
{% for contact in form_book_contact.contacts %}
Contact n° {{ num_contact }}
<div class="row" id="bookcontacts" data-prototype="{{ form_widget(form_book_contact.contacts.vars.prototype)|e }}">
<div class="col-md-6">
<div class="form-group">
{{ form_widget(contact.firstname) }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form_widget(contact.lastname) }}
</div>
....
{% endfor %}
The inputs look like:
<input type="text" class="form-control" placeholder="0.lastname" name="book_contact[contacts][0][lastname]" id="book_contact_contacts_0_lastname">
And my translation file has:
book_contact:
firstname: "Prénom"
lastname: "Nom"
.....
In this case, the translation doesn't work (which is normal because the name of the input is not "firstname" but "0.firsname". The problem is that I cannot handle the number of the generation of contact forms. When the user clicks the "add contact" button, the inputs look like: "1.firstname" etc...
How can I handle this kind of translation? How can I manage this number changing in my translation file ?
Thanks for you help.
Upvotes: 1
Views: 257
Reputation: 1158
As labels are already translated in the default form layout, you should only have to set it in your form type.
So if you have a form type:
class BookContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname')
->add('lastname')
;
}
}
Then simply use the form_label(form.firstName)
in your template and translate them into messages.fr.yml:
Firstname: "Prénom" # Do not forget the first uppercased character
Lastname: "Nom"
Or if you prefer using your translation prefix:
class BookContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', null, [
'label' => 'book_contact.firstname',
])
->add('lastname', null, [
'label' => 'book_contact.lastname',
])
;
}
}
And use the following messages.fr.yml:
book_contact:
firstname: "Prénom"
lastname: "Nom"
Upvotes: 0