How can I attach an error to a field with a custom validator in Symfony?

I’m working on a custom captcha and I created a custom validator which is supposed to validate the captcha.

The problem is that when the captcha is not valid, the error seems to be attached to the parent form raver than the current field (or form because I’m using a custom form with 2 fields).

I tried to look in the documentation but I don’t see where my form is wrong …

// RegistrationType
class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options):void {
        $builder
            ->add('username', TextType::class, [
                'required' => false, 
                'attr' => [ 
                    'class' => 'login__input',
                ],
                'constraints' => [
                    new NotBlank(),
                ]
            ])
            ->add('password', PasswordType::class, [
              'required' => true,
              'attr' => [
                'class' => 'login__input',
              ]
            ])
            ->add('captcha', CaptchaType::class, [
                'mapped' => false,
                'route' => 'app_captcha',
                'error_mapping' => [
                    'captcha' => 'captcha'
                ],
                'constraints' => [ new Challenge()]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
} 

As you can see, I tried to use error_mapping. I also use the challenge constraints multiple time in different configuration to see if there’s a difference but nop

// CaptchaType
class CaptchaType extends AbstractType
{

    public function __construct(private readonly ChallengeInterface $challenge, private readonly UrlGeneratorInterface $urlGenerator) {}

    public function configureOptions(OptionsResolver $resolver) 
    {
        $resolver->setDefaults([
            'constraints' => [
                new Challenge()
            ], 
            'route' => 'app_captcha',
        ]);
        parent::configureOptions($resolver);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('challenge', HiddenType::class, [
            'attr' => [
                'class' => 'captcha-challenge'
            ],
            'data' => $this->challenge->generateKey()
            ])
            ->add('answer', HiddenType::class, [
                'attr' => [
                    'class' => 'captcha-answer'
                ]
            ]
        );

        parent::buildForm($builder, $options);
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {

        $view->vars['attr'] = [
            'width' => PuzzleChallenge::WIDTH,
            'height' => PuzzleChallenge::HEIGHT,
            'piece-width' => PuzzleChallenge::PIECE_WIDTH,
            'piece-height' => PuzzleChallenge::PIECE_HEIGHT,
            'src' => $this->urlGenerator->generate($options['route'], [
                'challenge' => $form->get('challenge')->getData()
            ])
        ];
        
        parent::buildView($view, $form, $options);
    }
}

The validator :

class ChallengeValidator extends ConstraintValidator
{
    public function __construct(private readonly ChallengeInterface $challenge)
    {
        
    }

    /**
     * 
     * @params array{challenge: string, answer: string} $value
     */
    public function validate(mixed $value, Constraint $constraint): void
    {
        // dump($this->context);
        if (null === $value || '' === $value) {
            return;
        }

        if (!$this->challenge->verify($value['challenge'], $value['answer'])) {
            $this->context->buildViolation($constraint->message)
                ->addViolation();
        }

    }
}

I’m using Symfony 7.1 and php 8.2

I tried several things. For exemple you can see here the error in the form parent with a dump :

Form parent with attributes and an error in the error attribute

I tried the constraints “NotBlank” from the username field to see if the error is in the form parent or the field. It is in the field :
Children fields with an error in the attribute error of the username

Here, you can also see the captcha children with his 2 fields and there’s no error
Captcha children from the registration form with no errors

New contributor

Erika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật