开发者

Symfony 2 unique validator

开发者 https://www.devze.com 2023-04-09 03:34 出处:网络
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

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 func开发者_如何学编程tions 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.


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.


First of all, I'd recommend you using FOSUserBundle. It's quite flexible and you can save yourself some time you'd spend by fixing subtle bugs and testing if everything really works as intended.

Anyway, if you really want to build it yourself, you can at least inspire by bundle I mentioned above. They define custom validator and check for uniqueness in UserManager (validateUnique). Additionally, you have to register it as a service to provide UserManager via constructor injection. Then you just use it as a normal class validator.


There's the UniqueEntity validation constraint for ensuring that the user provides a unique value for a particular property.

Please refer to the documentation for examples using the various formats that Symfony supports. Here's an example using annotations:

// Acme/UserBundle/Entity/Author.php
namespace Acme\UserBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

// DON'T forget this use statement!!!
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity("email")
 */
class Author
{
    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    protected $email;

    // ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消