phpyii2yii-widgets

Yii 2.0 Getting data from model without widget


Can anyone give me sample of how to retrieve data from model without having to use Widget ? Because need to get data per table column and put them inside my own view (not using widget)

Controller :

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

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
}

View :

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
            'sku',
            'name',
            'short_description',
            'long_description',
            'thumb_img:ntext',
            'large_img:ntext',
            'url_content:ntext',
             'contact_info',
             'status',
            'currency',
             'price',
            'dimension',
            'weight',
            // 'created',
            // 'modified',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

The widget above iterate through the element inside the predefined gridview, but what I want to do instead is something like :

foreach($data as $ab) {
   echo $ab->id;
}

Solution

  • You can do it this way:

    /* assuming $data is an ActiveDataProvider object */
    $models = $data->getModels(); 
    
    foreach($models as $model) { ... }
    

    see more here