Problem with CRUD generated code in yii2

Good morning everyone, I am starting with yii2 and when generating a CRUD that goes against a table in postgresql BD, the result generates an error to make the corresponding call.
My configuration is: S.O. Debian 10, Apache 2 (2.4.38), Php 7.3, Yii2 (2.0.37), Postgresql 11.7.
The problem occurs once I create my model against my table in BD without problems, then I generate the CRUD in a satisfactory way, when entering my corresponding view it generates an error.

PHP Warning – yii\base\ErrorException

Invalid argument supplied for foreach()

I would be grateful for the help you can give me in this regard.

Hi @electronicajag, welcome to the forum.

We need more info to pin point the problem.
First off, could you show us the error message in details with a call stack? Then it would reveal us where the problematic code exists in CRUD (or in Model).

Thank you very much softark for answering.
The call is made through the url:

http://xxxx.com/index.php?r=usuarios

And the error on the page is the following:

1. in /var/www/ovsp/vendor/yiisoft/yii2/BaseYii.php at line 558
549550551552553554555556557558559560561562563564565566567

    /**
     * Configures an object with the initial property values.
     * @param object $object the object to be configured
     * @param array $properties the property initial values given in terms of name-value pairs.
     * @return object the object itself
     */
    public static function configure($object, $properties)
    {
//        if (is_array($properties) || is_object($properties)) {        
            foreach ($properties as $name => $value) {
                $object->$name = $value;
            }
//        } 
        return $object;
    }
 
    /**
     * Returns the public member variables of an object.
     * This method is provided such that we can get the public member variables of an object.

2. in /var/www/ovsp/vendor/yiisoft/yii2/BaseYii.php at line 558 – yii\web\ErrorHandler::handleError()
3. in /var/www/ovsp/vendor/yiisoft/yii2/base/BaseObject.php at line 107 – yii\BaseYii::configure()
4. in /var/www/ovsp/models/SistemaUsuarios.php at line 69 – app\models\SistemaUsuariosQuery::__construct()
636465666768697071

    /**
     * {@inheritdoc}
     * @return SistemaUsuariosQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new SistemaUsuariosQuery(get_called_class());
    }
}

5. in /var/www/ovsp/models/SistemaUsuariosQuery.php at line 43 – app\models\SistemaUsuarios::find()
37383940414243444546474849

     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = SistemaUsuarios::find();
 
        // add conditions that should always apply here
 
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

6. in /var/www/ovsp/controllers/UsuariosController.php at line 39 – app\models\SistemaUsuariosQuery::search()
33343536373839404142434445

     * Lists all SistemaUsuarios models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SistemaUsuariosQuery();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
 
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

7. in /var/www/ovsp/vendor/yiisoft/yii2/base/InlineAction.php at line 57 – app\controllers\UsuariosController::actionIndex()
8. in /var/www/ovsp/vendor/yiisoft/yii2/base/InlineAction.php at line 57 – call_user_func_array:{/var/www/ovsp/vendor/yiisoft/yii2/base/InlineAction.php:57}()
9. in /var/www/ovsp/vendor/yiisoft/yii2/base/Controller.php at line 180 – yii\base\InlineAction::runWithParams()
10. in /var/www/ovsp/vendor/yiisoft/yii2/base/Module.php at line 528 – app\controllers\UsuariosController::runAction()
11. in /var/www/ovsp/vendor/yiisoft/yii2/web/Application.php at line 103 – yii\web\Application::runAction()
12. in /var/www/ovsp/vendor/yiisoft/yii2/base/Application.php at line 386 – yii\web\Application::handleRequest()
13. in /var/www/ovsp/web/index.php at line 12 – yii\web\Application::run()
6789101112

 
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
 
$config = require __DIR__ . '/../config/web.php';
 
(new yii\web\Application($config))->run();

$_GET = [
‘r’ => ‘usuarios’,
];

$_COOKIE = [
‘PHPSESSID’ => ‘mvd2vuotefb0flg0crjeun6npp’,
‘_csrf’ => ‘a20368e0af736ad24114025c5fd270ec0132a24573f4ce6a894f6b069ee9f93da:2:{i:0;s:5:"_csrf";i:1;s:32:“aoRmOwVMetmR2eC4fgfMaKgoB2TeA8SE”;}’,
];

$_SESSION = [
‘__flash’ => [],
];

I have searched different forums including this one to no avail. The closest thing was the inclusion of an if to validate if it is an object or an arrangement, and what this achieves is to advance and present a failure elsewhere.
the code is:

model SistemaUsuarios

"<?php

namespace app\models;

use Yii;

/**

  • This is the model class for table “{{%sistema.usuarios}}”.

  • property int $id

  • property string $usuario

  • property string $clave

  • property string $correo

  • property string $created_on

  • property string|null $last_login
    /
    class SistemaUsuarios extends \yii\db\ActiveRecord
    {
    /
    *

    • {inheritdoc}
      */
      public static function tableName()
      {
      return ‘{{%sistema.usuarios}}’;
      }

    /**

    • {inheritdoc}
      */
      public function rules()
      {
      return [
      [[‘usuario’, ‘clave’, ‘correo’, ‘created_on’], ‘required’],
      [[‘created_on’, ‘last_login’], ‘safe’],
      [[‘usuario’, ‘clave’], ‘string’, ‘max’ => 50],
      [[‘correo’], ‘string’, ‘max’ => 255],
      [[‘correo’], ‘unique’],
      [[‘usuario’], ‘unique’],
      ];
      }

    /**

    • {inheritdoc}
      */
      public function attributeLabels()
      {
      return [
      ‘id’ => Yii::t(‘app’, ‘ID’),
      ‘usuario’ => Yii::t(‘app’, ‘Usuario’),
      ‘clave’ => Yii::t(‘app’, ‘Clave’),
      ‘correo’ => Yii::t(‘app’, ‘Correo’),
      ‘created_on’ => Yii::t(‘app’, ‘Created On’),
      ‘last_login’ => Yii::t(‘app’, ‘Last Login’),
      ];
      }

    /**

    • {inheritdoc}
    • return SistemaUsuariosQuery the active query used by this AR class.
      */
      public static function find()
      {
      return new SistemaUsuariosQuery(get_called_class());
      }
      }"

