Skip to content

Instantly share code, notes, and snippets.

@Mparaiso
Created March 14, 2013 08:33
Show Gist options
  • Save Mparaiso/5159788 to your computer and use it in GitHub Desktop.
Save Mparaiso/5159788 to your computer and use it in GitHub Desktop.
symfony/form validation constraint
// 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