在我的应用程序中,只有管理员用户可以创建和理论上可以编辑用户。到目前为止,仅使用 Symfony 安全系统(没有 FOSUserBundle 管理 - 它的复杂性不是必需的),创建具有不同角色的用户就可以了。完全逃脱我的挑战是如何在不知道用户密码的情况下编辑用户。我一直遇到预期的验证错误
密码不能为空
. 如何完成编辑?我肯定在这里遗漏了一些非常基本的东西。
编辑动作:
public function editAction($id) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ManaClientBundle:User')->find($id);
$form = $this->createForm(new UserType(), $user);
return array(
'form' => $form->createView(),
'user' => $user,
'title' => 'Edit user',
);
}
更新动作:
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ManaClientBundle:User')->find($id);
$originalPassword = $user->getPassword();
$form = $this->createForm(new UserType(), $user);
$form->bind($request);
if ($form->isValid()) {
$plainPassword = $form->get('password')->getData();
if (!empty($plainPassword)) {
//encode the password
$encoder = $this->container->get('security.encoder_factory')->getEncoder($entity); //get encoder for hashing pwd later
$tempPassword = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
$user->setPassword($tempPassword);
}
else {
$user->setPassword($originalPassword);
}
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('user_main', array()));
}
用户表格:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('enabled', 'choice', array(
'choices' => array('Yes' => 'Yes', 'No' => 'No'),
'expanded' => true,
'multiple' => false,
'label' => 'Enabled: ',
))
->add('fname')
->add('sname')
->add('email')
->add('username')
->add('password', 'repeated', array(
'type' => 'password',
'invalid_message' => 'Password fields do not match',
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
))
->add('role', 'choice', array(
'choices' => array('ROLE_USER' => 'User', 'ROLE_ADMIN' => 'Admin'),
'expanded' => true,
'multiple' => false,
'label' => 'Group: ',
))
;
}