CGridView::rowCssStyleExpression - a little improvement suggestion

Hello.

CGridView’s property “rowCssClassExpression” can evaluate css class while rendering.

Sometimes it’s useful to evaluate css style, not class.

Like this:


$this->widget('MyGridView', array(

  ...

  'rowCssStyleExpression' => '$data->login == "admin" ? "background-color:#FFC4D3;" : ""',

  ...

));


<?php


Yii::import('zii.widgets.grid.CGridView');


class MyGridView extends CGridView {


  /**

   * @var string a PHP expression that is evaluated for every table body row and whose result

   * is used as the CSS style for the row. In this expression, the variable <code>$row</code>

   * stands for the row number (zero-based), <code>$data</code> is the data model associated with

   * the row, and <code>$this</code> is the grid object.

   */

  public $rowCssStyleExpression;


  /**

   * Renders a table body row.

   * @param integer $row the row number (zero-based).

   */

  public function renderTableRow($row) {


    $data = $this->dataProvider->data[$row];


    $rowClass = '';

    if ($this->rowCssClassExpression !== null) {

      $rowClass = $this->evaluateExpression($this->rowCssClassExpression, array('row' => $row, 'data' => $data));

    }

    else if (is_array($this->rowCssClass) && ($n = count($this->rowCssClass)) > 0) {

      $rowClass = $this->rowCssClass[$row % $n];

    }


    $rowStyle = '';

    if ($this->rowCssStyleExpression !== null) {

      $rowStyle = $this->evaluateExpression($this->rowCssStyleExpression, array('row' => $row, 'data' => $data));

    }


    $rowAttributes = '';

    if ($rowClass) {

      $rowAttributes .= ' class="'.$rowClass.'" ';

    }

    if ($rowStyle) {

      $rowAttributes .= ' style="'.$rowStyle.'" ';

    }


    echo '<tr '.$rowAttributes.'>';


    foreach ($this->columns as $column) {

      $column->renderDataCell($row);

    }


    echo "</tr>\n";

    

  }


}

Why is that useful over a css class/id ?

Using a css class is so much more DRY and object oriented than hardcoding a style.

IMO.

For example, when color is data field.

Or you need some temp highlighting and you dont want to propagate css classes.

You can pass htmlOptions to a column:


                	'htmlOptions'=>array('width'=>'6%','class'=>'progress'),

Another example:


                	'htmlOptions'=>array('width'=>'6%','class'=>Helper::classFromFieldName($data->name)),

And I believe you can also just pass a ‘style’ argument in the htmlOptions array, although I’ve never had the need to try it. :)

I just feel such a feature would be redundant.

<edit>

Judging from your new topic, I guess you are on to that solution already. ;)

</edit>

Thanks for your replies :)

Yes, you can. But it will be a static style (not evaluated while rendering). Besides it will be applied for a single column only, not for a whole row.