DarkwaveMD
DarkwaveMD

Reputation: 31

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 .

Upvotes: 3

Views: 7705

Answers (3)

Highmastdon
Highmastdon

Reputation: 7520

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);

Upvotes: 0

EdanB
EdanB

Reputation: 1486

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.

Upvotes: 4

sadaf
sadaf

Reputation: 739

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);
}

Upvotes: 6

Related Questions