model SistemaUsuariosQuery

"<?php

namespace app\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\SistemaUsuarios;

/**

  • SistemaUsuariosQuery represents the model behind the search form of app\models\SistemaUsuarios.
    /
    class SistemaUsuariosQuery extends SistemaUsuarios
    {
    /
    *

    • {inheritdoc}
      */
      public function rules()
      {
      return [
      [[‘id’], ‘integer’],
      [[‘usuario’, ‘clave’, ‘correo’, ‘created_on’, ‘last_login’], ‘safe’],
      ];
      }

    /**

    • {inheritdoc}
      */
      public function scenarios()
      {
      // bypass scenarios() implementation in the parent class
      return Model::scenarios();
      }

    /**

    • Creates data provider instance with search query applied

    • param array $params

    • return ActiveDataProvider
      */
      public function search($params)
      {
      $query = SistemaUsuarios::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_on’ => $this->created_on,
      ‘last_login’ => $this->last_login,
      ]);

      $query->andFilterWhere([‘ilike’, ‘usuario’, $this->usuario])
      ->andFilterWhere([‘ilike’, ‘clave’, $this->clave])
      ->andFilterWhere([‘ilike’, ‘correo’, $this->correo]);

      return $dataProvider;
      }
      }"

Controller: UsuariosController

"<?php

namespace app\controllers;

