necroface
necroface

Reputation: 3465

2 password fields differ in Symfony2

In my UserEditType.php:

<?php

namespace HearWeGo\HearWeGoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use HearWeGo\HearWeGoBundle\Entity\User;

class UserEditType extends AbstractType
{
    protected $user;

    public function __construct(User $user)
    {
        $this->user=$user;
    }

    /**
     * @return mixed
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @param mixed $user
     */
    public function setUser($user)
    {
        $this->user = $user;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName','text',array('data'=>$this->user->getFirstName()))
            ->add('lastName','text',array('data'=>$this->user->getLastName()))
            ->add('email','email',array('data'=>$this->user->getEmail()))
            ->add('dateOfBirth','date',array(
                'data'=>$this->user->getDateOfBirth(),
                'years' => range(date('Y') -100, date('Y')-5)))
            ->add('phone','text',array('data'=>$this->user->getPhone()))
            ->add('password','repeated',array(
                'type'=>'password',
                'invalid_message'=>'Password fields must match',
                'options'=>array('attr'=>array('class'=>'password-field')),
                'required'=>true,
                'first_options'=>array('label'=>'Password'),
                'second_options'=>array('label'=>'Confirm password'),
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {

        $resolver->setDefaults(array('data_class'=>"HearWeGo\\HearWeGoBundle\\Entity\\User"));

    }

    public function getName()
    {
        return 'user_edit';
    }



}
?>

In profile.html.twig view:

    <html>

    <head>
        <title>User Profile</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="{{ asset('bundles/hearwegohearwego/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css">
        <link href="{{ asset('bundles/hearwegohearwego/css/profile.css') }}" rel="stylesheet" type="text/css">
        <script src="{{ asset('bundles/hearwegohearwego/js/jquery-2.1.4.min.js') }}"></script>
        <script src="{{ asset('bundles/hearwegohearwego/js/bootstrap.min.js') }}"></script>
    </head>

    <body>
        <div id="toppage">
            <img src="{{ asset('bundles/hearwegohearwego/images/banner.png') }}" style="width:100%">
        </div>
        <div class="container" align="center">
            <img src="{{ asset('bundles/hearwegohearwego/images/personal/profile.png') }}" style="height:40px">
            <div class="col-md-6">
                <img src="{{ asset('bundles/hearwegohearwego/images/personal/avatar.png') }}" style="width:300px;margin-top: 10px">
                {{ form_start(form) }}
                <h4>{{ form.firstName.vars.data }} {{ form.lastName.vars.data }}</h4>
            </div>
            <div class="col-md-6" style="text-align:left">
                <h5>First Name</h5>
                {{ form_widget(form.firstName,{'attr':{'size':'40'}}) }}
                <h5>Second Name</h5>
                {{ form_widget(form.lastName,{'attr':{'size':'40'}}) }}
                <h5>Email</h5>
                {{ form_widget(form.email,{'attr':{'size':'40'}}) }}
                <h5>Phone</h5>
                {{ form_widget(form.phone,{'attr':{'size':'40'}}) }}
                <h5>Date of Birth</h5>
                {{ form_widget(form.dateOfBirth) }}
                <h5>Password</h5>
                {{ form_widget(form.password.first,{'attr':{'size':'40'}}) }}
                {{ form_widget(form.password.second,{'attr':{'size':'40'}}) }}
                <br><br>
                {{ form_widget(form.submit) }}
                <br><br>
                {{ form_end(form) }}
            </div>
        </div>
        <div class="container" align="center">
            <img src="{{ asset('bundles/hearwegohearwego/images/personal/purchase.png') }}" style="height:40px">
        </div>
    </body>

    </html>

In controller:

/**
     * @Route("/profile",name="edit_profile")
     */
    public function editProfile(Request $request)
    {
        if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
            return  new Response('Please login');
        }

        $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');

        $user=$this->get('security.token_storage')->getToken()->getUser();
        $form=$this->createForm(new UserEditType($user),$user,array('method'=>'POST','action'=>$this->generateUrl('edit_profile')));
        $form->add('submit','submit',array(
            'label'=>'',
            'attr'=>array('class'=>'my-custom-button')
        ));
        if ($request->getMethod()=='POST')
        {
            $form->handleRequest($request);
            if ($form->isValid())
            {
                $em=$this->getDoctrine()->getEntityManager();
                $em->persist($user);
                $em->flush();
                return $this->render('@HearWeGoHearWeGo/Default/profile.html.twig',array("form"=>$form->createView()));
            }
        }

        return $this->render('@HearWeGoHearWeGo/Default/profile.html.twig',array("form"=>$form->createView()));
    }

As I searched, the "repeated" Field Type creates two identical fields whose values must match. This view I created is for user to edit their profile, and they can change password, too. I want to use first password field to type the password they want to change into, and the second one is for confirmation. Is there any way?

Upvotes: 0

Views: 545

Answers (1)

Hakim
Hakim

Reputation: 1102

What you can do, is to add a simple password field in your form for security reason. The user that wants to modify its password must provide the old one. And then you add a repeated password field so the user can type his new password (repeated field also for security reason, so the user doesn't make a typo). You could skip that though, and only put a simple password field for the new password as well.

To sum up, you need two different fields in your form. One for the old password, and one for the new (repeated or simple, as you wish).

Upvotes: 1

Related Questions