2

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;
}
Karate_Dog
  • 1,265
  • 5
  • 20
  • 37

2 Answers2

3

You can do it this way:

/* assuming $data is an ActiveDataProvider object */
$models = $data->getModels(); 

foreach($models as $model) { ... }

see more here

apoq
  • 1,454
  • 13
  • 14
2

If you are using an ActiveDataProvider: Controller:

public function actionMyAction()
{
    $dataProvider = new ActiveDataProvider([
        'query' => MyModel::find(),
    ]);

    return $this->render('my-results-page', [
        'dataProvider' => $dataProvider,
    ]);
}

View:

 <?php
  foreach ($dataProvider->models as $model){
            echo $model->myProperty;
        }  
 ?>

If you are using a query, such as this:

    $query = (new \yii\db\Query())
        ->select('this, that')
        ->from('over_there');
    $command = $query->createCommand();
    $rows = $command->queryAll();

Then you can iterate over the result like this(assuming you passed it to the view in a variable called $dataProvider):

  foreach($dataProvider as $data)
  {            
   $data['myProperty'];
  }
NovaLogic
  • 658
  • 13
  • 21