Search code examples
jsonmodel-view-controlleryii2modelsdataprovider

Data form models is not shown in controller even if exist (Yii 2.0.6)


I have this peace of code in my controller where I want to echo on the screen the JSON result for the data in the model:

public function actionIndex()
{
    $searchModel = new TestTableSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    var_dump($dataProvider->getModels());

    echo json_encode([
        "searchModel" => $searchModel,
        "getCount" => $dataProvider->getCount(),
        "dataProvider" => $dataProvider->models
    ]);
} 

So $dataProvider actually is not empty and it contains the data (which can be seen from var_dump() command), but the data are not returned as I'm expecting.

Even $dataProvider->getCount() is returning that there are two entries. This is the output that I got: http://prntscr.com/8hcel9.

I'm interested in showing the dataProvider part, where the items in array should not be empty.


Solution

  • You need to convert the object to array

    try this way :

    use yii\helpers\ArrayHelper;
    
    ......
    public function actionIndex()
    {
        $searchModel = new TestTableSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
        var_dump($dataProvider->getModels());
    
        echo json_encode([
            "searchModel" => $searchModel,
            "getCount" => $dataProvider->getCount(),
            "dataProvider" => ArrayHelper::toArray($dataProvider->models),  // object to Array 
       ]);
    }