简体   繁体   English

在带有转换的实体类中定义数据转换器invalid_message错误

[英]Define data transformer invalid_message error in entity class with translations

I have made a Data Transformer for my User class on a form field. 我在表单字段上为User类制作了一个Data Transformer。 It is for users to enter another username to which they want to send a private message to. 用户可以输入要向其发送私人消息的另一个用户名。 It also has a title and content, but that doesn't matter, for now. 它也有标题和内容,但这并不重要。

Here is the form builder: 这是表单生成器:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('content', 'textarea')
        ->add(
            'receiver',
            'text',
            array(
                // validation message if the data transformer fails
                'invalid_message' => 'That is not a valid user',
            )
        );

    $builder->get('receiver')->addModelTransformer(new UserTransformer($this->manager));
}

What I want to do is get the invalid_message error and put it into a translation file. 我要做的是获取invalid_message错误并将其放入翻译文件中。 The problem is that I have to write it here: 问题是我必须在这里写:

->add('receiver',
      'text',
       array('invalid_message' => 'user.invalid')

Which will be taken from my translations. 这将取自我的翻译。

Is there a way to have this message in my Entity class along with all the other validators, instead of having it in the form type class? 有没有办法将这个消息与所有其他验证器一起放在我的Entity类中,而不是将它放在表单类型类中? I don't want to spread my validation messages everywhere in my files. 我不想将验证消息分散到文件中的任何位置。

To answer your question, if you really want to store all the message translation keys in your entity, you could store those in a constant array in your entity class. 要回答您的问题,如果您确实要在实体中存储所有消息转换键,则可以将它们存储在实体类的常量数组中。

For example, your entity class may look like : 例如,您的实体类可能类似于:

//..
class Foo
{
    const MESSAGES = [
        'invalidUser' => 'user.invalid'
    ];

    public static function getMessages()
    {
        return self::MESSAGES;
    }

    //..
}

and in your data transformer : 在您的数据转换器中:

->add('receiver',
      'text', [
           'invalid_message' => Foo::getMessages()['invalidUser']
       ]

Still I am failing to fully understand the motivation behind this. 我仍然无法完全理解其背后的动机。 You will need at some point to identify the message you want to display in your data transformer. 您有时需要标识要在数据转换器中显示的消息。 So what is the point to not provide directly the translation key associated to this message, and instead retrieve it through the entity ? 那么,不直接提供与此消息关联的翻译密钥,而是通过实体检索它的意义何在呢?

The place where your messages should be gathered is only the translation file. 应该收集您的消息的地方只是翻译文件。 The validators in your entity class, as well as your data transformer, are only there to provide the good translation keys. 实体类中的验证器以及数据转换器仅在此处提供良好的转换密钥。

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

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