Yii Crud generates ErrorException out of the box - php

My problem is similar (or identical ?) to this one. However, the solution offered there does not help me.
I used Gii tot generate a model (Guest) with a search model (GuestQuery). Then I used Gii to generate CRUD for these models. Gii generates the code successfully.
Then, a call to /guest/index results in the following error:
PHP Warning – yii\base\ErrorException
Invalid argument supplied for foreach()
1. in /home/fmivps/photosprint.app/kanematsu.app/vendor/yiisoft/yii2/BaseYii.php at line 520
511512513514515516517518519520521522523524525526527528529
/**
* 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)
{
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 /home/fmivps/photosprint.app/kanematsu.app/vendor/yiisoft/yii2/BaseYii.php at line 520 – yii\base\ErrorHandler::handleError(2, 'Invalid argument supplied for fo...', '/home/fmivps/photosprint.app/kan...', 520, ...)
3. in /home/fmivps/photosprint.app/kanematsu.app/vendor/yiisoft/yii2/base/Object.php at line 105 – yii\BaseYii::configure(app\models\generated\GuestQuery, 'app\models\generated\Guest')
4. in /home/fmivps/photosprint.app/kanematsu.app/models/generated/Guest.php at line 55 – yii\base\Object::__construct('app\models\generated\Guest')
495051525354555657
/**
* #inheritdoc
* #return GuestQuery the active query used by this AR class.
*/
public static function find()
{
return new GuestQuery(get_called_class());
}
}
5. in /home/fmivps/photosprint.app/kanematsu.app/models/generated/GuestQuery.php at line 44 – app\models\generated\Guest::find()
38394041424344454647484950
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Guest::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
6. in /home/fmivps/photosprint.app/kanematsu.app/controllers/GuestController.php at line 39 – app\models\generated\GuestQuery::search([])
33343536373839404142434445
* Lists all Guest models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new GuestQuery();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
7. app\controllers\GuestController::actionIndex()
It looks like php get_called_class() returns a string 'app\models\generated\Guest' That would be correct. Next, YiiBase wants to threat this string as an array. Which results in the above error.
How do I get this working?
I am running Yii 2.0.8 on php 7.0.6.
update: the models and controllers are as generated by Gii:
Guest.php
<?php
namespace app\models\generated;
use Yii;
class Guest extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'guest';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['created_at', 'remaining_prints'], 'integer'],
[['cookie_value'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'cookie_value' => Yii::t('app', 'Cookie Value'),
'created_at' => Yii::t('app', 'Created At'),
'remaining_prints' => Yii::t('app', 'Remaining Prints'),
];
}
/**
* #inheritdoc
* #return GuestQuery the active query used by this AR class.
*/
public static function find()
{
return new GuestQuery(get_called_class());
}
}
GuestQuery.php:
<?php
namespace app\models\generated;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\generated\Guest;
class GuestQuery extends Guest
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'created_at', 'remaining_prints'], 'integer'],
[['cookie_value'], '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 = Guest::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,
'remaining_prints' => $this->remaining_prints,
]);
$query->andFilterWhere(['like', 'cookie_value', $this->cookie_value]);
return $dataProvider;
}
}
GuestController.php:
/**
* Lists all Guest models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new GuestQuery();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

Related

YII2 gridview sort sum of values of two columns

I successfully displayed the 3 columns in the gridview. the attr1, attr2, and the sum of the 2 attributes. attr1 and attr2 are from the database and the 3rd column is their sum. How do I make the sorting and filtering work?
Here is the gridview.
[
'label' => 'Number of Enquiries',
'value' => function ($model) {
return $model->countEnquire + $model->countPhone + $model->countTrial;
},
'enableSorting' => true,
]
How add sorting for this column?
OK, I don't have your full source code to go by but can help with a basic example.
Ideally you should start by creating your model and CRUD files using Gii like I have for in my example below.
Here is my basic database table, record:
I added some test data:
Then I created the model and CRUD files using Gii, which I then modified to show you an example of the custom summing/sorting you wish to achieve. See below.
#app/models/Record.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "record".
*
* #property integer $record_id
* #property integer $attr1
* #property integer $attr2
* #property integer $sum
*/
class Record extends \yii\db\ActiveRecord
{
public $sum;
public function getSum()
{
$this->sum = 0;
if (is_numeric($this->attr1) && is_numeric($this->attr2)) {
$this->sum = $this->attr1 + $this->attr2;
}
return $this->sum;
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'record';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['record_id', 'attr1', 'attr2'], 'required'],
[['record_id', 'attr1', 'attr2', 'sum'], 'integer'],
[['sum'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'record_id' => 'Record ID',
'attr1' => 'Attr1',
'attr2' => 'Attr2',
'sum' => 'Sum',
];
}
/**
* #inheritdoc
* #return RecordQuery the active query used by this AR class.
*/
public static function find()
{
return new RecordQuery(get_called_class());
}
}
#app/models/RecordSearch.php
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Record;
/**
* RecordSearch represents the model behind the search form about `app\models\Record`.
*/
class RecordSearch extends Record
{
/**
* #inheritdoc
*/
public function attributes()
{
// add related fields to searchable attributes
return array_merge(parent::attributes(), ['sum']);
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['record_id', 'attr1', 'attr2', 'sum'], 'integer'],
[['sum'], '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)
{
// find records, additionally selecting the sum of the 2 fields as 'sum'
$query = Record::find()->select('*, (`attr1` + `attr2`) AS `sum`');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// enable sorting for the related columns
$dataProvider->sort->attributes['sum'] = [
'asc' => ['sum' => SORT_ASC],
'desc' => ['sum' => SORT_DESC],
];
$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([
'record_id' => $this->record_id,
'attr1' => $this->attr1,
'attr2' => $this->attr2,
]);
// if the sum has a numeric filter value set, apply the filter in the HAVING clause
if (is_numeric($this->sum)) {
$query->having([
'sum' => $this->sum,
]);
}
return $dataProvider;
}
}
#app/views/record/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel app\models\RecordSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Records';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="record-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Record', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'record_id',
'attr1',
'attr2',
'sum',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
I hope this helps!

on calling new created controller function it navigates to 404 error page

in yii2 advanced template site Controller is working fine. When calling a function in new controller it is navigating to 404 error page.
I created model using model generator and create a crude for the model.
This is my controller
namespace backend\Controllers;
use Yii;
use common\models\PackageTable;
use common\models\PackageTableSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PackageTableController implements the CRUD actions for PackageTable model.
*/
class PackageTableController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all PackageTable models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PackageTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single PackageTable model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new PackageTable model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new PackageTable();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->package_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing PackageTable model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->package_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing PackageTable model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the PackageTable model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return PackageTable the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = PackageTable::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
This is my model
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "package_table".
*
* #property integer $package_id
* #property string $package_name
* #property string $description
* #property integer $amount
* #property integer $status
* #property string $created_on
* #property string $updated_on
*/
class PackageTable extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'package_table';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['package_name', 'description', 'amount', 'status'], 'required'],
[['description'], 'string'],
[['amount', 'status'], 'integer'],
[['created_on', 'updated_on'], 'safe'],
[['package_name'], 'string', 'max' => 250],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'package_id' => 'Package ID',
'package_name' => 'Package Name',
'description' => 'Description',
'amount' => 'Amount',
'status' => 'Status',
'created_on' => 'Created On',
'updated_on' => 'Updated On',
];
}
}
This is my model search
<?php
namespace common\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\PackageTable;
/**
* PackageTableSearch represents the model behind the search form about `common\models\PackageTable`.
*/
class PackageTableSearch extends PackageTable
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['package_id', 'amount', 'status'], 'integer'],
[['package_name', 'description', 'created_on', 'updated_on'], '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 = PackageTable::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([
'package_id' => $this->package_id,
'amount' => $this->amount,
'status' => $this->status,
'created_on' => $this->created_on,
'updated_on' => $this->updated_on,
]);
$query->andFilterWhere(['like', 'package_name', $this->package_name])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
}
}
Although php namespaces are case-insensitive, autoloader in your case is likely case-sensitive.
At the top of your controller namespace mentioned as
namespace backend/Controllers;
but in advanced template all directories are in lower case. So try to change this line to
namespace backend/controllers;

