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);
...
Related
I got the users in the equipments view by foreign key, but i can't assign an equipment for a user. I can assign it only to the unique ID from users table.I would also want to be possible to search by user in the equipment view.
If there are any suggestions how to modify this I appreciate very much.
First table : user_id - primary key, username, password ;
Second table: user_equip_id - primary key, phone_model, phone_model_series, phone_date_acq, nb_sg_model, nb_sg,_date_acq, display_model, display_series, display_date_acq, user_for_id - foreign key to user_id from table1
Controller :
<?php
namespace app\controllers;
use Yii;
use app\models\Equipment;
use app\models\EquipmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* EquipmentController implements the CRUD actions for Equipment model.
*/
class EquipmentController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Equipment models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Equipment 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 Equipment model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Equipment();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->user_equip_id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Equipment 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->user_equip_id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Equipment 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 Equipment model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Equipment the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Equipment::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "equipment".
*
* #property int $user_equip_id
* #property string|null $phone_model
* #property string $phone_series
* #property string $phone_date_acq
* #property string $nb_sg_model
* #property string $nb_sg_series
* #property string $nb_sg_date_acq
* #property string $display_model
* #property string $display_series
* #property string $display_date_acq
* #property int $user_for_id
*
* #property User $userFor
*/
class Equipment extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'equipment';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['phone_series', 'phone_date_acq', 'nb_sg_model', 'nb_sg_series', 'nb_sg_date_acq', 'display_model', 'display_series', 'display_date_acq', 'user_for_id'], 'required'],
[['phone_date_acq', 'nb_sg_date_acq', 'display_date_acq'], 'safe'],
[['user_for_id'], 'integer'],
[['phone_model', 'phone_series', 'nb_sg_model', 'nb_sg_series', 'display_model', 'display_series'], 'string', 'max' => 50],
[['user_for_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_for_id' => 'user_id']],
//[['username'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['username' => 'username']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'user_equip_id' => 'User Equip ID',
'phone_model' => 'Phone Model',
'phone_series' => 'Phone Series',
'phone_date_acq' => 'Phone Date Acq',
'nb_sg_model' => 'Nb Sg Model',
'nb_sg_series' => 'Nb Sg Series',
'nb_sg_date_acq' => 'Nb Sg Date Acq',
'display_model' => 'Display Model',
'display_series' => 'Display Series',
'display_date_acq' => 'Display Date Acq',
'user_for_id' => 'User For ID',
'username' => 'Username',
];
}
/**
* Gets query for [[UserFor]].
*
* #return \yii\db\ActiveQuery|yii\db\ActiveQuery
*/
public function getUserFor()
{
return $this->hasOne(User::className(), ['user_id' => 'user_for_id']);
}
//public function getUsername()
//{
// print_r($equipment->userFor->username);die;
// }
/**
* {#inheritdoc}
* #return EquipmentQuery the active query used by this AR class.
*/
public static function find()
{
return new EquipmentQuery(get_called_class());
}
}
View :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\EquipmentSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Equipments';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="equipment-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create Equipment', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
#['class' => 'yii\grid\SerialColumn'],
#'username',
#'user_equip_id',
'userFor.username',
'phone_model',
'phone_series',
'phone_date_acq',
'nb_sg_model',
'nb_sg_series',
'nb_sg_date_acq',
'display_model',
'display_series',
'display_date_acq',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Equipment Search:
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Equipment;
/**
* EquipmentSearch represents the model behind the search form of `app\models\Equipment`.
*/
class EquipmentSearch extends Equipment
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_equip_id', 'user_for_id'], 'integer'],
[['phone_model', 'phone_series', 'phone_date_acq', 'nb_sg_model', 'nb_sg_series', 'nb_sg_date_acq', 'display_model', 'display_series', 'display_date_acq'], '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 = Equipment::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([
'user_equip_id' => $this->user_equip_id,
'phone_date_acq' => $this->phone_date_acq,
'nb_sg_date_acq' => $this->nb_sg_date_acq,
'display_date_acq' => $this->display_date_acq,
'user_for_id' => $this->user_for_id,
]);
$query->andFilterWhere(['like', 'phone_model', $this->phone_model])
->andFilterWhere(['like', 'phone_series', $this->phone_series])
->andFilterWhere(['like', 'nb_sg_model', $this->nb_sg_model])
->andFilterWhere(['like', 'nb_sg_series', $this->nb_sg_series])
->andFilterWhere(['like', 'display_model', $this->display_model])
->andFilterWhere(['like', 'display_series', $this->display_series]);
return $dataProvider;
}
}
Thank you very much for any suggestions how to get there.
I have users table containing : PK - id, username, password.
i have three tables ( laptop, display, phone) - id - FK, series, model
I have userequipmentmapping table containing : id - PK , user_id - FK( id from users table), laptop_id - FK (id from laptop table), phone_id - FK (id from phone table), display_id(id from dislpay table), start_date, end_date.
I want to search by user in my gridview from UserEquipmentMapping, but don't know where should i implement the search model, considering the username is passed from the users table by foreign key.
If you have any suggestions are appreciated. Thank You in advance !
Controller :
<?php
namespace app\controllers;
use Yii;
use app\models\UserEquipmentMapping;
use app\models\UserequipmentmappingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\Laptop;
use app\models\Phone;
use app\models\Display;
/**
* UserequipmentmappingController implements the CRUD actions for UserEquipmentMapping model.
*/
class UserequipmentmappingController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserEquipmentMapping models.
* #return mixed
*/
public function actionIndex()
{
$usermodel = new UserEquipmentMapping();
$userquery = $usermodel->getUsers();
$displaymodel = new UserEquipmentMapping();
$displayquery = $displaymodel->getDisplays();
$phonemodel = new UserEquipmentMapping();
$phonequery = $phonemodel->getPhones();
$laptopmodel = new UserEquipmentMapping();
$laptopquery = $laptopmodel->getLaptops();
#foreach($query as $q)
# print_r($q);
#
# die;
$searchModel = new UserequipmentmappingSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'userquery' => $userquery,
'displayquery' => $displayquery,
'laptopquery'=> $laptopquery,
'phonequery'=> $phonequery,
]);
}
/**
* Displays a single UserEquipmentMapping 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 UserEquipmentMapping model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserEquipmentMapping();
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
#print_r(Yii::$app->request->post()); die;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Updates an existing UserEquipmentMapping 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);
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Deletes an existing UserEquipmentMapping 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 UserEquipmentMapping model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserEquipmentMapping the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserEquipmentMapping::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
use app\models\User;
use app\models\UserQuery;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_equipment_mapping".
*
* #property int $id
* #property int $user_id
* #property int|null $laptop_id
* #property int|null $phone_id
* #property int|null $display_id
* #property string|null $start_date
* #property string|null $stop_date
*
* #property Display $display
* #property Laptop $laptop
* #property Phone $phone
* #property User $user
*/
class UserEquipmentMapping extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user_equipment_mapping';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
[['display_id'], 'exist', 'skipOnError' => true, 'targetClass' => Display::className(), 'targetAttribute' => ['display_id' => 'id']],
[['laptop_id'], 'exist', 'skipOnError' => true, 'targetClass' => Laptop::className(), 'targetAttribute' => ['laptop_id' => 'id']],
[['phone_id'], 'exist', 'skipOnError' => true, 'targetClass' => Phone::className(), 'targetAttribute' => ['phone_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'laptop_id' => 'Laptop ID',
'phone_id' => 'Phone ID',
'display_id' => 'Display ID',
'start_date' => 'Start Date',
'stop_date' => 'Stop Date',
];
}
/**
* Gets query for [[Display]].
*
* #return \yii\db\ActiveQuery|DisplayQuery
*/
public function getDisplay()
{
return $this->hasOne(Display::className(), ['id' => 'display_id']);
}
/**
* Gets query for [[Laptop]].
*
* #return \yii\db\ActiveQuery|LaptopQuery
*/
public function getLaptop()
{
return $this->hasOne(Laptop::className(), ['id' => 'laptop_id']);
}
/**
* Gets query for [[Phone]].
*
* #return \yii\db\ActiveQuery|PhoneQuery
*/
public function getPhone()
{
return $this->hasOne(Phone::className(), ['id' => 'phone_id']);
}
/**
* Gets query for [[User]].
*
* #return \yii\db\ActiveQuery|UserQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getUsers()
{
return $this->hasMany(User::className(),['user_id', 'id']);
}
public function getLaptops()
{
return $this->hasMany(Laptop::className(),['laptop_id', 'id']);
}
public function getDisplays()
{
return $this->hasMany(Display::className(),['dislpay_id', 'id']);
}
public function getPhones()
{
return $this->hasMany(Phone::className(),['phone_id', 'id']);
}
/**
* {#inheritdoc}
* #return UserEquipmentMappingQuery the active query used by this AR class.
*/
public static function find()
{
return new UserEquipmentMappingQuery(get_called_class());
}
}
ModelSearch :
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\UserEquipmentMapping;
/**
* UserequipmentmappingSearch represents the model behind the search form of `app\models\UserEquipmentMapping`.
*/
class UserequipmentmappingSearch extends UserEquipmentMapping
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], '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 = UserEquipmentMapping::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,
'user_id' => $this->user_id,
'laptop_id' => $this->laptop_id,
'phone_id' => $this->phone_id,
'display_id' => $this->display_id,
'start_date' => $this->start_date,
'stop_date' => $this->stop_date,
]);
return $dataProvider;
}
}
Index :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\UserequipmentmappingSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'User Equipment Mappings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-equipment-mapping-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create User Equipment Mapping', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '-',],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
#'id',
'user.username',
#'laptop.laptop_model',
'laptop.laptop_series',
#'laptop_id',
#'phone.phone_model',
'phone.phone_series',
#'phone_id',
#'display.display_model',
'display.display_series',
#'display_id',
'start_date',
'stop_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Uncomment in your index view _search view. There are all fields from UserequipmentmappingSearch model. You can replace input fields with select fields for user, laptop and etc. Search model will do the other thing, all is in search function that fills your dataprovider
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;
I want to do search in Nama Mahasiswa search bar like picture below. As example I type name yuhara but there are no result whereas there are yuhara in the database.
Search model codes:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\AlumnyS3;
use app\models\AlumniIntegrasi;
/**
* AlumnyS3Search represents the model behind the search form about `app\models\AlumnyS3`.
*/
class AlumnyS3Search extends AlumnyS3
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Alumnys3ID'], 'integer'],
[['NRP', 'NamaMahasiswa', 'ProgramStudi', 'TanggalMasuk', 'TanggalKeluar'], 'safe'],
];
}
public $NamaMahasiswa;
/*public $TanggalMasuk;
public $tanggalMasukText;*/
/**
* #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 = AlumnyS3::find();
$query->joinWith('alumniIntegrasi');
// 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([
'Alumnys3ID' => $this->Alumnys3ID,
]);
$query->andFilterWhere([
'alumnys3.NRP' => $this->NRP,
'alumniintegrasi.NamaMahasiswa' => $this->NamaMahasiswa,
'alumnys3.ProgramStudi' => $this->ProgramStudi,
'alumnys3.TanggalMasuk' => $this->TanggalMasuk,
'alumnys3.TanggaKeluar' => $this->TanggalKeluar
]);
return $dataProvider;
}
}
Model codes:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "alumnys3".
*
* #property integer $Alumnys3ID
* #property string $NRP
* #property string $ProgramStudi
* #property string $TanggalMasuk
* #property string $TanggalKeluar
*
* #property AlumniIntegrasi $nRP
*/
class AlumnyS3 extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'alumnys3';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['NRP'], 'required'],
[['NRP'], 'string', 'max' => 15],
[['ProgramStudi'], 'string', 'max' => 5],
[['TanggalMasuk', 'TanggalKeluar'], 'string', 'max' => 30],
[['NRP'], 'exist', 'skipOnError' => true, 'targetClass' => AlumniIntegrasi::className(), 'targetAttribute' => ['NRP' => 'NRP']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'Alumnys3ID' => Yii::t('app', 'Alumnys3 ID'),
'NRP' => Yii::t('app', 'Nrp'),
'ProgramStudi' => Yii::t('app', 'Program Studi'),
'TanggalMasuk' => Yii::t('app', 'Tanggal Masuk'),
'TanggalKeluar' => Yii::t('app', 'Tanggal Keluar'),
'NamaMahasiswa' => Yii::t('app', 'Nama Mahasiswa'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getalumniIntegrasi()
{
return $this->hasOne(alumniIntegrasi::className(), ['NRP' => 'NRP']);
}
public function getNamaMahasiswa()
{
$alumniIntegrasi = alumniIntegrasi::findOne(['NRP'=> $this->NRP]);
if (empty($alumniIntegrasi))
return '';
return $alumniIntegrasi->NamaMahasiswa;
}
/*public function getTanggalMasukText()
{
$alumniIntegrasi = alumniIntegrasi::findOne(['NRP'=> $this->NRP]);
if (empty($alumniIntegrasi))
return '';
return $alumniIntegrasi->TanggalMasuk;
}*/
}
Index codes:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\AlumnyS3Search */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Alumny S3s');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="alumny-s3-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Alumny S3'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'Alumnys3ID',
'NRP',
'NamaMahasiswa',
'ProgramStudi',
//'tanggalMasukText',
'TanggalMasuk',
'TanggalKeluar',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I don't know how to fix that. Could you plese help me to solve this codes? I'm really grateful if you can solve this, thanks!
Add like query in search model like below
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\AlumnyS3;
use app\models\AlumniIntegrasi;
/**
* AlumnyS3Search represents the model behind the search form about `app\models\AlumnyS3`.
*/
class AlumnyS3Search extends AlumnyS3
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Alumnys3ID'], 'integer'],
[['NRP', 'NamaMahasiswa', 'ProgramStudi', 'TanggalMasuk', 'TanggalKeluar'], 'safe'],
];
}
public $NamaMahasiswa;
/*public $TanggalMasuk;
public $tanggalMasukText;*/
/**
* #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 = AlumnyS3::find();
$query->joinWith('alumniIntegrasi');
// 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([
'Alumnys3ID' => $this->Alumnys3ID,
]);
$query->andFilterWhere([
'alumnys3.NRP' => $this->NRP,
// 'alumniintegrasi.NamaMahasiswa' => $this->NamaMahasiswa,
'alumnys3.ProgramStudi' => $this->ProgramStudi,
'alumnys3.TanggalMasuk' => $this->TanggalMasuk,
'alumnys3.TanggaKeluar' => $this->TanggalKeluar
]);
$query->andFilterWhere(['like', 'alumniintegrasi.NamaMahasiswa', $this->NamaMahasiswa]);
return $dataProvider;
}
}
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,
]);
}