Browse Source

Fixes #3087: Added `yii\helpers\BaseHtml::error()` "errorMethod" option to be able to customize errors display

tags/2.0.14
杨国帅 7 years ago committed by Alexander Makarov
parent
commit
f9cdcf438d
  1. 1
      framework/CHANGELOG.md
  2. 5
      framework/helpers/BaseHtml.php
  3. 14
      tests/framework/helpers/HtmlTest.php

1
framework/CHANGELOG.md

@ -4,6 +4,7 @@ Yii Framework 2 Change Log
2.0.14 under development
------------------------
- Enh #3087: Added `yii\helpers\BaseHtml::error()` "errorMethod" option to be able to customize errors display (yanggs07, developeruz)
- Bug #15355: Fixed `yii\db\Query::from()` does not work with `yii\db\Expression` (vladis84)
- Bug #8983: Only truncate the original log file for rotation (matthewyang, developeruz)
- Bug #14276: Fixed I18N format with dotted parameters (developeruz)

5
framework/helpers/BaseHtml.php

@ -1271,6 +1271,8 @@ class BaseHtml
* - tag: this specifies the tag name. If not set, "div" will be used.
* See also [[tag()]].
* - encode: boolean, if set to false then the error message won't be encoded.
* - errorMethod (since 2.0.14): string, if set then this value will be used as a method name to
* be called instead of getFirstError().
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
@ -1279,7 +1281,8 @@ class BaseHtml
public static function error($model, $attribute, $options = [])
{
$attribute = static::getAttributeName($attribute);
$error = $model->getFirstError($attribute);
$errorMethod = ArrayHelper::remove($options, 'errorMethod', 'getFirstError');
$error = $model->$errorMethod($attribute);
$tag = ArrayHelper::remove($options, 'tag', 'div');
$encode = ArrayHelper::remove($options, 'encode', true);
return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);

14
tests/framework/helpers/HtmlTest.php

@ -1214,6 +1214,15 @@ EOD;
$this->assertEquals($expectedHtml, Html::errorSummary($model, $options));
}
public function testError()
{
$model = new HtmlTestModel();
$model->validate();
$this->assertEquals('<div>Name cannot be blank.</div>', Html::error($model, 'name'));
$this->assertEquals('<div>this is custom error message</div>', Html::error($model, 'name', ['errorMethod' => 'customError']));
}
/**
* Data provider for [[testActiveTextArea()]].
* @return array test data
@ -1580,4 +1589,9 @@ class HtmlTestModel extends DynamicModel
[['radio', 'checkbox'], 'boolean'],
];
}
public function customError()
{
return 'this is custom error message';
}
}

Loading…
Cancel
Save