Kohana 3.2 でカスタム エラー メッセージを作成する方法を理解しています: Kohana 3.2: カスタム検証ルールのカスタム エラー メッセージ?
私の問題は、ユーザーモデル、ポストモデルなどに別のファイルが必要なため、繰り返しが多すぎることです.
ほとんどの場合、一般的に自分のエラーメッセージを使用する方法はありますか? i18nで使用したいと思います。
Kohana 3.2 でカスタム エラー メッセージを作成する方法を理解しています: Kohana 3.2: カスタム検証ルールのカスタム エラー メッセージ?
私の問題は、ユーザーモデル、ポストモデルなどに別のファイルが必要なため、繰り返しが多すぎることです.
ほとんどの場合、一般的に自分のエラーメッセージを使用する方法はありますか? i18nで使用したいと思います。
メッセージの国際化を行う方法は次のとおりです。メッセージ ファイルで、実際の英語のテキストを以下のように翻訳呼び出しに置き換えます。
return array
(
'code' => array(
'not_empty' => __('code.not_empty'),
'not_found' => __('code.not_found'),
),
);
翻訳は、i18n フォルダー内のファイルのエントリを介して、通常どおり処理されます。
'code.not_empty' => 'Please enter your invitation code!',
もちろん、カスタム検証ルールに合わせて上記を調整してください。
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);
}
application/classes/validate.php で拡張することにより、デフォルトの Validate クラスの動作を変更することもできます。
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;
}