6

你好我有一个小问题。我从来没有在 sf2 中做过表单验证器,所以我不知道我应该从哪里开始。我有一个字段“用户名”,它在数据库中是唯一的,那么我该如何尝试呢?

我的代码:

-> 实体

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

-> 表格

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

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

-> 控制器

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

-> 查看

 <form action="{{ path('licence_create') }}" method="post" {{
 form_enctype(form) }}>
     {{ form_widget(form) }}
     <p>
         <button type="submit">Create</button>
     </p> </form>
4

3 回答 3

8

您需要在 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;

当您在实体中声明约束时,验证将直接生效。因此,您已经可以在控制器中检查验证。

2/ 在你的控制器中

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

        $form->bind($request);

        if ($form->isValid())
        {
            //do something if the form is valid
        }
}
于 2012-09-08T12:27:16.400 回答
1

这很简单。足够添加文件实体@ORM\Column this "unique=true"

例子:

class User
{
    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    protected $email;
}
于 2016-06-08T13:38:46.817 回答
0

请记住,sf2.1 中的表单处理发生了一些变化,因此请务必检查正确的文档:

验证以多种方式完成,其中包括对实体字段的注释,在您的情况下,您需要UniqueEntity注释。

请务必在线查看所有 symfony2 文档,因为这是了解问题的最佳方式。

于 2012-09-08T12:27:43.620 回答