简体   繁体   中英

Adding new field in model class using Yii framework

In table i have column 'description' , which contain description of goods. I want include in CGridView column 'short_description', which will contain first 150 characters.

class Product extends CActiveRecord
{   
    /**
     * The followings are the available columns in table 'Product':
     * @var integer $id
     * @var integer $id_cat
     * @var string $title
     * @var string $description
     * @var timestamp $date
     */
    public $id;
    public $id_cat;
    public $title;
    public $description;
    public $date;
    public $short_description ;

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

Unfortunately, this code does not work .

You need to override afterFind function of model class and write the code

$this->short_description = substr($this->description, 0, 150);

in afterFind function.

You need to do some thing like this

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

Another option is to define the function

public function getShortDescription()
{
   return substr($this->description, 0, 150);
}

Then you can call $product->shortDescription (using get magic method).

In this way the short description will only be "calculated" if needed, and not after every find even if it is not used.

You could use Virtual Attributes . This is specifically designed to access altered variables. You can read more here

Inside the model you can make this function:

public function getShortDescription(){
        return substr($this->description, 0, 150);
}

You can also just add the variable at the top of the class:

public $shortDescription = substr($this->description, 0, 150);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM