Answer the question
In order to leave comments, you need to log in
How to validate forms in symfony2?
There is a form for changing email on symfony2:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('newEmail', 'email', array(
'required' => true,
'constraints' => array(
new NotBlank(),
new Email(),
)
));
}
Answer the question
In order to leave comments, you need to log in
Maybe just make the field unique in the database and catch an error when writing?
/**
* @ORM\Column(name="email_address", unique="true")
*/
protected $email;
If:
email - current address;
new_email - new but not confirmed.
1. You can check the uniqueness at the stage of writing to new_email. But then you need to make your own validator, which will take the value from new_email, and check it against the primary email field.
2. It is possible at the confirmation stage by writing the value from new_email to the email, and make the first one unique. As @v_prom said , additionally writing UniqueEntity on the email field.
And if you make a small controller that will respond to an AJAX request.
The controller will check if there is already such an email in the database, and accordingly send a true or false response.
AJAX send after the user has moved on to filling out the next form field or 5 seconds after the last character entered. And depending on the response to AJAX, do something with the form, for example, highlight it in red or green.
Well, in addition, do what @v_prom wrote
In your entity add/change a field
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Column(unique=true)
*/
protected $email;
/**
* @param Symfony\Component\Validator\Mapping\ClassMetadata $metadata
*/
public static function loadValidatorMetadata(ClassMetadata $metadata) {
$metadata->addConstraint(new UniqueEntity(array(
"fields" => "email",
"message" => "Данный email уже используется. Введите пожалуйста другой.")
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'email', array(
'required' => true,
'constraints' => array(
new NotBlank(),
new Email(),
)
));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question