Yii 1.1: decimali18nbehavior

Behavior to convert DECIMAL columns in ActiveRecords to locale specific format
13 followers

This is a behavior for CActiveRecords which converts DECIMALs between DB and locale specific display format.

Requirements

Should work with any 1.1.x version. Not tested with 1.0.x.

Usage

When this behavior is attached to a model, all DECIMAL columns will be formatted with the Yii::app()->numberFormatter component. By default, the default decimal format for the current locale will be used (CNumberFormatter::formatDecimal).

Configuration

Like all behaviors this extension has to be configured in the behaviors() method of a model:

public function behaviors()
{
    return array(
        'defaults'=>array(
            'class'=>'ext.decimali18nbehavior.DecimalI18NBehavior',
            'format'=>'db',
        ),
    );
}

The complete list of configuration options is:

  • format - If not set, the default decimal format is used. If set to a format string, this string is supplied for CNumberFormat::format. If set to db the number of decimals will be read from DB. So a DECIMAL(10,4) will be displayed with 4 decimals.
  • formats - Can be an Array of additional name/format pairs, to supply formats per attribute. If not set, format will be used instead.
  • parseExpression - If set, this expression will be used to convert a formatted number back to DB format. $value will contain the formatted attribute value. For example to convert 1,234 into 1.234 the expression can be set to strtr($value,",",".")

Example

Here's another configuration example for this behavior:

public function behaviors()
{
    return array(
        'defaults'=>array(
            'class'=>'ext.decimali18nbehavior.DecimalI18NBehavior',
            'format'=>'db',  // use DB format by default
            'formats'=> array(
                'someCol'=>'#0.0', // specific format for someCol
            ),
            'parseExpression'=> "strtr(\$value, ',' , '.' )",
        ),
    );
}

Resources

Changelog

  • 1.0.0 - initial release

Total 3 comments

#8848 report it
Juan David Rodriguez at 2012/07/03 11:03am
parseExpresion

I have problems with parseExpresion does not work, always placing a "," Put the symbol that puts you help ... I apologize for my English ...

#5597 report it
Tyr84 at 2011/10/23 06:59pm
Very nice

I wrote formaters for decimal numbers and date in my SuperModel.

But i like that way much more !

#3982 report it
at 2011/05/24 08:51pm
Thanks You Very Much.

This is I need. I Will try and use this extension. thanks.

Leave a comment

Please to leave your comment.

Create extension