mercredi 20 février 2019

Symfony ChoiceType Error Messages

How ChoiceTypes Errors

Interestingly, with the validator form extension the ChoiceType always shows as valid when a form is submitted.

If the ChoiceType field ends up not synchronized, a violation is added with the invalid_message option as its message.

To provide a real, useful error message pass invalid_message to your ChoiceType field. invalid_message_parameters is also useful.

use Symfony\Component\Form\Forms;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Validator\Validation;
$validator = Validation::createValidator();
$forms = Forms::createFormFactoryBuilder()
    ->addExtension(new ValidatorExtension($validator))
$choices = [
    'One' => 'one',
    'Two' => 'two',
$form = $forms->createBuilder()
    ->add('test', ChoiceType::class, [
        'choices' => $choices,
        'invalid_message' => '"{{ value }}" is not valid. Valid choices: {{ choices }}.',
        'invalid_message_parameters' => [
            '{{ choices }}' => implode(', ', $choices),
$form->submit(['test' => 'three']);
var_dump($form->isValid()); // true
// outputs '"three" is not valid. Valid choices: one, two.
foreach ($form->getErrors(true) as $err) {
    echo $err->getMessage(), PHP_EOL;

Aucun commentaire:

Enregistrer un commentaire