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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With