Symfony 2 Doctrime 2 and form validate ( unique field )

12,309

Solution 1

You need to use Unique Entity in symfony to validate that a particular field in a model is unique.

To help you a little bit (if you have a field called nick):

1/ In your entity

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;

Validation will directly take effect as you asserted the constraints in your entity.. Therefore, you can already check the validaiton in your controller.

2/ In your controller

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

        $form->bind($request);

        if ($form->isValid())
        {
            //do something if the form is valid
        }
}

Solution 2

It's very simple. Enough add in file Entity @ORM\Column this "unique=true"

Example:

class User
{
    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    protected $email;
}
Share:
12,309
Micchaleq
Author by

Micchaleq

Updated on October 21, 2022

Comments

  • Micchaleq
    Micchaleq over 1 year

    Hello I have small problem. I've never done form validator in sf2 so I don't know where I should start. I have one field 'username' and it is unique in database so how can I try it?

    My Code :

    -> ENTITY

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

    -> FORM

     public function buildForm(FormBuilder $builder, array $options)
     {
         $builder
             ->add('nick_allegro')
         ;
     }
    
     public function getDefaultOptions(array $options) {
         return array(
             'data_class' => 'My\FrontendBundle\Entity\Licence',
         );
     }
    

    -> Controller

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

    -> View

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