1

I understand the way of creating custom error messages in Kohana 3.2: Kohana 3.2: Custom error message for a custom validation rule?

My problem with it is the too much repeat, because I need a separate file for User Model, Post Model etc.

Are there any way for use my own error messages generally most of the cases? I would like to use them with i18n.

Community
  • 1
  • 1
Subi
  • 11
  • 3

2 Answers2

0

You can set a default error message for each validation rule in application/messages/validate.php:

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

This will return message 'Field is empty' for following example:

$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);
}

You could also change the behaviour of default Validate class, by extending it in 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;
}
nutrija
  • 317
  • 2
  • 8
  • Thanks, but I would like to use the custom error messages with ORM. – Subi Apr 24 '12 at 19:17
  • Furthermore I think your solution has a few mistakes: for example maybe your Validate class must extend Kohana_Validation instead of Kohana_Validate. The "return $messages;" position is interesting too… – Subi Apr 24 '12 at 19:46
0

The way to go with message internationalization is like this: in your message file replace the actual English text with a translation call, as below.

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

Translations are then handled as usually, via entries in files in i18n folder, e.g.:

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

Of course, adapt the above for your custom validation rules.

guntars
  • 320
  • 2
  • 6
  • 1
    `The way to go with message internationalization is like this` -- [Kohana 3.2 documentation](http://kohanaframework.org/3.2/guide/kohana/files/messages): *Don't use __() in your messages files, as these files can be cached and will not work properly.* –  Oct 03 '12 at 19:55