duanlu1793 2019-07-03 11:54
浏览 81

Symfony - 如何正确使用属性数组的“error_mapping”选项?

The context

I'm using Sylius 1.4.4 with Symfony 4.2.8.

And this is a gist of the code I'll be rambling about: https://gist.github.com/migmolrod/1dbad05afc58974f7b938ab67a36b132

  1. The main entity is Business. Then I have a ContactAwareTrait with 'phone', 'mobile', 'email' and 'fax' fields so I can easily reuse it in several entities. Business entity uses this trait (so do others in my code but for the sake of simplicity, I'll put only the Business related stuff in the gist).
  2. The BusinessType form type then uses a ContactType form type (again, so I can reuse it in the other form types which entities had the ContactAwareTrait).
  3. Then I have the validation yaml file where I specify the constraints. Here I hardcoded the contact fields validation config in the business validation config. Is there a way to abstract that to some sort of 'Contact validation' file that can then be reused in the entity validation? Because now I'm repeating code/config.
  4. I've also put the templates there because... well, at this point I'm just desperate and don't know if I did anything wrong in the most unexpected spot so...

The issue

if I put an invalid value for any of those properties/fields (phone, mobile, email and/or fax), the error message is shown on top of the form, not attached to the corresponding field.

What I've tried

I've been looking for a solution here in SO but all I found is meant to be used with child entities. In my case, the Contact info is not an entity itself but an array of properties in the form, so to speak.

So can I use the 'error_mapping' to tell the validator "hey, this error belongs to this field" in this particular use case? If so, how? I've tried several permutations of 'error_mapping' => ['several permutations here' => 'the same amount or more permutations here'] and in several places (the call to ContactType inside BusinessType, in the ContactType buildForm, in the ContactType fields...), even clearing cache between changes to be sure everything was in place. But no luck.

What can I do? Better to abstract Contact to a model (even non-mapped to doctrine as an entity/table) and refactor code around that?

Any help would be appreciated. I'd prefer to learn and understand how to use the error_mapping option, even if just out of curiosity at this point.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题