【问题标题】:implement change password function symfony 2 with FOS使用 FOS 实现更改密码功能 symfony 2
【发布时间】:2016-04-21 08:07:19
【问题描述】:

我想用 FOS 实现密码更改功能,但我不知道该怎么做。

我首先创建了一个具有两个属性(旧密码和新密码(重复))的表单。

class ChangePasswordType extends UtilisateurType{ 

/**
 * @SecurityAssert\UserPassword(
 *     message = "pswd ko"
 * )
 */
protected $oldPassword;

/**
 * @Assert\Length(
 *     min = 7,
 *     max = 255,
 *     minMessage = "pswd too short"
 *     maxMessage = "pswd too long" 
 * )
 */
protected $newPassword;

protected $user;


public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('old', 'password', array('label' => 'Mot de passe actuel','attr' => array('placeholder' => 'Sasir votre mot de passe actuel','class' =>'form-control')));
    $builder->add('newPassword', 'repeated', array(
            'type' => 'password',
            'invalid_message' => ' Les deux mots de passe ne sont pas identiques  .',
            'required' => true,
            'first_options'  => array('label' => 'Nouveau mot de passe', 'attr' => array('placeholder' => 'Sasir un nouveau mot de passe','class' =>'form-control')),
            'second_options' => array('label' => 'Vérification', 'attr' => array('placeholder' => 'Vérification','class' =>'form-control')),
    ));
}


/**
 * @return string
 */
public function getName()
{
    return 'Mybundle_changePassword';
}

在我的控制器中,我创建了这样的表单:

        $form = $this->createForm(new ChangePasswordType(), null, array(
            'action' => $this->generateUrl('fos_user_change_password'),
            'method' => 'POST',
    ));

在我的树枝中,我有这个表单和一个提交按钮(在 FOS 中操作:changePasswordActionChangePasswordController),但它不起作用。

                            {{ form_start(formChangerPswd) }}
                                {{ form_widget(formChangerPswd) }}
                                    <div class="box-footer">
                                        <input type="submit" value="Modify pswd" class="btn btn-primary pull-right" formnovalidate="formnovalidate"/>
                                    </div><!-- /.box-footer -->
                                {{ form_end(formChangerPswd) }}

我有这个错误

无法从“MyBundle\Entity\User”类型的对象中读取索引“oldPassword”,因为它没有实现 \ArrayAccess。

这是实现此功能的最佳方式吗? 有人可以帮我吗?

【问题讨论】:

  • 您到底想达到什么目的?您是否注意到该捆绑包已经附带了此功能的表单类型?
  • 我正在尝试实现修改密码功能。
  • 这并不能解释为什么您自己构建表单类型,同时重用 FOSUserBundle 已经提供的其余功能。
  • 你能解释一下使用fos的form和controller实现这个功能的方法吗?
  • 您只需要添加一个指向fos_user_change_password 路由的链接。

标签: symfony fosuserbundle


【解决方案1】:

如果您使用 FOSUser 捆绑包,则不需要创建自定义密码更改逻辑,您只需转到要实例化密码更改的 twig 模板并添加此

<a href="{{ path('fos_user_change_password') }}">Change Password</a>

上面的代码是修改密码过程的路由,它调用了fosUser changepassword控制器。

注意:如果您正在设置新的 fosUser 捆绑包,则需要覆盖内置模板并将其自定义为具有您网站的主题。如果你不知道怎么做,你可以访问这个网站,它会给你一个很好的启动
http://www.sitepoint.com/basic-user-management-in-symfony2-with-fosuserbundle/

但是

