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.
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 %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With