Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created March 31, 2014 10:20
Show Gist options
  • Save umidjons/9889371 to your computer and use it in GitHub Desktop.
Save umidjons/9889371 to your computer and use it in GitHub Desktop.
Yii: Add additional `data-` attributes to each row in `CGridView`

Add additional data- attributes to each row in CGridView

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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment