ZF2可选择更改表单中的用户密码

时间:2015-03-18 08:10:53

标签: zend-framework2

我希望有一个表单,登录用户可以更改其用户数据。他可以选择插入新密码。我试图删除密码'的输入过滤器。和密码验证'字段,如果发布的密码为空,但我不知道如何处理我的服务中的保存,密码不会被覆盖......

控制器操作

public function indexAction() {
    $identity = $this->authentication()->getIdentity();
    $userService = $this->userService;

    $form = $this->userForm;
    $form->bind($identity);

    $request = $this->getRequest();
    if ($request->isPost()) {
        $form->setData($request->getPost());

        if ($form->get('password')->getValue() == '') {
            $validationGroup = $form->getValidationGroup();
            $passwordKey = array_search('password', $validationGroup);
            $passwordVerificationKey = array_search('passwordVerification', $validationGroup);

            unset($validationGroup[$passwordKey]);
            unset($validationGroup[$passwordVerificationKey]);

            $form->setValidationGroup($validationGroup);
            $form->getInputFilter()->remove('password');
            $form->getInputFilter()->remove('passwordVerification');
        }

        if ($form->isValid()) {
            $userService->saveUser($form->getData());

            $this->flashMessenger()->addSuccessMessage('Data has been saved successfully');
            return $this->redirect()->toRoute('admin/account');
        }
    }

    return array(
        'userForm' => $form
    );
}

用户服务

public function saveUser(User $user) {
    if ($password = $user->getPassword()) {
        $user->setPassword($this->authenticationService->getAdapter()->getBcrypt()->create($password));
    }

    $this->userRepository->save($user);
}

1 个答案:

答案 0 :(得分:-1)

当我这样做时,我在我的用户实体中使用了一个未映射的密码属性(例如passwordForm),该属性在表单中使用,因此不会覆盖原始密码。如果填写了passwordForm字段,则可以使用该值覆盖原始密码