0

我正在尝试在 Twig 中自定义此错误消息“已有帐户”的显示。

这是表单类中的相关代码:

->add('cin', TextType::class, [
            'required' => true,
        ])

这是相关的 HTML/Twig 代码:

<div class="form-outline">
   {{ form_row(registrationForm.cin ,{'label':false,'attr':{'placeholder':'Numéro carte d\'identité', 'name':'cin', 'class':'form-control', 'id':'cin', 'type':'number', 'minlength':'8', 'maxlength':'8', 'required data-error':'Veuillez saisir votre numéro de carte d\'identité', } } ) }}
   <span style="color: red">{{ form_errors(registrationForm.cin) }}</span>
</div>

如果出现错误,这就是我在屏幕上看到的内容:

在此处输入图像描述

但是,我想得到的只是自定义为“无效卡 ID”之类的红色消息(位于文本字段下方)。那么,我的代码有什么问题?任何想法?

4

2 回答 2

1

经过更多研究后,我们发现可以@UniqueEntity在用户类的验证器中更改错误消息。

将当前验证器从

/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"cin"}, message="There is already an account with this cin")
*/

/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"cin"}, message="Invalid card id")
*/

导致验证错误消息被相应地修改。

于 2022-01-01T21:23:24.967 回答
0

由于 TextType 扩展了 FormType 类,您应该能够定义自定义的无效消息属性。Symfony 将尝试通过在验证器翻译中搜索来解析给定的标识符,或者如果找不到匹配的翻译,则仅使用给定的文本。有关详细信息,请参阅FormType 字段

->add('cin', TextType::class, [
    'required' => true,
    'invalid_message' => 'Invalid card ID'
])

将无效消息更改为此将导致 twig 呈现自定义消息。在上面的示例中,我只是将必需的参数作为选项添加到 TextType。

于 2022-01-01T19:59:19.957 回答