Symfony2用于注册的单独实体验证

时间:2013-01-16 14:38:37

标签: validation symfony entity unique

问题是,如何为唯一用户名添加验证?我可以通过$ user-> findByUsername(...)来检查它,但是我没有正确的错误

主要问题是表单实体(Constraints)和(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;
}
// ............
}

RegistrationType:

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();
            }
        }
    }
    // ..............
    }}

1 个答案:

答案 0 :(得分:0)

这是Doctrine2 UniqueEntity约束的工作!

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Table(name="_account")
 * @UniqueEntity("username")
 */
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="username", type="string", length=255, unique=true)
 */
protected $username;

// ...........
}

我还为username

的表结构添加了unicity(unique = true)

修改

当您处理表单中的不同实体而不是持久化实体时,您必须明确验证ORM实体:

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());

            if ($this->get('validator')->validate(user))
            {
                $em->persist($user);
                $em->flush();
            }
            else
            {
                $form->addError(/* ... */);
            }
        }
    }
    // ..............
}

我让您了解如何在表单中添加错误...