DataColumn

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',
			]
		);
    }
}

read more...