バリデーションメッセージをDryにしつつ国際化
id:cakephper:20090727
メッセージは別ファイルで管理してみる。
config/error_messages.php
<?php $config['_error_messages'] = array( 'require' => __( 'hoge', true ), 'email_invalid' => __( 'moge', true ), 'between' => __( 'hage', true ), );
config/bootstrap.php
<?php Configure::load( 'error_messages' );
models/behaviors/validation_error_i18n.php
<?php var $_configName = '_error_messages'; function setup(&$model, $config = array()){ if( !empty( $config['withFieldName'] ) ){ $this->_withFieldName = true; } if( !empty( $config['configName'] ) ){ $this->_configName = $config['configKey']; } } function _getDefaultErrorMessagesI18n(){ //Write Default Error Message $default_error_messages = array( 'require' => 'Please be sure to input.', 'email_invalid' => __('Invalid Email address.',true), 'between' => __('Between %2$d and %3$d characters.',true), ); $error_messages = Configure::read( $this->_configName ); if ( !empty( $error_messages ) ) { return am( $default_error_messages, $error_messages ); } return $default_error_messages; } function clearErrorMessages( &$model ) { $this->_error_messages = array(); }
tests/cases/behaviors/validation_error_i18n.test.php
<?php class ValidationErrorI18nTestModel extends CakeTestModel { var $actsAs = array( 'tools.ValidationErrorI18n' ); function beforeValidate() { $this->replaceValidationErrorMessagesI18n(); return true; } } class ValidationErrorI18nModel extends ValidationErrorI18nTestModel { var $name = 'ValidationErrorI18nTestModel'; var $useTable = false; var $useDbConfig = 'test'; var $validate = array( 'name' => array( 'require' => array( ), ), 'email' => array( 'email_cmp' => array( ), ), ); } class ValidationErrorI18nTest extends CakeTestCase { var $Model = null; function startTest() { $this->Model =& ClassRegistry::init( 'ValidationErrorI18nModel' ); Configure::delete( '_error_messages' ); } function endTest() { $this->Model->clearErrorMessages(); unset( $this->Model ); Configure::delete( '_error_messages' ); } function testReplaceValidationErrorMessagesI18n() { $this->assertFalse( isset( $this->Model->validate['name']['require']['message'] ) ); $this->Model->beforeValidate(); $this->assertTrue( isset( $this->Model->validate['name']['require']['message'] ) ); $this->assertEqual( $this->Model->validate['name']['require']['message'], 'Please be sure to input.' ); } function testReplaceValidationErrorMessagesI18nFromConfig() { Configure::write( '_error_messages.require', 'hogehoge' ); Configure::write( '_error_messages.email_cmp', __( 'mogemoge', true ) ); $this->Model->beforeValidate(); $this->assertTrue( isset( $this->Model->validate['name']['require']['message'] ) ); $this->assertEqual( $this->Model->validate['name']['require']['message'], 'hogehoge' ); $this->assertEqual( $this->Model->validate['email']['email_cmp']['message'], 'mogemoge' ); } }