简体   繁体   English

symfony2数据转换器和断言

[英]symfony2 data transformer and asserts

I have a symfony2 entity linked to a user entity. 我有一个链接到用户实体的symfony2实体。 The user only submits a users username, not the users ID. 用户仅提交用户名,而不提交用户ID。 So I created a Data Transformer, which works perfectly. 因此,我创建了一个数据转换器,它可以完美运行。

Due to the fact that a username can only have exactly 8 characters I wanted to create a custom error message by adding a Assert\\Length to the field. 由于用户名只能有8个字符,因此我想通过在字段中添加Assert\\Length来创建自定义错误消息。 But that does not work, because the form only accepts a user-object, not a string. 但这是行不通的,因为表单仅接受用户对象,而不接受字符串。

So I tried by creating a Assert\\Callback for the user-field, but that also didn't work for me because I wasn't able to access the submitted value in the Callback / ExecutionContextInterface to test the submitted string (not an object, because wrong length means no user can be found!) 因此,我尝试通过为用户字段创建Assert\\Callback来进行尝试,但这对我也不起作用,因为我无法访问Callback / ExecutionContextInterface中的提交值来测试提交的字符串(不是对象,因为长度错误意味着找不到用户!)

Neither did it work to use the DataTransformer because the thrown TransformationFailedException won't be translated to custom error messages for the user - and that's what I wanted to achieve! 使用DataTransformer也不起作用,因为抛出的TransformationFailedException不会转换为用户的自定义错误消息-这就是我想要实现的目标!

Has anybody an idea how to do this? 有谁知道如何做到这一点?

Thank you very much! 非常感谢你!

Martin 马丁

The only way to achieve what I wanted to do was to use the method answered in Combine constraints and data transformers . 实现我想要做的唯一方法是使用“ 合并约束和数据转换器”中回答的方法。 Hope that helps others too! 希望对别人也有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM