Hi.
I have created a custom yii\grid\DataColumn
used to display customized data. I use this both with standard and Kartik’s gridview, but the latter uses more methods and functions, so if I’m using it the constructor fails… I either use two classes for the two DataColumns, or can I use Dependency Injection? This means I should create my DataColumn as a standard object, and instantiate the parent DataColumn class from config parameters. I tried implementing something like this, a stub is below, but it didn’t work as expected. The DataColumn class didn’t have access to $this->view
.
I’m going to implement this a formatter, but for learning purposes, how can this be accomplished using D-I? thanks
<?php
namespace yetopen\helpers\components;
use kartik\base\Config;
use yii\base\BaseObject;
use yii\base\InvalidCallException;
use yii\base\UnknownPropertyException;
use yii\grid\DataColumn;
class JsonArrayDataColumn extends BaseObject
{
public $dataColumnClass = DataColumn::class;
public $separator = ', ';
public function __construct($config = [])
{
parent::__construct($config);
$this->_dataColumn = \Yii::createObject($this->dataColumnClass, $config);
}
public function __get($name)
{
try {
return parent::__get($name);
}catch (InvalidCallException $exception) {
return $this->_dataColumn->__get($name);
}
}
public function __set($name, $v)
{
try {
return parent::__set($name, $v);
}catch (InvalidCallException $exception) {
return $this->_dataColumn->__set($name, $v);
}
}
public function __call($name, $params)
{
if (method_exists($this, $name)) {
return $this->$name();
}
return $this->_dataColumn->$name();
}
/**
* Returns the data cell value.
* @param mixed $model the data model
* @param mixed $key the key associated with the data model
* @param int $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]].
* @return string the data cell value
*/
public function getDataCellValue($model, $key, $index)
{
$value = parent::getDataCellValue($model, $key, $index);
if ($value) {
return implode($this->separator, $value);
}
return null;
}
}