Symfony 2 Doctrime 2和表单验证(唯一字段)

Mic*_*leq 5 forms validation symfony symfony-2.1

你好我有小问题.我在sf2中从未做过表单验证器,所以我不知道应该从哪里开始.我有一个字段'用户名',它在数据库中是唯一的,所以我怎么试试呢?

我的代码:

- > ENTITY

 /**
  * @var string $nick_allegro
  *
  * @ORM\Column(name="nick_allegro", type="string", length=255, unique=true, nullable=true)
  */
 private $nick_allegro;
Run Code Online (Sandbox Code Playgroud)

- >表格

 public function buildForm(FormBuilder $builder, array $options)
 {
     $builder
         ->add('nick_allegro')
     ;
 }

 public function getDefaultOptions(array $options) {
     return array(
         'data_class' => 'My\FrontendBundle\Entity\Licence',
     );
 }
Run Code Online (Sandbox Code Playgroud)

- >控制器

 /**
  * Displays a form to create a new Licence entity.
  *
  * @Route("/new", name="licence_new")
  * @Template()
  */
  public function newAction()
  {
      $entity = new Licence();
      $form   = $this->createForm(new LicenceType(), $entity);

      return array(
          'entity' => $entity,
          'form'   => $form->createView()
      );
  }

  /**
   * Creates a new Licence entity.
   *
   * @Route("/create", name="licence_create")
   * @Method("post")
   * @Template("MyFrontendBundle:Licence:new.html.twig")
   */
  public function createAction()
  {
      $entity  = new Licence();
      $request = $this->getRequest();
      $form    = $this->createForm(new LicenceType(), $entity);
      $form->bindRequest($request);

      if ($form->isValid()) {
          $em = $this->getDoctrine()->getEntityManager();
          $em->persist($entity);
          $em->flush();

          return $this->redirect($this->generateUrl('licence_show', array('id' => $entity->getId())));

      }

      return array(
          'entity' => $entity,
          'form'   => $form->createView()
      );
  }
Run Code Online (Sandbox Code Playgroud)

- >查看

 <form action="{{ path('licence_create') }}" method="post" {{
 form_enctype(form) }}>
     {{ form_widget(form) }}
     <p>
         <button type="submit">Create</button>
     </p> </form>
Run Code Online (Sandbox Code Playgroud)

Mic*_*ick 7

您需要在symfony中使用Unique Entity来验证模型中的特定字段是否唯一.

为了帮助你一点(如果你有一个字段叫nick):

1 /在您的实体中

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @UniqueEntity("nick")
*/
class User
{
/**
 * @var string $email
 *
 * @ORM\Column(name="nick", type="string", length=255, unique=true)
 */
private $nick;
Run Code Online (Sandbox Code Playgroud)

验证将直接生效,因为您在实体中声明了约束.因此,您已经可以检查控制器中的validaiton.

2 /在您的控制器中

if ( 'POST' === $request->getMethod()) {

        $form->bind($request);

        if ($form->isValid())
        {
            //do something if the form is valid
        }
}
Run Code Online (Sandbox Code Playgroud)