0

I am getting Invalid argument supplied for foreach() error when I call project/index controller. What seems to be the problem?

This is the search in the model:

 public function search($params)
    {
        $query = Projects::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;

Controller:

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

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

View file:

<div class="projects-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Projects', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'filterPosition' => 'header',
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'name',
            'description:ntext',
            'created_at:date',
            'updated_at:date',

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

</div>
Sasha
  • 8,521
  • 23
  • 91
  • 174
  • 1
    You named ProjectQuery yii2 normally name ProjectSearch – ScaisEdge Sep 22 '15 at 18:12
  • @scaisEdge is right. You need to use ProjectSearch instead (if already built with Gii) which has a Search method that returns an activeDataProvider instance. This is what the ActiveQuery is for : http://stackoverflow.com/questions/31948917/yii2-activequery-example-and-what-is-the-reason-to-generate-activequery-class/31950149#31950149 – Salem Ouerdani Sep 23 '15 at 22:49

1 Answers1

0

Try using

public function actionIndex()
{
    $searchModel  = new ProjectsSearch();

Instead of

$searchModel  = new ProjectsQuery();
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107