Search code examples
phpyiiyii-cmodel

Implementing a custom getter in Yii?


I am working with Yii and I have the following situation:

I have a MySQL table:

charges {
    id INT AUTOINCREMENT,
    name VARCHAR(256),
    value DOUBLE
}

Then I have the model from this table. And finally I have the views for create, list, admin, update and view.

In the admin and view views I want to display the value field formated with two decimal numbers. One option to do this could be in the view and admin files format the number. Is there a way to create a method in the model and then not having to do anything in the views but the method itself will solve formating the number?

thanks


Solution

  • You can override the afterFind() method of CActiveRecord in your model and format the value field in it.

    Alternatively you could also declare a virtual attribute of the model, and set it in the afterFind() method, and use this virtual attribute in the views.

    Example(with virtual attribute):

    Class ChargesModel extends CActiveRecord{
        public $valueModified;
    
        /*
         * other code
         */
    
        protected function afterFind(){
            parent::afterFind();
            // in the following line i'm just making $valueModified and $value equal, but obviously you would have to insert the 2 decimals
            $this->valueModified=$this->value;
        }
    }
    

    Then you can access the virtual attribute like this : $modelObject->valueModified

    I would recommend you to use the virtual attribute, because you then have both the unmodified $value and modified $modifiedValue, once the formatting is done, we can use either as required, and not have to reformat back to original when we need the original.