问题是,如何为唯一用户名添加验证?我可以通过 $user->findByUsername(...) 简单地检查它,但是我不会有正确的错误
主要问题是表单实体(约束)和(ORM)实体是分开的......
用户:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Table(name="_account")
*/
class User implements UserInterface
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="usrename", type="string", length=255)
*/
protected $username;
// ...........
}
登记 :
use Symfony\Component\Validator\Constraints as Assert;
class Registration
{
/** accountName
* @Assert\NotBlank()
* @Assert\Regex
* (
* pattern="/^[a-zA-Z0-9]{1,}$/i",
* message="You use illegal character(s). Must be a-z, A-Z and 0-9 symbols."
* )
* @Assert\Length
* (
* min="4",
* minMessage="User name must be more then 3 characters.",
* max="25",
* maxMessage="User name must be less then 25 characters."
* )
*/
protected $accountName;
public function setAccountName($accountName)
{
$this->accountName = $accountName;
}
// ............
}
注册类型:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('accountName', 'text', array('label' => 'Account Name'))
->add('accountPass', 'repeated', array(
'type' => 'password',
'first_name' => 'Password',
'second_name' => 'Confirm'))
->add('accountMail', 'text', array('label' => 'Account Email'))
->add('accountTerm', 'checkbox', array('label' => 'Our Terms of use'));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Some\NewBundle\Form\Registration',
'required' => false,
'csrf_protection' => false
));
}
// ..........
}
最后一个,控制器
class RegistrationController extends Controller
{
public function defaultAction()
{
$form = $this->createForm(new RegistrationType(), new Registration);
if ($this->getRequest()->isMethod('post'))
{
$form->bind($this->getRequest());
if ($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$ef = $this->get('security.encoder_factory');
$user = new User();
$data = $form->getData();
$pass = $ef->getEncoder($user)->encodePassword($data->getAccountPass(), $user->getSalt());
$user->setPassword($pass);
$user->setUsername($data->getAccountName());
$user->setEmail($data->getAccountMail());
// changed from here
$userErrors = $this->get('validator')->validate($user);
if (count($userErrors) > 0)
{
foreach ($userErrors as $error)
{
$form->addError(new FormError($error));
//$form->get($error->getPropertyPath())->addError($error->getMessage());
}
} else
{
$em->persist($user);
$em->flush();
}
}
}
// ..............
}}