Blog Image

Yii2 how to set custom value for checkbox in gridview widget

In Yii2, while you use gridview widget to display your table data, for performing any operation on the record by selecting the checkbox, gridview assign the value of the first column retrieved from your the result set.

But you need to set some different value to the checkbox, so to do that you can use the below code

GridView::widget([
	'dataProvider' => $dataProvider,
	'filterModel' => $searchModel,
	'columns' => [
		['class' => 'yii\grid\SerialColumn'],
		[
			'class' => '\kartik\grid\CheckboxColumn',
			'checkboxOptions' => function($model, $key, $index, $widget) {
				return ["value" => $model['id']]; // this can be substituted with any column value of your result data
			},
		],
		'name',
		['class' => 'yii\grid\ActionColumn'],
	],
]);

instead of the default one

GridView::widget([
	'dataProvider' => $dataProvider,
	'filterModel' => $searchModel,
	'columns' => [
		['class' => 'yii\grid\SerialColumn'],
		[
			'class' => '\kartik\grid\CheckboxColumn',
			'mergeHeader'=>false
		],
		'name',
		['class' => 'yii\grid\ActionColumn'],
	],
]);



Author: admin

Vinod Ram has been in Software Industry since 2006 and has experience of over 16 years in Software Development & Project Management domain specialised majorly in LAMP stack & Open Source Technology, building enterprise level Web based Application, Large Database driven and huge traffic Websites and Project Management. He loves to write information articles and blog to share his knowledge and experience with the outside world and help people to find solution for their problems.