【问题标题】:How to customize the display of "There is already an account with this" message in Twig如何在 Twig 中自定义显示“已经有此帐户”消息
【发布时间】:2022-01-01 19:50:13
【问题描述】:

我正在尝试在 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”之类的红色消息(位于文本字段下方)。 那么,我的代码有什么问题?有什么想法吗?

【问题讨论】:

    标签: twig customization textfield message symfony-4.4


    【解决方案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")
    */
    

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

    【讨论】:

    • 太棒了!现在,还有一件事要弄清楚:如何摆脱错误消息重复?
    • 请参阅Customize Form Rendering,了解有关您的模板为何两次呈现错误的更多信息。
    • 我找到了!我必须将form_row 更改为form_widget
    【解决方案2】:

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

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

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

    【讨论】:

    • 我试过了,但没有任何改变。它一直给我同样的结果。
    • 不太清楚 Symfony/Twig 如何处理配置选项的合并。保持更改并尝试将类型的呈现更改为{{ form_row(registrationForm.cin) }}。这能解决您的问题吗?
    • 我也试过了,但是bug仍然存在。
    • 您是否使用 MakerBundler 创建了此表单?在我看来,您似乎正在尝试使用注册表单添加另一个用户并使用 cin 作为唯一标识符。也许这个方向看起来更有前途。
    • 您是否将自定义验证 @UniqueEntity 添加到用户类的 cin 属性中?
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多