如果您想从自定义控制器处理更改密码过程

    namespace FOS\UserBundle\Controller;

   use FOS\UserBundle\FOSUserEvents;
   use FOS\UserBundle\Event\FormEvent;
   use FOS\UserBundle\Event\FilterUserResponseEvent;
   use FOS\UserBundle\Event\GetResponseUserEvent;
   use FOS\UserBundle\Model\UserInterface;
   use Symfony\Bundle\FrameworkBundle\Controller\Controller;
   use Symfony\Component\HttpFoundation\Request;
   use Symfony\Component\HttpFoundation\RedirectResponse;
   use Symfony\Component\Security\Core\Exception\AccessDeniedException;

    /**
     * your custom Controller managing the password change
     *
     * 
     */
  class ProfileController extends Controller
     {
     /**
      * Change user password
       */
      public function changePasswordAction(Request $request)
       {
    $user = $this->getUser();



    //dispatch the appropriate events

    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_INITIALIZE,            $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }


 /**
  * this is where you start the initialization of the form to you use
  */

    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface           */
    $formFactory = $this->get('fos_user.change_password.form.factory');

    $form = $formFactory->createForm();
      //pass in the user data
    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isValid()) {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');

        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_SUCCESS, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            //here you set the url to go to after changing the password
              //for example i am redirecting back to the page  that triggered the change password process
            $url = $this->generateUrl('showProfileAccount');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    return $this->render('FOSUserBundle:ChangePassword:changePassword.html.twig', array(
       //note remove this comment. pass the form to template
        'form' => $form->createView()
    ));
}
}

模板

    {{ form_start(form) }}
     {{ form_widget(form) }}
     <div>
    <input type="submit" value="{{ 'change_password.submit'|trans }}" />
     </div>
  {{ form_end(form) }}

【讨论】:

  • 感谢您的回答,但它没有回答我的问题。我有一个用户配置文件视图,我想在此视图中集成更改密码表单。所以,我必须在控制器中初始化呈现配置文件视图的表单?
  • @peace 等等,让我编辑我的答案,向您展示如何从您的自定义控制器初始化更改密码过程
  • Thnk 的@Akoh,你修改了吗?
  • @peace 是的我已经修改过了
  • 你能把答案再发一遍吗?
【解决方案2】:

如果您使用 FOSUser 捆绑包,则不需要创建自定义密码更改逻辑,您只需转到要实例化密码更改的 twig 模板并添加此

<a href="{{ path('fos_user_change_password') }}">Change Password</a>

上面的代码是修改密码过程的路由,它调用了fosUser changepassword控制器。

注意:如果您正在设置新的 fosUser 捆绑包,则需要覆盖内置模板并将其自定义为具有您网站的主题。如果你不知道怎么做,你可以访问这个网站,它会给你一个很好的启动
http://www.sitepoint.com/basic-user-management-in-symfony2-with-fosuserbundle/

但是如果你必须自己处理这个过程,下面的过程是如何去做的

如果您想从自定义控制器处理更改密码过程

    namespace FOS\UserBundle\Controller;

   use FOS\UserBundle\FOSUserEvents;
   use FOS\UserBundle\Event\FormEvent;
   use FOS\UserBundle\Event\FilterUserResponseEvent;
   use FOS\UserBundle\Event\GetResponseUserEvent;
   use FOS\UserBundle\Model\UserInterface;
   use Symfony\Bundle\FrameworkBundle\Controller\Controller;
   use Symfony\Component\HttpFoundation\Request;
   use Symfony\Component\HttpFoundation\RedirectResponse;
   use Symfony\Component\Security\Core\Exception\AccessDeniedException;

    /**
     * your custom Controller managing the password change
     *
     * 
     */
  class ProfileController extends Controller
     {
     /**
      * Change user password
       */
      public function changePasswordAction(Request $request)
       {
    $user = $this->getUser();



    //dispatch the appropriate events

    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_INITIALIZE,            $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }


 /**
  * this is where you start the initialization of the form to you use
  */

    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface           */
    $formFactory = $this->get('fos_user.change_password.form.factory');

    $form = $formFactory->createForm();
      //pass in the user data
    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isValid()) {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');

        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_SUCCESS, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            //here you set the url to go to after changing the password
              //for example i am redirecting back to the page  that triggered the change password process
            $url = $this->generateUrl('showProfileAccount');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    return $this->render('FOSUserBundle:ChangePassword:changePassword.html.twig', array(
       //note remove this comment. pass the form to template
        'form' => $form->createView()
    ));
}
}

模板

    {{ form_start(form) }}
     {{ form_widget(form) }}
     <div>
    <input type="submit" value="{{ 'change_password.submit'|trans }}" />
     </div>
  {{ form_end(form) }}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多