Commit 0e4da438 by Qiang Xue

Merge pull request #3906 from cebe/Erik-r-2359-formatter-refactored

[WIP] formatter refactored
parents 38476309 2b38d6ab
...@@ -141,7 +141,7 @@ Data column is for displaying and sorting data. It is default column type so spe ...@@ -141,7 +141,7 @@ Data column is for displaying and sorting data. It is default column type so spe
using it. using it.
The main setting of the data column is its format. It could be specified via `format` attribute. Its values are The main setting of the data column is its format. It could be specified via `format` attribute. Its values are
corresponding to methods in `format` application component that is [[\yii\base\Formatter|Formatter]] by default: corresponding to methods in `format` application component that is [[\yii\i18n\Formatter|Formatter]] by default:
```php ```php
<?= GridView::widget([ <?= GridView::widget([
...@@ -158,34 +158,12 @@ corresponding to methods in `format` application component that is [[\yii\base\F ...@@ -158,34 +158,12 @@ corresponding to methods in `format` application component that is [[\yii\base\F
]); ?> ]); ?>
``` ```
In the above `text` corresponds to [[\yii\base\Formatter::asText()]]. The value of the column is passed as the first In the above `text` corresponds to [[\yii\i18n\Formatter::asText()]]. The value of the column is passed as the first
argument. In the second column definition `date` corresponds to [[\yii\base\Formatter::asDate()]]. The value of the argument. In the second column definition `date` corresponds to [[\yii\i18n\Formatter::asDate()]]. The value of the
column is, again, passed as the first argument while 'Y-m-d' is used as the second argument value. column is, again, passed as the first argument while 'Y-m-d' is used as the second argument value.
Here's the bundled formatters list: For a list of available formatters see the [section about Data Formatting](output-formatter.md).
- [[\yii\base\Formatter::asRaw()|raw]] - the value is outputted as is.
- [[\yii\base\Formatter::asText()|text]] - the value is HTML-encoded. This format is used by default.
- [[\yii\base\Formatter::asNtext()|ntext]] - the value is formatted as an HTML-encoded plain text with newlines converted
into line breaks.
- [[\yii\base\Formatter::asParagraphs()|paragraphs]] - the value is formatted as HTML-encoded text paragraphs wrapped
into `<p>` tags.
- [[\yii\base\Formatter::asHtml()|html]] - the value is purified using [[HtmlPurifier]] to avoid XSS attacks. You can
pass additional options such as `['html', ['Attr.AllowedFrameTargets' => ['_blank']]]`.
- [[\yii\base\Formatter::asEmail()|email]] - the value is formatted as a mailto link.
- [[\yii\base\Formatter::asImage()|image]] - the value is formatted as an image tag.
- [[\yii\base\Formatter::asUrl()|url]] - the value is formatted as a hyperlink.
- [[\yii\base\Formatter::asBoolean()|boolean]] - the value is formatted as a boolean. You can set what's rendered for
true and false values by calling `Yii::$app->formatter->booleanFormat = ['No', 'Yes'];` before outputting GridView.
- [[\yii\base\Formatter::asDate()|date]] - the value is formatted as date.
- [[\yii\base\Formatter::asTime()|time]] - the value is formatted as time.
- [[\yii\base\Formatter::asDatetime()|datetime]] - the value is formatted as datetime.
- [[\yii\base\Formatter::asInteger()|integer]] - the value is formatted as an integer.
- [[\yii\base\Formatter::asDouble()|double]] - the value is formatted as a double number.
- [[\yii\base\Formatter::asNumber()|number]] - the value is formatted as a number with decimal and thousand separators.
- [[\yii\base\Formatter::asSize()|size]] - the value that is a number of bytes is formatted as a human readable size.
- [[\yii\base\Formatter::asRelativeTime()|relativeTime]] - the value is formatted as the time interval between a date
and now in human readable form.
#### Action column #### Action column
......
Data Formatter
==============
For formatting of outputs Yii provides a formatter class to make date more readable for users.
[[yii\i18n\Formatter]] is a helper class that is registered as an [application component](concept-components.md) name `formatter` by default.
It provides a set of methods for data formatting purpose such as date/time values, numbers and other commonly used formats in a localized way.
The formatter can be used in two different ways.
1. Using the formatting methods(all formatter methods prefixed with `as`) directly:
```php
echo Yii::$app->formatter->asDate('2014-01-01', 'long'); // output: January 1, 2014
echo Yii::$app->formatter->asPercent(0.125, 2); // output: 12.50%
echo Yii::$app->formatter->asEmail('cebe@example.com'); // output: <a href="mailto:cebe@example.com">cebe@example.com</a>
echo Yii::$app->formatter->asBoolean(true); // output: Yes
// it also handles display of null values:
echo Yii::$app->formatter->asDate(null); // output: (Not set)
```
2. Using the [[yii\i18n\Formatter::format()|format()]] method using the format name.
This method is used by classes like GridView and DetailView where you can specify the data format of a column in the
widget config.
```php
echo Yii::$app->formatter->format('2014-01-01', 'date'); // output: January 1, 2014
// you can also use an array to specify parameters for the format method:
// `2` is the value for the $decimals parameter of the asPercent()-method.
echo Yii::$app->formatter->format(0.125, ['percent', 2]); // output: 12.50%
```
All output of the formatter is localized when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed.
You can configure the [[yii\i18n\Formatter::locale|locale]] property of the formatter for this. If not configured, the
application [[yii\base\Application::language|language]] is used as the locale. See the [Section on internationaization](tutorial-i18n.md) for more details.
The Formatter will then choose the correct format for dates and number according to the locale including names of month and
week days translated to the current language. Date formats are also affected by the [[yii\i18n\Formatter::timeZone|timeZone]]
which will also be taken [[yii\base\Application::timeZone|from the application]] by default.
For example the date format call will output different results for different locales:
```php
Yii::$app->formatter->locale = 'en-US';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: January 1, 2014
Yii::$app->formatter->locale = 'de-DE';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: 1. Januar 2014
Yii::$app->formatter->locale = 'ru-RU';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: 1 января 2014 г.
```
> Note that formatting may differ between different versions of the ICU library compiled with PHP and also based on the fact whether the
> [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed or not. So to ensure your website works with the same output
> in all environments it is recommended to install the PHP intl extension in all environments and verify that the version of the ICU library
> is the same.
Configuring the format
----------------------
The default format of the Formatter class can be adjusted using the properties of the formatter class.
You can adjust these values application wide by configuring the `formatter` component in your [application config](concept-configurations.md#application-configurations)
an example configuration is shown in the following.
For more details about certain properties check out the [[yii\i18n\Formatter|API documentation of the Formatter class]].
```php
'components' => [
'formatter' => [
'dateFormat' => 'dd.MM.yyyy',
'decimalSeparator' => ',',
'thousandSeparator' => ' ',
'currencyCode' => 'EUR',
];
```
Formatting Dates
----------------
TDB
See http://site.icu-project.org/ for the format.
- [[\yii\i18n\Formatter::asDate()|date]] - the value is formatted as date.
- [[\yii\i18n\Formatter::asTime()|time]] - the value is formatted as time.
- [[\yii\i18n\Formatter::asDatetime()|datetime]] - the value is formatted as datetime.
- [[\yii\i18n\Formatter::asTimestamp()|timestamp]] - the value is formatted as a unix timestamp.
- [[\yii\i18n\Formatter::asRelativeTime()|relativeTime]] - the value is formatted as the time interval between a date
and now in human readable form.
Formatting Numbers
------------------
TDB
See http://site.icu-project.org/ for the format.
- [[\yii\i18n\Formatter::asInteger()|integer]] - the value is formatted as an integer.
- [[\yii\i18n\Formatter::asDecimal()|decimal]] - the value is formatted as a number with decimal and thousand separators.
- [[\yii\i18n\Formatter::asPercent()|percent]] - the value is formatted as a percent number.
- [[\yii\i18n\Formatter::asScientific()|scientific]] - the value is formatted as a number in scientific format.
- [[\yii\i18n\Formatter::asCurrency()|currency]] - the value is formatted as a currency value.
- [[\yii\i18n\Formatter::asSize()|size]] - the value that is a number of bytes is formatted as a human readable size.
- [[\yii\i18n\Formatter::asShortSize()|shortSize]] - the value that is a number of bytes is formatted as a human readable size.
Other formatters
----------------
TDB
Here's the bundled formatters list:
- [[\yii\i18n\Formatter::asRaw()|raw]] - the value is outputted as is.
- [[\yii\i18n\Formatter::asText()|text]] - the value is HTML-encoded. This format is used by default.
- [[\yii\i18n\Formatter::asNtext()|ntext]] - the value is formatted as an HTML-encoded plain text with newlines converted
into line breaks.
- [[\yii\i18n\Formatter::asParagraphs()|paragraphs]] - the value is formatted as HTML-encoded text paragraphs wrapped
into `<p>` tags.
- [[\yii\i18n\Formatter::asHtml()|html]] - the value is purified using [[HtmlPurifier]] to avoid XSS attacks. You can
pass additional options such as `['html', ['Attr.AllowedFrameTargets' => ['_blank']]]`.
- [[\yii\i18n\Formatter::asEmail()|email]] - the value is formatted as a mailto link.
- [[\yii\i18n\Formatter::asImage()|image]] - the value is formatted as an image tag.
- [[\yii\i18n\Formatter::asUrl()|url]] - the value is formatted as a hyperlink.
- [[\yii\i18n\Formatter::asBoolean()|boolean]] - the value is formatted as a boolean. You can set what's rendered for
true and false values by calling `Yii::$app->formatter->booleanFormat = ['No', 'Yes'];` before outputting GridView.
...@@ -94,7 +94,7 @@ if you do not specify its class, the default one will be used. ...@@ -94,7 +94,7 @@ if you do not specify its class, the default one will be used.
Please refer to the [Data Access Objects](db-dao.md) section for more details. Please refer to the [Data Access Objects](db-dao.md) section for more details.
* [[yii\base\Application::errorHandler|errorHandler]]: handles PHP errors and exceptions. * [[yii\base\Application::errorHandler|errorHandler]]: handles PHP errors and exceptions.
Please refer to the [Handling Errors](tutorial-handling-errors.md) section for more details. Please refer to the [Handling Errors](tutorial-handling-errors.md) section for more details.
* [[yii\base\Formatter|formatter]]: formats data when they are displayed to end users. For example, a number * [[yii\i18n\Formatter|formatter]]: formats data when they are displayed to end users. For example, a number
may be displayed with thousand separator, a date may be formatted in long format. may be displayed with thousand separator, a date may be formatted in long format.
Please refer to the [Data Formatting](output-formatting.md) section for more details. Please refer to the [Data Formatting](output-formatting.md) section for more details.
* [[yii\i18n\I18N|i18n]]: supports message translation and formatting. * [[yii\i18n\I18N|i18n]]: supports message translation and formatting.
......
...@@ -308,7 +308,7 @@ content to end users, you should try to [internationalize and localize](tutorial ...@@ -308,7 +308,7 @@ content to end users, you should try to [internationalize and localize](tutorial
- If the extension displays messages intended for end users, the messages should be wrapped into `Yii::t()` - If the extension displays messages intended for end users, the messages should be wrapped into `Yii::t()`
so that they can be translated. Messages meant for developers (such as internal exception messages) do not need so that they can be translated. Messages meant for developers (such as internal exception messages) do not need
to be translated. to be translated.
- If the extension displays numbers, dates, etc., they should be formatted using [[yii\base\Formatter]] with - If the extension displays numbers, dates, etc., they should be formatted using [[yii\i18n\Formatter]] with
appropriate formatting rules. appropriate formatting rules.
For more details, please refer to the [Internationalization](tutorial-i18n.md) section. For more details, please refer to the [Internationalization](tutorial-i18n.md) section.
......
...@@ -478,23 +478,4 @@ put there file for russian language as follows `views/site/ru-RU/index.php`. ...@@ -478,23 +478,4 @@ put there file for russian language as follows `views/site/ru-RU/index.php`.
i18n formatter i18n formatter
-------------- --------------
i18n formatter component is the localized version of formatter that supports formatting of date, time and numbers based See the [Date Formatter section](output-formatter.md) for details.
on current locale. In order to use it you need to configure formatter application component as follows:
```php
return [
// ...
'components' => [
'formatter' => [
'class' => 'yii\i18n\Formatter',
],
],
];
```
After configuring the component can be accessed as `Yii::$app->formatter`.
Note that in order to use i18n formatter you need to install and enable
[intl](http://www.php.net/manual/en/intro.intl.php) PHP extension.
In order to learn about formatter methods refer to its API documentation: [[yii\i18n\Formatter]].
...@@ -217,6 +217,9 @@ Yii Framework 2 Change Log ...@@ -217,6 +217,9 @@ Yii Framework 2 Change Log
- Enh: ListView now uses the widget ID in the base tag, consistent to gridview (cebe) - Enh: ListView now uses the widget ID in the base tag, consistent to gridview (cebe)
- Enh: Added `yii\web\Response::enableCsrfCookie` to support storing CSRF tokens in session (qiangxue) - Enh: Added `yii\web\Response::enableCsrfCookie` to support storing CSRF tokens in session (qiangxue)
- Chg #2287: Split `yii\db\ColumnSchema::typecast()` into two methods `phpTypecast()` and `dbTypecast()` to allow specifying PDO type explicitly (cebe) - Chg #2287: Split `yii\db\ColumnSchema::typecast()` into two methods `phpTypecast()` and `dbTypecast()` to allow specifying PDO type explicitly (cebe)
- Chg #2359: Refactored formatter class. One class with or without intl extension and PHP format pattern as standard (Erik_r, cebe)
- `yii\base\Formatter` functionality has been merged into `yii\i18n\Formatter`
- removed the `yii\base\Formatter` class
- Chg #2380: `yii\widgets\ActiveForm` will register validation js even if there are not fields inside (qiangxue) - Chg #2380: `yii\widgets\ActiveForm` will register validation js even if there are not fields inside (qiangxue)
- Chg #2898: `yii\console\controllers\AssetController` is now using hashes instead of timestamps (samdark) - Chg #2898: `yii\console\controllers\AssetController` is now using hashes instead of timestamps (samdark)
- Chg #2913: RBAC `DbManager` is now initialized via migration (samdark) - Chg #2913: RBAC `DbManager` is now initialized via migration (samdark)
......
...@@ -214,6 +214,36 @@ new ones save the following code as `convert.php` that should be placed in the s ...@@ -214,6 +214,36 @@ new ones save the following code as `convert.php` that should be placed in the s
tag around each radio/checkbox when you specify labels for them. You should manually render such container tags, tag around each radio/checkbox when you specify labels for them. You should manually render such container tags,
or set the `item` option for `Html::radioList()`, `Html::checkboxList()` to generate the container tags. or set the `item` option for `Html::radioList()`, `Html::checkboxList()` to generate the container tags.
* The formatter class has been refactored to have only one class regardless whether PHP intl extension is installed or not.
Functionality of `yii\base\Formatter` has been merged into `yii\i18n\Formatter` and `yii\base\Formatter` has been
removed so you have to replace all usage of `yii\base\Formatter` with `yii\i18n\Formatter` in your code.
Also the API of the Formatter class has changed in many ways.
The signature of the following Methods has changed:
- `asDate`
- `asTime`
- `asDateTime`
- `asSize` has been split up into `asSize` and `asShortSize`
- `asCurrency`
- `asDecimal`
- `asPercent`
- `asScientific`
The following methods have been removed, this also means that the corresponding format which may be used by a
GridView or DetailView is not available anymore:
- `asNumber`
- `asDouble`
Also due to these changes some formatting defaults have changes so you have to check all your GridView and DetailView
configuration and make sure the formatting is displayed correctly.
The configuration for `asSize()` has changed. It now uses the configuration for the number formatting from intl
and only the base is configured using `$sizeFormatBase`.
The specification of the date and time formats is now using the ICU pattern format even if PHP intl extension is not installed.
You can prefix a date format with `php:` to use the old format of the PHP `date()`-function.
* `beforeValidate()`, `beforeValidateAll()`, `afterValidate()`, `afterValidateAll()`, `ajaxBeforeSend()` and `ajaxComplete()` * `beforeValidate()`, `beforeValidateAll()`, `afterValidate()`, `afterValidateAll()`, `ajaxBeforeSend()` and `ajaxComplete()`
are removed from `ActiveForm`. The same functionality is now achieved via JavaScript event mechanism. For example, are removed from `ActiveForm`. The same functionality is now achieved via JavaScript event mechanism. For example,
if you want to do something before performing validation on the client side, you can write the following if you want to do something before performing validation on the client side, you can write the following
...@@ -228,3 +258,4 @@ new ones save the following code as `convert.php` that should be placed in the s ...@@ -228,3 +258,4 @@ new ones save the following code as `convert.php` that should be placed in the s
} }
}); });
``` ```
...@@ -22,7 +22,7 @@ use Yii; ...@@ -22,7 +22,7 @@ use Yii;
* @property \yii\db\Connection $db The database connection. This property is read-only. * @property \yii\db\Connection $db The database connection. This property is read-only.
* @property \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application * @property \yii\web\ErrorHandler|\yii\console\ErrorHandler $errorHandler The error handler application
* component. This property is read-only. * component. This property is read-only.
* @property \yii\base\Formatter $formatter The formatter application component. This property is read-only. * @property \yii\i18n\Formatter $formatter The formatter application component. This property is read-only.
* @property \yii\i18n\I18N $i18n The internationalization application component. This property is read-only. * @property \yii\i18n\I18N $i18n The internationalization application component. This property is read-only.
* @property \yii\log\Dispatcher $log The log dispatcher application component. This property is read-only. * @property \yii\log\Dispatcher $log The log dispatcher application component. This property is read-only.
* @property \yii\mail\MailerInterface $mailer The mailer application component. This property is read-only. * @property \yii\mail\MailerInterface $mailer The mailer application component. This property is read-only.
...@@ -514,7 +514,7 @@ abstract class Application extends Module ...@@ -514,7 +514,7 @@ abstract class Application extends Module
/** /**
* Returns the formatter component. * Returns the formatter component.
* @return \yii\base\Formatter the formatter application component. * @return \yii\i18n\Formatter the formatter application component.
*/ */
public function getFormatter() public function getFormatter()
{ {
...@@ -612,7 +612,7 @@ abstract class Application extends Module ...@@ -612,7 +612,7 @@ abstract class Application extends Module
return [ return [
'log' => ['class' => 'yii\log\Dispatcher'], 'log' => ['class' => 'yii\log\Dispatcher'],
'view' => ['class' => 'yii\web\View'], 'view' => ['class' => 'yii\web\View'],
'formatter' => ['class' => 'yii\base\Formatter'], 'formatter' => ['class' => 'yii\i18n\Formatter'],
'i18n' => ['class' => 'yii\i18n\I18N'], 'i18n' => ['class' => 'yii\i18n\I18N'],
'mailer' => ['class' => 'yii\swiftmailer\Mailer'], 'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
'urlManager' => ['class' => 'yii\web\UrlManager'], 'urlManager' => ['class' => 'yii\web\UrlManager'],
......
...@@ -28,7 +28,6 @@ return [ ...@@ -28,7 +28,6 @@ return [
'yii\base\Event' => YII2_PATH . '/base/Event.php', 'yii\base\Event' => YII2_PATH . '/base/Event.php',
'yii\base\Exception' => YII2_PATH . '/base/Exception.php', 'yii\base\Exception' => YII2_PATH . '/base/Exception.php',
'yii\base\ExitException' => YII2_PATH . '/base/ExitException.php', 'yii\base\ExitException' => YII2_PATH . '/base/ExitException.php',
'yii\base\Formatter' => YII2_PATH . '/base/Formatter.php',
'yii\base\InlineAction' => YII2_PATH . '/base/InlineAction.php', 'yii\base\InlineAction' => YII2_PATH . '/base/InlineAction.php',
'yii\base\InvalidCallException' => YII2_PATH . '/base/InvalidCallException.php', 'yii\base\InvalidCallException' => YII2_PATH . '/base/InvalidCallException.php',
'yii\base\InvalidConfigException' => YII2_PATH . '/base/InvalidConfigException.php', 'yii\base\InvalidConfigException' => YII2_PATH . '/base/InvalidConfigException.php',
......
...@@ -63,7 +63,7 @@ class DataColumn extends Column ...@@ -63,7 +63,7 @@ class DataColumn extends Column
* @var string|array in which format should the value of each data model be displayed as (e.g. "raw", "text", "html", * @var string|array in which format should the value of each data model be displayed as (e.g. "raw", "text", "html",
* ['date', 'Y-m-d']). Supported formats are determined by the [[GridView::formatter|formatter]] used by * ['date', 'Y-m-d']). Supported formats are determined by the [[GridView::formatter|formatter]] used by
* the [[GridView]]. Default format is "text" which will format the value as an HTML-encoded plain text when * the [[GridView]]. Default format is "text" which will format the value as an HTML-encoded plain text when
* [[\yii\base\Formatter::format()]] or [[\yii\i18n\Formatter::format()]] is used. * [[\yii\i18n\Formatter::format()]] or [[\yii\i18n\Formatter::format()]] is used.
*/ */
public $format = 'text'; public $format = 'text';
/** /**
......
...@@ -9,7 +9,7 @@ namespace yii\grid; ...@@ -9,7 +9,7 @@ namespace yii\grid;
use Yii; use Yii;
use Closure; use Closure;
use yii\base\Formatter; use yii\i18n\Formatter;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\helpers\Url; use yii\helpers\Url;
use yii\helpers\Html; use yii\helpers\Html;
......
...@@ -9,7 +9,7 @@ namespace yii\widgets; ...@@ -9,7 +9,7 @@ namespace yii\widgets;
use Yii; use Yii;
use yii\base\Arrayable; use yii\base\Arrayable;
use yii\base\Formatter; use yii\i18n\Formatter;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\base\Model; use yii\base\Model;
use yii\base\Widget; use yii\base\Widget;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment