gpt4 book ai didi

php - Symfony 表单事件向特定字段添加错误

转载 作者:行者123 更新时间:2023-12-05 03:09:41 29 4
gpt4 key购买 nike

我的场景如下:

如果用户从“maxRedemptionForDiscount”中选择 true 并在“maxRedemptionForDiscountValue”中键入“0”,则应该向特定字段(在 TextType 字段的位置)呈现一条错误消息

这是带有事件监听器的表单:

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']
);
}

这是 onPreSubmit 函数:

/**
* @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);
}

这是 Twig 代码:

{{ form_row(form.maxRedemptionForDiscount) }}

<div id="maxRedemptionForDiscountValue">
{{ form_row(form.maxRedemptionForDiscountValue) }}
</div>

这会在表单上方呈现一条错误消息。但我想要的是向特定字段呈现错误消息。

这不起作用:

$form->get('maxRedemptionForDiscountValue')->addError(new FormError('error message'));

如果我尝试这样做,错误消息将在我的表单顶部消失,但不会出现在特定字段位置。

我做错了什么?

最佳答案

首先,您应该将 error_bubbling 设置为 false(或将其删除,因为它是默认行为)。

如文档所述

If true, any errors for this field will be passed to the parent field or form. For example, if set to true on a normal field, any errors for that field will be attached to the main form, not to the specific field.

特别是 ChoiceType

Set that error on this field must be attached to the field instead of the parent field (the form in most cases).

其次,您应该将错误添加到特定的表单域

$form
->get('maxRedemptionForDiscountValue')
->addError(new FormError('error message'));

第三,你应该编辑你的模板

<div id="maxRedemptionForDiscountValue">
{{ form_errors(form.maxRedemptionForDiscountValue) }}
{{ form_row(form.maxRedemptionForDiscountValue) }}
</div>

关于php - Symfony 表单事件向特定字段添加错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42108754/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com