Adding a new field to a model class using the Yii structure

In the table I have a description of the column containing a description of the goods. I want to include 'short_description' in the CGridView column, which will contain the 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.

+3
source share
3 answers

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

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

in the afterFind function.

You need to do something like this

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

Another option is to define a function

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

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

, "", , , .

+4

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

Inside the model, you can execute this function:

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

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

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

Source: https://habr.com/ru/post/1792217/


All Articles