Your own Grid columns in the Yii2 framework

Your own Grid columns in the Yii2 framework

Continuing to expand my knowledge of Yii2.

I had, of course, heard about custom columns in Grid, but hadn’t used them in practice. However, when code duplication reached 5 separate places, I thought — why not give it a try? And it turned out to be quite nice, convenient, and most importantly — flexible!

Below is the full code listing of a sample column class that extends DataColumn:

namespace backendgrid;

use Yii;
use yiihelpersHtml;
use yiigridDataColumn;

class ActiveColumn extends DataColumn
{
	public $headerOptions = [
		'style' => 'width: 80px;'
	];
	
	public $contentOptions = [
		'class' => 'text-center'
	];
	
	public $attribute = 'is_active';
	
    /**
     * @inheritdoc
     */
    protected function renderDataCellContent($a)
    {
		if($a['is_active'] == 1)
		{
			return Html::a('<span class="glyphicon glyphicon-ok-circle"></span>', [
					'active', 'id' => $a['id'], 'is_active' => 0], [
					'title' => Yii::t('app', 'Unactivate this'),
					'data-pjax' => '0',
				]
			);
		}
		return Html::a('<span class="glyphicon glyphicon-lock"></span>', [
				'active', 'id' => $a['id'], 'is_active' => 1], [
				'title' => Yii::t('app', 'Activate this'),
				'data-pjax' => '0',
			]
		);
    }
}

I’m sure anyone who has worked at least once with GridView in Yii is familiar with some of the parameters. But I want to highlight this one:

public $attribute = 'is_active';

It defines the name of the database field used for retrieving the label from the model and enables sorting when clicking the column header in the table.

How to use it? Simple — in GridView, specify the name of our class, and optionally provide parameters if needed:

...
echo GridView::widget([
	'dataProvider' => $dataProvider,
	'columns' => [

		['class' => ActiveColumn::className()],
		
	],
]);
...

Are you having problems with your Yii2 framework website? Do you need additional functionality?
>Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *