Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Yii2 在Yi2 ArrayDataProvider中使用闭包_Yii2_Dataprovider - Fatal编程技术网

Yii2 在Yi2 ArrayDataProvider中使用闭包

Yii2 在Yi2 ArrayDataProvider中使用闭包,yii2,dataprovider,Yii2,Dataprovider,在ActiveDataProvider中,可以使用闭包作为值,如: $dataprovider = new ArrayDataProvider([ 'allModels' => $array ]); $gridColumns = [ 'attrib_1', [ 'attribute' => 'attrib_2', 'label' => 'Label_2', 'value' => function($

ActiveDataProvider中,可以使用闭包作为值,如:

$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的扩展版本,对于从提供程序获得的每个模型,我都调用回调

  • 这是自定义ActiveDataProvider,在本例中放在common\components命名空间中

    <?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;
    }
    }
    
  • 最后,这是模型中的getDataModelPerActiveProvider方法:

    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;
    }