Created
March 14, 2013 08:33
-
-
Save Mparaiso/5159788 to your computer and use it in GitHub Desktop.
symfony/form validation constraint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I am trying to put a validation constraint on an input field for inputting a username that it be unique - | |
//if the name is already present in the database I want the validation to fail. | |
//Is there an obvious way to go about this? Any hint in the right direction would be appreciated. | |
/* | |
Here's an example from one of my projects. This is from a registration | |
form, to check if the email is already used. | |
First, I make "app" a required option of my form type: | |
*/ | |
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
parent::setDefaultOptions($resolver); | |
$resolver->setRequired(array("app")); | |
} | |
//Then while building the form, I can access it like: | |
$app = $options["app"]; | |
//and when creating the email field, I attach a callback validator: | |
$builder->add("email", "email", array( | |
"label" => "E-mail address", | |
"constraints" => array( | |
new Assert\NotBlank(), | |
new Assert\Email(), | |
new Assert\Callback(array( | |
"methods" => array(function ($email, | |
ExecutionContext $context) use ($app) { | |
if ($app["db.user"]->findByEmail($email)) { | |
$context->addViolation("Email taken"); | |
} | |
}), | |
)), | |
), | |
)); | |
//In my controller: | |
$form = $app["form.factory"]->create(new UserType(), null, | |
array("app" => $app)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment