A calculated field in the model

The table has a description field containing a description of the product. In CGridView, I want to display a short description of the product, about 150 characters from the full one. I save it in $short_descriptionlike this:

public function __construct()
{
    $this->short_description = substr($this->description, 0, 150);   
}

Unfortunately, this method does not work. What other options might there be? The option of changing data in the controller is not considered.

Model class inherits from CActiveRecord.


Answer 1, authority 100%

If I understand correctly, then you have a description field in the database, cutting off 150 characters you want to get a shortdescription field.
Having rummaged through the sources of CActiveRecord further CModel and further CComponent we look at the code of the magic method __get()

public function __get($name)
    {
        $getter='get'.$name;
        if(method_exists($this,$getter))
            return $this->$getter();
        else if(strncasecmp($name,'on',2)===0 && method_exists($this,$name))
        {
            // duplicating getEventHandlers() here for performance
            $name=strtolower($name);
            if(!isset($this->_e[$name]))
                $this->_e[$name]=new CList;
            return $this->_e[$name];
        }
        else if(isset($this->_m[$name]))
            return $this->_m[$name];
        else if(is_array($this->_m))
        {
            foreach($this->_m as $object)
            {
                if($object->getEnabled() && (property_exists($object,$name) || $object->canGetProperty($name)))
                    return $object->$name;
            }
        }
        throw new CException(Yii::t('yii','Property "{class}.{property}" is not defined.',
            array('{class}'=>get_class($this), '{property}'=>$name)));
    }

you can try to write a function getsshortdescription

public function getshortdescription()
{
   return mb_substr($this->description,0,150)
}

Answer 2, authority 50%

See what parameters the class has, if, say, something like this:

Class A {
    private description = '';
    public function __construct() {
        //    
    }
...
}

And somewhere there:

$record = new A();

I recommend just extending class A:

Class B extends A {
    ...
}

This will give you access to this->description from class B and you can do whatever you want, unless description is protected, of course.


Answer 3, authority 25%

Add to model:

protected function afterFind(){
    $this->short_description = substr($this->description, 0, 150);  
    return $this;
}