Yii2 在Yi2 ArrayDataProvider中使用闭包
在ActiveDataProvider中,可以使用闭包作为值,如:Yii2 在Yi2 ArrayDataProvider中使用闭包,yii2,dataprovider,Yii2,Dataprovider,在ActiveDataProvider中,可以使用闭包作为值,如: $dataprovider = new ArrayDataProvider([ 'allModels' => $array ]); $gridColumns = [ 'attrib_1', [ 'attribute' => 'attrib_2', 'label' => 'Label_2', 'value' => function($
$dataprovider = new ArrayDataProvider([
'allModels' => $array
]);
$gridColumns = [
'attrib_1',
[
'attribute' => 'attrib_2',
'label' => 'Label_2',
'value' => function($model) {
return Html::encode($model->value_2);
}
],
'attrib_3'
];
echo GridView::widget([
'dataProvider'=> $dataprovider,
'columns' => $gridColumns
]);
是否可以在阵列数据提供程序中执行相同或类似操作?是。唯一的区别是$model不是对象而是数组,因此:
'value' => function($model) {
return Html::encode($model['value_2']);
}
为此,我创建了ActiveDataProvider的扩展版本,对于从提供程序获得的每个模型,我都调用回调
<?php
namespace common\components;
class CustomActiveDataProvider extends \yii\data\ActiveDataProvider
{
public $formatModelOutput = null;
public function getModels()
{
$inputModels = parent::getModels();
$outputModels = [];
if($this->formatModelOutput != null)
{
for($k=0;$k<count($inputModels);$k++)
{
$outputModels[] = call_user_func( $this->formatModelOutput, $k , $inputModels[$k]);
}
}
else
{
$outputModels = $inputModels;
}
return $outputModels;
}
}
public function getDataModelPerActiveProvider()
{
$this->id = 1;
// here you can customize other fields
// OR you can also return a custom array, for example:
// return ['field1' => 'test', 'field2' => 'foo', 'field3' => $this->id];
return $this;
}
非常感谢。我想,没有模型,因为数据提供者是基于一个自己创建的数组。谢谢!我也要试试这个!
public function getDataModelPerActiveProvider()
{
$this->id = 1;
// here you can customize other fields
// OR you can also return a custom array, for example:
// return ['field1' => 'test', 'field2' => 'foo', 'field3' => $this->id];
return $this;
}