Wednesday, August 17, 2011

Formatting Yii's CGridView Can be a Bit Tricky

First, an example:


<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'news-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'type',
'title',
array(
'name'=>'content',
'type'=>'ntext',
),
'release_date',
array(
'name'=>'external_link',
'type'=>'url',
),
array(
'type'=>'image',
'value'=>'$data->image->getImgSrc()',
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>

This is part of an admin section for a site, so I've included Yii's CButtonColumn.

This is similar to my previous post on CDetailView. I'll try not to repeat myself.

Primary points of interest:

  • Individual models are referred to as $data. This is "automagically" done by Yii. It's the variable CGridView provides. You must use it if you want to access that model for anything fancy.
  • Most of the things I'm trying to display, here, are attributes belonging to the main model. I don't need to use $data to get the content, for example. All I have to do is include 'content' in the output. Because I wanted to format content using the ntext formatter, I had to use an array to tell CGridView to include 'content' and to format as 'ntext.' (See above. You'll get it.)
  • I have a method for getting the image source of a related Image model. I used eager loading to give myself access to $data->image, so now I can call the Image method, getImgSrc(). Important: the whole expression to be evaluated is surrounded by quotes! That's necessary. Even though I'm using single quotes, Yii will evaluate it rather than render it as a literal. Trust me.


That's it!

No comments:

Post a Comment