Since Symfony 2.3 you can easily use UserPassword
validation constraint.
AcmeUserBundleFormModelChangePassword.php
namespace AcmeUserBundleFormModel;
use SymfonyComponentSecurityCoreValidatorConstraints as SecurityAssert;
use SymfonyComponentValidatorConstraints as Assert;
class ChangePassword
{
/**
* @SecurityAssertUserPassword(
* message = "Wrong value for your current password"
* )
*/
protected $oldPassword;
/**
* @AssertLength(
* min = 6,
* minMessage = "Password should be at least 6 chars long"
* )
*/
protected $newPassword;
}
AcmeUserBundleFormChangePasswordType.php
namespace AcmeUserBundleForm;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;
class ChangePasswordType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('oldPassword', 'password');
$builder->add('newPassword', 'repeated', array(
'type' => 'password',
'invalid_message' => 'The password fields must match.',
'required' => true,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AcmeUserBundleFormModelChangePassword',
));
}
public function getName()
{
return 'change_passwd';
}
}
AcmeUserBundleControllerDemoController.php
namespace AcmeUserBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use AcmeUserBundleFormChangePasswordType;
use AcmeUserBundleFormModelChangePassword;
class DemoController extends Controller
{
public function changePasswdAction(Request $request)
{
$changePasswordModel = new ChangePassword();
$form = $this->createForm(new ChangePasswordType(), $changePasswordModel);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// perform some action,
// such as encoding with MessageDigestPasswordEncoder and persist
return $this->redirect($this->generateUrl('change_passwd_success'));
}
return $this->render('AcmeUserBundle:Demo:changePasswd.html.twig', array(
'form' => $form->createView(),
));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…