use Yii;
use app\models\SistemaUsuarios;
use app\models\SistemaUsuariosQuery;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**

  • UsuariosController implements the CRUD actions for SistemaUsuarios model.
    /
    class UsuariosController extends Controller
    {
    /
    *

    • {inheritdoc}
      */
      public function behaviors()
      {
      return [
      ‘verbs’ => [
      ‘class’ => VerbFilter::className(),
      ‘actions’ => [
      ‘delete’ => [‘POST’],
      ],
      ],
      ];
      }

    /**

    • Lists all SistemaUsuarios models.

    • return mixed
      */
      public function actionIndex()
      {
      $searchModel = new SistemaUsuariosQuery();
      $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    /**

    • Displays a single SistemaUsuarios model.
    • param integer $id
    • return mixed
    • throws NotFoundHttpException if the model cannot be found
      */
      public function actionView($id)
      {
      return $this->render(‘view’, [
      ‘model’ => $this->findModel($id),
      ]);
      }

    /**

    • Creates a new SistemaUsuarios model.

    • If creation is successful, the browser will be redirected to the ‘view’ page.

    • return mixed
      */
      public function actionCreate()
      {
      $model = new SistemaUsuarios();

      if ($model->load(Yii::$app->request->post()) && $model->save()) {
      return $this->redirect([‘view’, ‘id’ => $model->id]);
      }

      return $this->render(‘create’, [
      ‘model’ => $model,
      ]);
      }

    /**

    • Updates an existing SistemaUsuarios model.

    • If update is successful, the browser will be redirected to the ‘view’ page.

    • param integer $id

    • return mixed

    • throws NotFoundHttpException if the model cannot be found
      */
      public function actionUpdate($id)
      {
      $model = $this->findModel($id);

      if ($model->load(Yii::$app->request->post()) && $model->save()) {
      return $this->redirect([‘view’, ‘id’ => $model->id]);
      }

      return $this->render(‘update’, [
      ‘model’ => $model,
      ]);
      }

    /**

    • Deletes an existing SistemaUsuarios model.

    • If deletion is successful, the browser will be redirected to the ‘index’ page.

    • param integer $id

    • return mixed

    • throws NotFoundHttpException if the model cannot be found
      */
      public function actionDelete($id)
      {
      $this->findModel($id)->delete();

      return $this->redirect([‘index’]);
      }

    /**

    • Finds the SistemaUsuarios model based on its primary key value.

    • If the model is not found, a 404 HTTP exception will be thrown.

    • param integer $id

    • return SistemaUsuarios the loaded model

    • throws NotFoundHttpException if the model cannot be found
      */
      protected function findModel($id)
      {
      if (($model = SistemaUsuarios::findOne($id)) !== null) {
      return $model;
      }

      throw new NotFoundHttpException(Yii::t(‘app’, ‘The requested page does not exist.’));
      }
      }"

views: usuarios/index

" <?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* var $this yii\web\View */
/* var $searchModel app\models\SistemaUsuariosQuery */
/* var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Sistema Usuarios');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="sistema-usuarios-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Create Sistema Usuarios'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?php Pjax::begin(); ?>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

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

            'id',
            'usuario',
            'clave',
            'correo',
            'created_on',
            //'last_login',

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

    <?php Pjax::end(); ?>

</div>"

SistemaUsariosQuery should extends ActiveQuery, not SistemaUsarios (i.e., ActiveRecord).

Try to re-generate SistemaUarios and SistemaUsariosQuery using Gii’s model generator. Remember to set check on “Generate ActiveQuery” and be careful not to change “ActiveQuery Base Class” which should be “yii\db\ActiveQuery”.

And then try the CRUD generator once again. Note that “Search Model Class” must not be “SistemaUsariosQuery” or any other existing class. Because it is to be generated anew with CRUD generator, the name of it should be “SistemaUsariosSearch” or something like that.

I hope it will solve the problem.

1 Like

Hello, thank you very much for the help raised, of course help is always welcome and brings new knowledge, for which I thank you infinitely.

I had thought about this option, however it also generates an error, which I dismissed it, since the code that I placed before is the generator for the Gii module, which for me had more weight when deciding which one to continue fighting with. .

In none of the screens change the extension options or anything similar. I generated the crud with the default values, including the class and file names to avoid inconvenience.

I followed his recommendation, obtaining in this case a new error which I attached below:

ArgumentCountError
Too few arguments to function yii\db\ActiveQuery::__construct(), 0 passed in /var/www/ovsp/controllers/UsuariosController.php on line 38 and at least 1 expected

1. in /var/www/ovsp/vendor/yiisoft/yii2/db/ActiveQuery.php at line 107

     */
    public $joinWith;
 
 
    /**
     * Constructor.
     * param string $modelClass the model class associated with this query
     * param array $config configurations to be applied to the newly created query object
     */
    public function __construct($modelClass, $config = [])
    {
        $this->modelClass = $modelClass;
        parent::__construct($config);
    }
 
    /**
     * Initializes the object.
     * This method is called at the end of the constructor. The default implementation will trigger
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end

2. in /var/www/ovsp/controllers/UsuariosController.php at line 38 – yii\db\ActiveQuery::__construct()

    /**
     * Lists all SistemaUsuarios models.
     * return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SistemaUsuariosQuery();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
 
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

3. app\controllers\UsuariosController::actionIndex()
4. in /var/www/ovsp/vendor/yiisoft/yii2/base/InlineAction.php at line 57 – call_user_func_array([app\controllers\UsuariosController, 'actionIndex'], [])
5. in /var/www/ovsp/vendor/yiisoft/yii2/base/Controller.php at line 180 – yii\base\InlineAction::runWithParams(['r' => 'usuarios'])
6. in /var/www/ovsp/vendor/yiisoft/yii2/base/Module.php at line 528 – yii\base\Controller::runAction('', ['r' => 'usuarios'])
7. in /var/www/ovsp/vendor/yiisoft/yii2/web/Application.php at line 103 – yii\base\Module::runAction('usuarios', ['r' => 'usuarios'])
8. in /var/www/ovsp/vendor/yiisoft/yii2/base/Application.php at line 386 – yii\web\Application::handleRequest(yii\web\Request)
9. in /var/www/ovsp/web/index.php at line 12 – yii\base\Application::run()

 
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
 
$config = require __DIR__ . '/../config/web.php';
 
(new yii\web\Application($config))->run();

The code of my class was this way:

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use app\models\SistemaUsuarios;

/**

  • SistemaUsuariosQuery represents the model behind the search form of app\models\SistemaUsuarios.
    /
    class SistemaUsuariosQuery extends ActiveQuery
    {
    /
    *
    • {inheritdoc}
      */
      public function rules()
      {
      return [

Thank you very much for the help you can give me and I apologize for the inconvenience.

Good afternoon colleagues, Thank you so much for your help. indeed the problem was as well said. “I can’t make the lookup class the Query class automatically generated by the model generator.” For this reason in the generation of the CRUD the search class calls it SistemaUsuarioSearch following its recommendation.

Thank you very much for your time and support. Always at your service in this way.

PROBLEM SOLVED.