How to Basic CRUD operation in many-to-many relation in Yii2?

Hello to everyone out there I am new to Yii2. I just started learning Yii2 and got stuck in a condition where i have to use CRUD operation in case where I am having many-to-many relation in the backend. I was trying to solve it but not able to understand how I can d this. Below I am writting the strcuture of my tables and the code.
Table
1. test_role
id->first column
role_name->second column
2. test_user
id->primary column
user_name
3.user_role
id->primary key
user_id ->foreign key(primary key of test_user)
role_id ->foreign key(primary key of test_role)
And there is many-to-many relation between roles and users means to say that a user can have multiple roles and a role can be assigned to multiple users.
Based on this i have created the following models.
Model 1 TestRolephp
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "test_role".
*
* #property integer $id
* #property string $role_name
*
* #property TestUserRole[] $testUserRoles
*/
class TestRole extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'test_role';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['role_name'], 'required'],
[['role_name'], 'string', 'max' => 200],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'role_name' => 'Role Name',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getTestUserRoles()
{
return $this->hasMany(TestUserRole::className(), ['role_id' => 'id']);
}
}
Model 2 TestUser.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "test_user".
*
* #property integer $id
* #property string $username
*
* #property TestUserRole[] $testUserRoles
*/
class TestUser extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'test_user';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['username'], 'required'],
[['username'], 'string', 'max' => 200],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getTestUserRoles()
{
return $this->hasMany(TestUserRole::className(), ['user_id' => 'id']);
}
}
Below are the controllers
Controller 1 TestUserController.php
<?php
namespace app\controllers;
use Yii;
use app\models\TestUser;
use app\models\TestUserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TestUserController implements the CRUD actions for TestUser model.
*/
class TestUserController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all TestUser models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new TestUserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single TestUser model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new TestUser model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new TestUser();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing TestUser model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing TestUser model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the TestUser model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return TestUser the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestUser::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Second Controller TestRoleController.php
<?php
namespace app\controllers;
use Yii;
use app\models\TestRole;
use app\models\search\TestRoleSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TestRoleController implements the CRUD actions for TestRole model.
*/
class TestRoleController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all TestRole models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new TestRoleSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single TestRole model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new TestRole model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new TestRole();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing TestRole model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing TestRole model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the TestRole model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return TestRole the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TestRole::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Now what I want that i want to insert data into both tables. I want that at the time creating new user all the list of roles should display having checkbox infront of each role and vice-versa. Any help can help me a lot.
My view file is ->create.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\TestUser */
$this->title = 'Create Test User';
$this->params['breadcrumbs'][] = ['label' => 'Test Users', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="test-user-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
And create action of TestUserController.php
public function actionCreate()
{
$user = new TestUser;
$role = new TestRole;
if($user->load(Yii::$app->request->post()) && $role->load(Yii::$app->request->post()) &&
$user->validate() && $role->validate())
{
$user->save(false);
$role->save(false);
$user->link('testRoles', $role); //add row in junction table
return $this->redirect(['index']);
}
return $this->render('create', compact('user', 'role'));
}
Add in TestRole model
public function getTestUsers(){
return $this->hasMany(TestUser::className(), ['id' => 'user_id'])
->viaTable(TestUserRole::tableName(), ['role_id' => 'id']);
}
Add in TestUser model
public function getTestRoles(){
return $this->hasMany(TestRole::className(), ['id' => 'role_id'])
->viaTable(TestUserRole::tableName(), ['user_id' => 'id']);
}
In controller, when save models
public function actionCreate(){
$user = new TestUser;
$role = new TestRole;
if($user->load(Yii::$app->request->post()) && $role->load(Yii::$app->request->post()) &&
$user->validate() && $role->validate()){
$user->save(false);
$role->save(false);
$user->link('testRoles', $role); //add row in junction table
return $this->redirect(['index']);
}
return $this->render('create', compact('user', 'role'));
}

Yii2 query result always returns the same

I am working on a Yii2 based project right now. Today when I was testing my application I noticed a very interesting bug in it. I have a Products table with it's model and controllers and views. (These are generated with gii)
When I list all the records in the index action it works fine. But here comes the bug. When I click on the edit or view action it alwasy renders the first record in the database. I was var_dump the result of the queries and always returnd the mentiond result. Only when I used createCommand got the proper result.
What do you think guys could be the problem with it?
The controller
<?php
namespace backend\controllers;
use Yii;
use app\models\Termek;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TermekController implements the CRUD actions for Termek model.
*/
class TermekController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Termek models.
* #return mixed
*/
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => Termek::find(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Termek model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model,
]);
}
/**
* Creates a new Termek model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Termek();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Termek model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Termek model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Termek model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Termek the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Termek::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
The index.php view file
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Termeks');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="termek-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Create Termek'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'nev',
'szelesseg',
'magassag',
'egyeb:ntext',
// 'ar',
// 'termek_kategoria_id',
// 'torolt',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Part of view.php view file:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'nev',
'szelesseg',
'magassag',
'egyeb:ntext',
'ar',
'termek_kategoria_id',
'torolt',
],
]) ?>
Model file:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "termek".
*
* #property integer $id
* #property string $nev
* #property double $szelesseg
* #property double $magassag
* #property string $egyeb
* #property string $ar
* #property integer $termek_kategoria_id
* #property string $torolt
*/
class Termek extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'termek';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['nev', 'termek_kategoria_id'], 'required'],
[['szelesseg', 'magassag'], 'number'],
[['egyeb'], 'string'],
[['ar', 'termek_kategoria_id'], 'integer'],
[['torolt'], 'safe'],
[['nev'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'nev' => Yii::t('app', 'Nev'),
'szelesseg' => Yii::t('app', 'Szelesseg'),
'magassag' => Yii::t('app', 'Magassag'),
'egyeb' => Yii::t('app', 'Egyeb'),
'ar' => Yii::t('app', 'Ar'),
'termek_kategoria_id' => Yii::t('app', 'Termek Kategoria ID'),
'torolt' => Yii::t('app', 'Torolt'),
];
}
/**
* #inheritdoc
* #return \app\models\Query\TermekQuery the active query used by this AR class.
*/
public static function find()
{
return new \app\models\Query\TermekQuery(get_called_class());
}
}
Try modify the findModel function using find()->where instead of findOne
protected function findModel($id)
{
var_dump($id);
$model = Termek::find()->where(['id'=> $id])->one();
var_dump($model);
if (($model !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
I am not sure why but somehow the error solved. I had a function in TermekQuery that was supposed to query all the records that has the deleted field null. I removed it and now works fine.

Yii2 Search model, Invalid argument supplied for foreach

I am new at Yii framework and I am facing this problem that when i am creating search model to add filters and sorting, it's not working, i already have tried this solution Yii2 ActiveDataProvider - Invalid argument supplied for foreach() and even generated the new models and controller but the result is same, it did not work.
Please have a look at the code and kindly tell me what i am doing wrong.
Controller
namespace backend\controllers;
use Yii;
use backend\models\Contacts;
use backend\models\ContactsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* ContactsController implements the CRUD actions for Contacts model.
*/
class ContactsController extends Controller
{
...
/**
* Lists all Contacts models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new ContactsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]);
}
...
}
Model
namespace backend\models;
use Yii;
use backend\models\User;
/**
* This is the model class for table "user_contacts".
*
* #property string $id
* #property string $user_id
* #property string $contact_id
* #property string $created_on
* #property string $modified_on
*
* #property User $contact
* #property User $user
*/
class Contacts extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user_contacts';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id', 'contact_id'], 'integer'],
[['created_on', 'modified_on'], 'safe'],
[['user_id', 'contact_id'], 'unique', 'targetAttribute' => ['user_id', 'contact_id'], 'message' => 'The combination of User ID and Contact ID has already been taken.']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'user_id' => Yii::t('app', 'User ID'),
'contact_id' => Yii::t('app', 'Contact ID'),
'created_on' => Yii::t('app', 'Created On'),
'modified_on' => Yii::t('app', 'Modified On')
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getContact()
{
return $this->hasOne(User::className(), ['id' => 'contact_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
/**
* #inheritdoc
* #return ContactsSearch the active query used by this AR class.
*/
public static function find()
{
return new ContactsSearch(get_called_class());
}
}
Search model
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Contacts;
/**
* ContactsSearch represents the model behind the search form about `backend\models\Contacts`.
*/
class ContactsSearch extends Contacts
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'user_id', 'contact_id'], 'integer'],
[['created_on', 'modified_on'], '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 = Contacts::find();
$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;
}
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'contact_id' => $this->contact_id,
'created_on' => $this->created_on,
'modified_on' => $this->modified_on
]);
return $dataProvider;
}
}
View(index.php)
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'user_id',
'contact_id',
'created_on',
'modified_on',
['class' => 'yii\grid\ActionColumn']
]
]);
Error
PHP Warning – yii\base\ErrorException
Invalid argument supplied for foreach()
1. in F:\Files\Web\PHP\wamp\www\Php\sites\expenses\vendor\yiisoft\yii2\BaseYii.php at line 517
public static function configure($object, $properties)
{
foreach ($properties as $name => $value) {
$object->$name = $value;
}
return $object;
}
2. in F:\Files\Web\PHP\wamp\www\Php\sites\expenses\backend\models\Contacts.php at line 76 – yii\base\Object::__construct()
public static function find()
{
return new ContactsSearch(get_called_class());
}
3. in F:\Files\Web\PHP\wamp\www\Php\sites\expenses\backend\models\ContactsSearch.php at line 43 – backend\models\Contacts::find()
public function search($params)
{
$query = Contacts::find();
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
$this->load($params);
...

Categories