Sometimes we need to hold some values from model in data- attributes of tag. But we can't use $data special variable in cell's htmlOptions attributes. Instead of holding data in cell, we can generate data- attributes for rows (tr). For this purpose CGridView has special attribute rowHtmlOptionsExpression.
<?php
$this->widget( 'zii.widgets.grid.CGridView',
[
'id' => 'my-grid',
'dataProvider' => $model->search(),
'filter' => null,
'itemsCssClass' => 'table table-striped table-hover table-condensed',
'template' => '{items}{pager}',
'columns' =>
[
[
'name' => 'id',
'htmlOptions' => [ 'class' => 'id' ],
],
[
'name' => 'animal_class',
'value' => 'AnimalClass::visualValues( $data->animal_class )', // class name, not class ID
'htmlOptions' => [ 'class' => 'animal-class', ],
],
[
'name' => 'title',
'htmlOptions' => [ 'class' => 'title' ],
],
],
'rowHtmlOptionsExpression' => '[ "data-animalclass" => $data->animal_class, ]', // <tr data-animalclass = "123">
] );Access data-animalclass property using jQuery.
// $(this) - clicked link in the row or, for example, button in the CButtonColumn.
var row=$(this).closest('tr'),
animalClassID=row.data('animalclass');
console.log('Animal class ID:', animalClassID);