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 two tables. One for Users, one for Equipments.
I managed to make the search for username from other table, but now i want to create an equipment or to update an equipment directly to username, not by user_for_id. Is there any posibilty to do that ? Which would be the steps ? Thank you very much for any guidance.
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;
use yii\filters\AccessControl;
/**
* EquipmentController implements the CRUD actions for Equipment model.
*/
class EquipmentController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
/**
* 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'],
[['userFor'], 'safe'],
[['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']],
[['userFor'], 'string', 'max' => 50],
//[['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',
'nb_sg_model' => 'NB/GS Model',
'nb_sg_series' => 'NB/GS Series',
'nb_sg_date_acq' => 'NB/GS Date',
'display_model' => 'Display Model',
'display_series' => 'Display Series',
'display_date_acq' => 'Display Date',
'user_for_id' => 'User For ID',
'userFor.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());
}
}
Model 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
{
public $userFor;
/**
* {#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'],
[['userFor'], 'safe'],
#[['username'], '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();
$query->joinWith(['userFor']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['username'] = [
'asc' => ['user.username' => SORT_ASC],
'desc' => ['user.username' => 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([
'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])
->andFilterWhere(['like', 'user.username', $this->userFor]);
return $dataProvider;
}
}
Thank you in advance for any guidance or help.
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
I'm new in Yii 2, and I'm creating an inventory system for the library of my school, but I had a problem.
First, I have a relation like this:
I want to show all the adqs (a unique number for each book - that way we don't need to capture the book again for every copy) of a book in his view, but only the adqs related to the book id obviously at the bottom.
My View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $model app\models\Libros */
/* #var $searchModel app\models\LibrosSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = $model->lib_titulo;
$this->params['breadcrumbs'][] = ['label' => 'Libros', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="libros-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Modificar', ['update', 'id' => $model->lib_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Borrar', ['delete', 'id' => $model->lib_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<div class="row" align="center">
<?php
if ($model->lib_image_web_filename!='') {
echo '<br /><p><img width="500" src="'.Url::to('#web/', true). '/uploads/libros/'.$model->lib_image_web_filename.'"></p>';
}
?>
</div>
<div class="row" style="
text-align: center;
font: normal normal bold 15px/1 'lato';
color: rgba(7,7,7,1);
text-align: center;
">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'lib_id',
'lib_titulo',
'lib_autor',
//'lib_edicion',
'editorialNombre',
'ubicacionNombre',
'lib_isbn',
'lib_clasificacion',
'lib_seccion',
//'lib_image_src_filename',
//'lib_image_web_filename',
],
]) ?>
</div>
</div>
My Controller (LibrosController):
<?php
namespace backend\controllers;
use Yii;
use app\models\Libros;
use app\models\LibrosSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* LibrosController implements the CRUD actions for Libros model.
*/
class LibrosController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Libros models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new LibrosSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Libros model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionCreate()
{
$model = new Libros();
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Libros 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())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = explode(".", $image->name);
$ext_final = end($ext);
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext_final}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Deletes an existing Libros 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 Libros model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Libros the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Libros::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
My Model (Libros.php):
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "libros".
*
* #property int $lib_id
* #property string $lib_titulo
* #property string $lib_autor
* #property string $lib_edicion
* #property int $lib_ubi
* #property int $lib_editorial_id
* #property string $lib_isbn
* #property string $lib_clasificacion
* #property string $lib_seccion
* #property string $lib_image_src_filename
* #property string $lib_image_web_filename
*
* #property Adq[] $adqs
* #property Editorial $libEditorial
* #property Ubicacion $libUbi
* #property LibrosCarreras[] $librosCarreras
* #property Carreras[] $licCarreras
*/
class Libros extends \yii\db\ActiveRecord
{
const PERMISSIONS_PRIVATE = 10;
const PERMISSIONS_PUBLIC = 20;
public $image;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'libros';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_titulo', 'lib_autor', 'lib_ubi', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'required'],
[['lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo'], 'string', 'max' => 120],
[['lib_autor', 'lib_clasificacion'], 'string', 'max' => 64],
//[['lib_edicion'], 'string', 'max' => 3],
[['lib_isbn'], 'string', 'max' => 32],
[['lib_seccion'], 'string', 'max' => 2],
[['lib_editorial_id'], 'exist', 'skipOnError' => true, 'targetClass' => Editorial::className(), 'targetAttribute' => ['lib_editorial_id' => 'edi_id']],
[['lib_ubi'], 'exist', 'skipOnError' => true, 'targetClass' => Ubicacion::className(), 'targetAttribute' => ['lib_ubi' => 'ubil_id']],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 100],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
[['image'], 'file', 'maxSize'=>'1000000'],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 255], ];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'lib_id' => 'ID',
'lib_titulo' => 'Titulo',
'lib_autor' => 'Autor',
//'lib_edicion' => 'Edicion',
'lib_editorial_id' => 'Editorial',
'lib_isbn' => 'ISBN',
'lib_clasificacion' => 'Clasificacion',
'lib_ubi' => 'Ubicacion',
'lib_seccion' => 'Seccion',
'image' => 'Captura',
'lib_image_src_filename' => Yii::t('app', 'Nombre de Archivo'),
'lib_image_web_filename' => Yii::t('app', 'Nombre del Directorio'),
'editorialNombre' => 'Editorial',
'ubicacionNombre' => 'Ubicacion',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
/**
* #return \yii\db\ActiveQuery
*/
public function getLibrosCarreras()
{
return $this->hasMany(LibrosCarreras::className(), ['lic_libros_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEditorial0()
{
return $this->hasOne(Editorial::className(), ['edi_id' => 'lib_editorial_id']);
}
public function getEditorialNombre()
{
return $this->editorial0->edi_nombre;
}
public function getLibUbi()
{
return $this->hasOne(Ubicacion::className(), ['ubil_id' => 'lib_ubi']);
}
public function getUbicacionNombre()
{
return $this->libUbi->ubil_nombre; }
}
My Search Model (LibrosSearch.php):
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Libros;
/**
* LibrosSearch represents the model behind the search form of `app\models\Libros`.
*/
class LibrosSearch extends Libros
{
public $editorialNombre;
public $ubicacionNombre;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_id', 'lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo', 'lib_autor', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'safe'],
[['editorialNombre'],'safe'],
[['ubicacionNombre'],'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 = Libros::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes'=>[
'editorialNombre'=>[
'asc'=>['editorial.edi_nombre'=>SORT_ASC],
'desc'=>['editorial.edi_nombre'=>SORT_DESC],
'label'=>'Editorial Nombre'
]
]
]);
$dataProvider->setSort([
'attributes'=>[
'ubicacionNombre'=>[
'asc'=>['ubicacion.ubil_nombre'=>SORT_ASC],
'desc'=>['ubicacion.ubil_nombre'=>SORT_DESC],
'label'=>'Ubicacion Nombre'
]
]
]);
$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([
'lib_id' => $this->lib_id,
'lib_ubi' => $this->lib_ubi,
'lib_editorial_id' => $this->lib_editorial_id,
]);
$query->andFilterWhere(['like', 'lib_titulo', $this->lib_titulo])
->andFilterWhere(['like', 'lib_autor', $this->lib_autor])
//->andFilterWhere(['like', 'lib_edicion', $this->lib_edicion])
->andFilterWhere(['like', 'lib_isbn', $this->lib_isbn])
->andFilterWhere(['like', 'lib_clasificacion', $this->lib_clasificacion])
->andFilterWhere(['like', 'lib_seccion', $this->lib_seccion])
->andFilterWhere(['like', 'lib_image_src_filename', $this->lib_image_src_filename])
->andFilterWhere(['like', 'lib_image_web_filename', $this->lib_image_web_filename]);
$query->joinWith(['editorial0'=>function($q)//creamos un nuevo filtro
{
$q->where('editorial.edi_nombre LIKE "%' . $this->editorialNombre . '%"');
}]);
$query->joinWith(['libUbi'=>function($q)//creamos un nuevo filtro
{
$q->where('ubicacion.ubil_nombre LIKE "%' . $this->ubicacionNombre . '%"');
}]);
return $dataProvider;
}
}
How can I accomplish this task?
[
'attribute' => 'adq_libro_id',
'value' => implode(', ', \yii\helpers\ArrayHelper::map($model->Adqs, 'id',
function ( $model )
{
return $model['adq'];
}
)),
'format' => 'raw'
],
try like this. Check the right name of attributes
In your model Libros.php you have this function.
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
This means you can access the relations of Libros like:
// where $model is an instance of Libros
$model->adqs->property_name
Or as a function
$model->getAdqs();
I have a custom action in ActiveController and need to fetch some data by joining two tables.
I have written following query .
$query = Item::find()->joinWith(['subcategory'])->select(['item.*', 'sub_category.name'])->where(['item.active' => 1])->addOrderBy(['item.id' => SORT_DESC]);
$pageSize = (isset($_GET["limit"]) ? $_GET["limit"] : 1) * 10;
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
$dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $pageSize, "page" => $page]]);
$formatter = new ResponseFormatter();
return $formatter->formatResponse("", $dataProvider->getTotalCount(), $dataProvider->getModels());
but it is throwing an exception
"message": "Setting unknown property: common\\models\\Item::name",
Here is the item Model with all the fields and relation.
<?php
namespace common\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\BaseActiveRecord;
use yii\db\Expression;
/**
* This is the model class for table "item".
*
* #property integer $id
* #property integer $subcategory_id
* #property string $title
* #property resource $description
* #property integer $created_by
* #property integer $updated_by
* #property string $created_at
* #property string $updated_at
* #property string $image
* #property integer $active
*
* #property SubCategory $subcategory
*/
class Item extends \yii\db\ActiveRecord
{
public $imageFile;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'item';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['created_by', 'updated_by'], 'required'],
[['subcategory_id', 'created_by', 'updated_by', 'active'], 'integer'],
[['description'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['title', 'image'], 'string', 'max' => 999],
[['title'], 'unique'],
[['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'subcategory_id' => 'Subcategory ID',
'title' => 'Title',
'description' => 'Description',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'image' => 'Image',
'active' => 'Active',
'imageFile' => 'Image',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSubcategory()
{
return $this->hasOne(SubCategory::className(), ['id' => 'subcategory_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCreatedBy()
{
return $this->hasOne(User::className(), ['id' => 'created_by']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUpdatedBy()
{
return $this->hasOne(User::className(), ['id' => 'updated_by']);
}
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => new Expression('NOW()'),
],
];
}
}
The joinWith makes a query using the joins requested, but result data are mapped in source model (in this case Item).
Since you have select(['item.*', 'sub_category.name']) , the framework will try to fill 'name' field of Item model, that does not exist and this generates the error.
According with documentation (http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#overriding-extra-fields) you should have db relation subcategory populated from db, by default, but I don't see subcategory relation in your model.
So you have only to create subcategory relation in your model, such as:
public function getSubcategory() { return $this->hasOne(Subcategory::className(), ['id' => 'subcategory_id']); }
So you should solve your problem.
Other solution to have custom fields from more models could be:
1) Create a sql View (and from that create the Model) with fields that you want and pass it to ActiveDataProvide
2) Override extraFields method of the model (http://www.yiiframework.com/doc-2.0/yii-base-arrayabletrait.html#extraFields%28%29-detail)
Again, I suggest you to read this good article:
http://www.yiiframework.com/wiki/834/relational-query-eager-loading-in-yii-2-0/