Yii - CGridView row formatting

Do you want some advanced styling on your CGridView rows?

To individually style each row of your CGridView you can use the rowCssClassExpression property. However, the first thing that you will notice is that your ODD and EVEN formatting disappears.  That is because the rowCssClassExpression overwrites any internal defaults. If you want to retain this or include other complex formatting rules, it can get a bit confusing trying to get everything to fit inside a quoted string.  For example:- 'rowCssClassExpression'=>'($row%2)? "even ".str_replace(","," ",$data->flags) : "odd ".str_replace(","," ",$data->flags)'; And this is relatively simple.  What if I wanted to check the value of other fields as well ... perhaps something like this:- function () { $ret=($row%2)? "even" : "odd"; if ($e=='B') $ret.=' BK'; if ($e=='P') $ret.=' PR'; if (strpos($f,'UNREAD',0)>-1) $ret.=' UNREAD'; return $ret; } This could return a string like "ODD PR UNREAD"

Creating a Component

The best way I've found so far, is to create a really simple component with a function that returns the list of classes that you want to add. 1.  create a file ERowClass in your protected/components directory 2. Add code similar to the following class ERowClass { public function rowClass($row, $e, $f) { $ret=($row%2)? "even" : "odd"; if ($e=='B') $ret.=' BK'; if ($e=='P') $ret.=' PR'; if (strpos($f,'UNREAD',0)>-1) $ret.=' UNREAD'; return $ret; } } ?> 3. Call this component from your rowCssClassExpression $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'email-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'rowCssClassExpression'=>'ERowClass::rowClass($row,$data->entity_type,$data->flags);', 'columns'=>array( .... ), 4. Make sure that the component is loaded in your config/main.php 'import'=>array( 'application.models.*', 'application.components.*', 'application.helpers.*', ... ),

Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...


Leave a Comment

twitterfacebookgooglelinkedin https://me.yahoo.com