Question: CGridView - How to override particular row's css ?

Hello everyone. I’m new to programming and very much interested in Yii.

I want to override particular columns back ground color should they meet particular requisitions. For example (this is not the actual case):

  • If the $data contains “porn” in one or more of its attributes, then change the respective row’s back ground color to red.

  • If the $data contains “kids” in one or more of its attributes, then change the respective row’s back ground color to green.

  • If the $data contains “action” in one or more of its attributes, then change the respective row’s back ground color to blue.

Could any one please direct me on how to accomplish this simple task? A brief example would be very much appreciated.

Thank you very much in advance. And yes, i want to learn Yii more.

inspired by this post

add a virtual property in your model




private $_background_color;


public function background_color(){

	//your logic here

	if (strlen(strstr($this->column1,'porn'))>0)

		$this->_background_color= 'red';

	elseif (strlen(strstr($this->column1,'kids'))>0)

		$this->_background_color= 'green';

	elseif (strlen(strstr($this->column1,'action'))>0)

		$this->_background_color= 'blue';

 

	return $this->_background_color;

}




in your view





<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id' => 'category-grid',

	'dataProvider' => $model->search(),

	'filter' => $model,

	'columns' => array(

		'id',

		array(

		    'name' => 'column1',

		    'cssClassExpression'=>'$data->background_color',

		),

	),

)); ?>






btw, i did not try myself. but it should work.

@rootbear:

Thanks for your helpful reply!

I’m trying this as soon as i get home. :)

EDIT:

I’ve tried the steps yesterday, but the forum forbid me to make more than 3 posts per day. And the result works perfect!.. Thanks a lot… ;)

I am attempting to modify the background color property based on a value being in a data field.

I have modified the protected\views\tickets\index.php file with the following;

private $_background_color;

public function background_color(){

    //your logic here


	&#036;this-&gt;_background_color = 'white';


    #if (strlen(strstr(.&#036;model-&gt;ack_username))&gt;0) &#036;this-&gt;_background_color= 'green';





    return &#036;this-&gt;_background_color;

)

even without calling the function I get an error. but my understanding is that I can add the

‘cssClassExpression’=>’$data->background_color’,

which would call the function and thereby set the background color for the row in my grid.

Am I doing something wrong here? I’m very new to Yii, so still getting to know it.