【问题标题】:Custom i18n error messages in Kohana 3.2Kohana 3.2 中的自定义 i18n 错误消息
【发布时间】:2012-04-24 13:02:11
【问题描述】:

我了解在 Kohana 3.2 中创建自定义错误消息的方式:Kohana 3.2: Custom error message for a custom validation rule?

我的问题是重复太多,因为我需要一个单独的文件用于用户模型、帖子模型等。

在大多数情况下,有什么方法可以使用我自己的错误消息吗?我想将它们与 i18n 一起使用。

【问题讨论】:

    标签: internationalization kohana kohana-3.2


    【解决方案1】:

    您可以在 application/messages/validate.php 中为每个验证规则设置默认错误消息:

    <?php
    return array(
        'not_empty' => 'Field is empty',
        'Custom_Class::custom_method' => 'Some error'
    );
    

    这将返回以下示例的消息“字段为空”:

    $post_values = array('title'=>'');
    
    $validation = Validate::factory($post_values)
        ->rules('title', array(
                'not_empty'=>NULL) );
    
    if($validation->check()){
        // save validated values
        $post = ORM::factory('post');
        $post->values($validation);
        $post->save();
    }
    else{
        $errors = $validation->errors(true);
    }
    

    您还可以更改默认 Validate 类的行为,方法是在 application/classes/validate.php 中扩展它:

    class Validate extends Kohana_Validate
    {
        public function errors($file = NULL, $translate = TRUE)
        {
            // default behavior
            if($file){
                return parent::errors($file, $translate);
            }
    
            // Custom behaviour
            // Create a new message list
            $messages = array();
    
            foreach ($this->_errors as $field => $set)
            {
                // search somewhere for your message
                list($error, $params) = $set;
                $message = Kohana::message($file, "{$field}.{$error}");
            }
            $messages[$field] = $message;
        }
        return $messages;
    }
    

    【讨论】:

    • 谢谢,但我想将自定义错误消息与 ORM 一起使用。
    • 此外,我认为您的解决方案存在一些错误:例如,您的 Validate 类可能必须扩展 Kohana_Validation 而不是 Kohana_Validate。 “返回 $messages;”位置也很有趣……
    【解决方案2】:

    消息国际化的方法是这样的:在你的消息文件中用翻译调用替换实际的英文文本,如下所示。

    return array
    ( 
        'code' => array(
            'not_empty'    => __('code.not_empty'),
            'not_found'    => __('code.not_found'),
        ),
    );
    

    然后像往常一样通过 i18n 文件夹中的文件中的条目处理翻译,例如:

    'code.not_empty'  => 'Please enter your invitation code!',
    

    当然,根据您的自定义验证规则调整上述内容。

    【讨论】:

    • The way to go with message internationalization is like this -- Kohana 3.2 documentation: 不要在你的消息文件中使用 __(),因为这些文件可以被缓存并且不能正常工作。跨度>
    猜你喜欢
    • 2012-03-24
    • 2011-03-26
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多