My scenario is the following:
If the user choose true from "maxRedemptionForDiscount" and type "0" into the "maxRedemptionForDiscountValue" there should be an error message rendering to the specific field (at the position of the TextType field)
This is the form with an eventListener:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'maxRedemptionForDiscount',
ChoiceType::class,
[
'placeholder' => false,
'multiple' => false,
'choices' => [
true => 'discount.form_fields.set_max_redemptions',
false => 'discount.form_fields.unlimited',
],
'label' => 'discount.form_fields.max_redemption_for_discount',
'translation_domain' => 'entities',
'required' => false,
'error_bubbling' => true,
'attr' => [
'class' => 'maxRedemptionForDiscountSelect',
],
]
)->add(
'maxRedemptionForDiscountValue',
TextType::class,
[
'label' => 'discount.form_fields.set_max_redemptions',
'translation_domain' => 'entities',
'required' => false,
]
)->addEventListener(
FormEvents::PRE_SUBMIT,
[$this, 'onPreSubmit']
);
}
and this is the onPreSubmit function:
/**
* @param FormEvent $event
*/
public function onPreSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if ($data['maxRedemptionForDiscount'] == 1) {
if ($data['maxRedemptionForDiscountValue'] == 0) {
$form->addError(new FormError('error message'));
}
}
$event->setData($data);
}
Here is the twig code:
{{ form_row(form.maxRedemptionForDiscount) }}
<div id="maxRedemptionForDiscountValue">
{{ form_row(form.maxRedemptionForDiscountValue) }}
</div>
This render a error message above the form. But what I want i to render a error message to the specific field.
This does not work:
$form->get('maxRedemptionForDiscountValue')->addError(new FormError('error message'));
If I try this the error message will disappear at the top of my form, but not showing up at the specific field position.
What I am doing wrong here?