早上好,我正在尝试进行密码更改表格但是没有任何成功到目前为止我一直在研究这部分,我没有在谷歌上找到任何有用的结果所以我来到这里:D
这是我的密码更改控制器操作
/**
*
* @Route("/user/change-password", name="change_password")
* @Template()
*
*/
public function changePasswordAction(Request $request) {
$changePasswordModel = new ChangePassword();
$form = $this->createForm(new ChangePasswordType(), $changePasswordModel);
$form->handleRequest($request);
if($form->isValid()) {
$changePassword = $form->getData();
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($changePassword->getUser());
var_dump($encoder);
$password = $encoder->encodePassword($changePassword->getUser()->getPlainPassword(), $changePassword->getUser()->getSalt());
$changePassword->getUser()->setPassword($password);
$em->persist($changePassword->getUser());
$em->flush();
return $this->redirect($this->generateUrl('change_password_success'));
}
return array(
'form' => $form->createView(),
);
}
密码更改模型
/**
* @Assert\Type(type="AppBundle\Entity\User")
* @Assert\Valid()
*/
protected $user;
/**
* @SecurityAssert\UserPassword(
* message = "Wrong value for your current password"
* )
*/
protected $password;
/**
* @Assert\Length(
* min = 6,
* minMessage = "Password should by at least 6 chars long"
* )
*/
protected $plainPassword;
public function setUser(User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function setPassword($password) {
$this->password = $password;
return $this;
}
public function getPassword() {
return $this->password;
}
public function setPlainPassword($plainPassword) {
$this->plainPassword = $plainPassword;
return $this;
}
public function getPlainPassword() {
return $this->plainPassword;
}
密码类型
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('password', 'password');
$builder->add('plainPassword', 'repeated', array(
'type' => 'password',
'invalid_message' => 'The password fields must match.',
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
));
$builder->add('ChangePassword', 'submit');
}
我当前的错误是:
No encoder has been configured for account "".
500 Internal Server Error - RuntimeException
忘记添加security.yml
encoders:
AppBundle\Entity\User:
algorithm: bcrypt
cost: 15
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
in_memory:
memory: ~
db_provider:
entity:
class: AppBundle\Entity\User
答案 0 :(得分:2)
使用当前代码,您永远不会设置要更改密码的实际用户。因此,以下行失败,因为null
作为参数传递:
$factory->getEncoder($changePassword->getUser());
如果您想坚持当前的实现,您只需要意识到ChangePassword
实际上只是data transfer object需要正确设置。
此设置的部分内容将通过表单处理(ChangePasswordType
)来完成,其他部分必须由您明确设置。所以,例如只需添加:
$changePasswordModel = new ChangePassword();
$changePasswordModel->setUser($this->getUser());
就我个人而言,我认为这种方法是一个好主意,因为它使代码更具语义性(或者如果你愿意,那就是表达性)。请记住,不要在symfony方面考虑隐含的 magic 。