Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 unique validator

I'm trying to validate a form with some fields that need to be unique - username and email address. If I submit the form I get a database error. I want to use a validator like I did for everything else - right now I'm trying to use custom getters and isvalidUsername functions in the object and I'm not sure if using the entity manager in the object is the best way to do this. Heres what I'm working with so far...

    Frontend\UserBundle\Entity\User:
         properties:
             email:
                  - NotBlank: ~
                  - Email: ~
         username:
             - NotBlank: ~
         getters:
              validUsername:
                   - "True": { message: "Duplicate User detected.  Please use a different username." }
              validEmail:
                   - "True": { message: "Duplicate email detected. Please use a different email." }

There are built in unique validators in the fosuserbundle but I haven't been able to figure out how to use them.

like image 526
michael Avatar asked Sep 29 '11 16:09

michael


1 Answers

I know that this is an old question but I've just had to work this out so I thought I would share my solution.

I prefer not to use any bundles to handle my users so this is my manual approach:

<?php
namespace MyCorp\CorpBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/** User - Represent a User object */
class User implements AdvancedUserInterface {

    /** @var integer $id */
    private $id;

    /** @var string $email */
    private $email;

    /** Constructor, Getters, Setters etc... */

    /** Set a list of rules to use when validating an instance of this Class 
        @param Symfony\Component\Validator\Mapping\ClassMetadata $metadata */
    public static function loadValidatorMetadata(ClassMetadata $metadata) {

        $metadata->addPropertyConstraint('email', new MaxLength(255));
        $metadata->addPropertyConstraint('email', new NotBlank());
        $metadata->addPropertyConstraint('email', new Email());

        $metadata->addConstraint(new UniqueEntity(array(
            "fields" => "email", 
            "message" => "This email address is already in use")
        ));

    }

}

As you can see I define my validation in the model itself. Symfony will call loadValidatorMetadata to let you load validators.

like image 152
OrganicPanda Avatar answered Oct 13 '22 02:10

OrganicPanda