Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom rendering of a "repeated" field from Symfony 2 in Twig

Tags:

twig

symfony

I just started using Twig and I'm trying to build a registration form. To add a password/re-enter password field I use the "repeated" filetype:

->add('password', 'repeated', array(     'type' => 'password',     'invalid_message' => 'Passwords have to be equal.',     'first_name'      => 'Password',     'second_name'     => 'Re-enter password', )); 

which works as intended. The problem I have however is that I want to add some custom classes etc. to my form. So my template looks like this:

<form action="{{ path('register') }}" method="post" {{ form_enctype(form) }}>     {{ form_errors(form) }}     {{ form_errors(form.username) }}     <div class="form-field">         {{ form_label(form.username, null, { 'attr': {'class': 'form-label'} }) }}         {{ form_widget(form.username, { 'attr': {'class': 'form-input'} }) }}     </div>     {{ form_errors(form.email) }}     <div class="form-field">         {{ form_label(form.email, null, { 'attr': {'class': 'form-label'} }) }}         {{ form_widget(form.email, { 'attr': {'class': 'form-input'} }) }}     </div>     {{ form_errors(form.password) }}     <div class="form-field">         {{ form_label(form.password, null, { 'attr': {'class': 'form-label'} }) }}         {{ form_widget(form.password, { 'attr': {'class': 'form-input'} }) }}     </div>      {{ form_rest(form) }}      <input type="submit" class="contact-submit" /> </form> 

this works fine for everything except for the password part. I want to render both fields seperately there, now they are just both rendered in the same div.

How do I fix this? Is there a way to select the seperate fields in Twig? Or am I just doing something wrong because I encounter this problem in the first place.

like image 304
teuneboon Avatar asked May 20 '12 16:05

teuneboon


2 Answers

After a random guess I solved my own problem. I'll post it here so others who might come to this question by searching also know the answer:

{% for passwordField in form.password %}     <div class="form-field">         {{ form_label(passwordField, null, { 'attr': {'class': 'form-label'} }) }}         {{ form_widget(passwordField, { 'attr': {'class': 'form-input'} }) }}     </div> {% endfor %} 
like image 87
teuneboon Avatar answered Sep 28 '22 07:09

teuneboon


If you want to seperate both passwords field from a repeated method in your twig template you just have to call back their respective names like:

{{ form_label(form.password.pass, "Password :") }} {{ form_widget(form.password.pass) }}  {{ form_label(form.password.confirm, "Confirm :") }} {{ form_widget(form.password.confirm) }} 

And of course in your function:

/.. ->add('password', 'repeated', array( 'first_name' => 'pass', 'second_name' => 'confirm', 'type' => 'password' )) 

Regards.

like image 24
Log Avatar answered Sep 28 '22 07:09

Log