GridView and two columns as one

Let’s take this case for example: there are two related models (Reader and Book). Every Reader can have many Books. Reader model has, besides others, these two attributes - firstName and lastName.

How would you display column, in Book model view files, using GridView, that represent Reader full name? (column with concatenated data from columns firstName and lastName)

When you define GridView columns just add a new column name (let’s say readerFullName). In Book model class add a new method called “getReaderFullName” similar to this one:

    public function getreaderFullName(){

        return sprintf('%s %s', $this->reader->name, $this->reader->surname);


This way, you will hava a "Full Name" column with concatenated reader name and surname. If you want to change column label you can add "readerFullName" array entry to attributeLabels methods in Book model.

I don’t know if this is the best way but it works. I’m new to yii… just 2 weeks working on it :wink:

PS: I assume you have defined book and reader relation. reader attribute in Book model represents this Book-Reader relation