i want to join my company table name to employee id. here my code in
employee model
public function attributeLabels()
{
return [
'id' => 'ID',
//'company_id' => 'Company ID',
'emp_name' => 'Emp Name',
'emp_email' => 'Emp Email',
'emp_salery' => 'Emp Salery',
];
}
public function getCompany()
{
return $this->hasOne(Company::className(),['id' => 'company_id']);
}
in index file i use this code
<?php PJax::begin();?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
//'id',
[
'attribute' => 'company_id',
'value' => 'company.name',
],
'emp_name',
'emp_email:email',
'emp_salery',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php PJax::end();?></div>
in employee search table i use this code
public function search($params)
{
$query = Employee::find();
$query->joinWith(['company']);
// 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,
]);
$query->andFilterWhere(['like', 'company_id', $this->company_id])
->andFilterWhere(['like', 'emp_name', $this->emp_name])
->andFilterWhere(['like', 'emp_email', $this->emp_email])
->andFilterWhere(['like', 'emp_salery', $this->emp_salery])
->andFilterWhere(['like', 'Company.name', $this->company_id])
->andFilterWhere(['like', 'company.name', $this->company])
;
return $dataProvider;
}
http://localhost/test/web/employee/
is shows in company field (not set)
pls help me
you can do this in two difference way : 1 . If you want use active record you must set property in first model you want to select it and join table with that like:
public $pin;
then when you get data you can access to pin in second table
the second way is you use asArray() that return all off data in both table
$model = News::find()->leftJoin('comment', 'news.id = comment.news_id')->asArray()->all();
then you can use it in your gridview
You should add a getter eg:getCompanyname()n your base model
......
public function attributeLabels()
{
return [
'id' => 'ID',
//'company_id' => 'Company ID',
'emp_name' => 'Emp Name',
'emp_email' => 'Emp Email',
'emp_salery' => 'Emp Salery',
'companyName' => 'Company Name')
];
}
public function getCompany()
{
return $this->hasOne(Company::className(),['id' => 'company_id']);
}
You should add a getter for company name
/*
Getter for company name
*/
public function getCommpanyName() {
return $this->company->name;
}
and in your gridview you should use the new get name (companyName)
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'companyName',
'emp_name',
'emp_email:email',
'emp_salery',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
see this for more complete samples
http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/
Related
I want to use Select2 dr as filter in Yii Grid view, but it doesn't filter at all, only refreshes the page.
I take the data from 2 tables - from accounts I take only user_id, and from credits I take everything else. And every filter works, except And the 'user_id' one.
<?php
echo GridView::widget(
[
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'wp_id',
'value' => 'accounts.user_id',
'filter' => Select2::widget(
[
'model' => $searchModel,
'attribute' => 'wp_id',
'data' => ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id'),
'options' => ['placeholder' => ' --Filter by user id-- '],
'language' => 'en',
'pluginOptions' => [
'allowClear' => true,
],
]
),
],
],
]
); ?>
Here is the action in the controller.
<?php
public function actionIndex()
{
$searchModel = new CreditsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
} ?>
And this is the search model method
<?php
public function search($params)
{
$query = Credits::find()->with('accounts');
$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;
}
if(!empty($this->user_id)) {
$query->andFilterWhere(['=', 'accounts.user_id', $this->user_id]);
}
// grid filtering conditions
$query->andFilterWhere([
'user_id' => $this->user_id,
'wp_id' => $this->wp_id,
'credits_bought' => $this->credits_bought,
'purchase_date' => $this->purchase_date,
'id' => $this->id,
]);
return $dataProvider;
}
} ?>
Thanks in advance!
Because you are passing the wp_id under the GridView filter and selecting the wp_id from the Accounts model as the value of the select2-dropdown
ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id')
Although it is confusing that you use the gridview column attribute wp_id and use the select2 to filter the user_id for the same column but if you are looking to do that you might need to change the above to
ArrayHelper::map(Accounts::find()->all(), 'user_id', 'wp_id')
I have a relation between User and Thesis and my dataProvider just displays user attributes and not thesis'ones in the Gridview. Is there a better way to print join attributes than: ['attribute'] => ['table.attribute']?
model:
public function search($params)
{
$query = Request::find()->joinWith('user')->joinWith('thesis')->where(['thesis.staff'=> Yii::$app->user->identity->id]);
$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;
}
view:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'title',
['attribute' => 'thesis',
'value' => 'thesis.title'],
//'company',
'description:ntext',
'duration',
['attribute' => 'user'
'value' => 'user.id'],
//'requirements',
//'course',
'n_person',
'ref_person',
'is_visible:boolean',
//'created_at',
//'staff',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
controller:
public function actionIndex()
{
$searchModel = new SearchRequest();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
You need to add the relation getters on your model.
On your Thesis model, you need to add something like
public function getUser0 () {
return $this->hasOne(\your\user\model\location\User::className(), ['id' => 'user']);
}
Having this on your model will populate via lazy-load the user relation when you call Thesis::user0, in your case, something like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
/// ---- other attributes
['attribute' => 'user0.name'],
/// ---- other attributes
],
]); ?>
Is better to add your code after $this->load($params);
My example is:
.
.
.
$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->joinWith('user');
$query->joinWith('thesis');
$query->andFilterWhere(['thesis.staff'=> Yii::$app->user->identity->id]);
.
.
.
I Have two tables "Personal_data" and "Students", Student has Personal_data.
I used Gii to generate the code for views, controlers and models, and I need to show all "Personal_data" from "Students" in a GridView, but i cant get it.
Code from models/PersonalDataSearch.php
public function search($params)
{
$query = PersonalData::find()->joinWith('Students'])->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'document' => $this->document,
'telephone' => $this->telephone,
'direction' => $this->direction,
'sex' => $this->sex,
]);
$query->andFilterWhere(['like', 'names', $this->names])
->andFilterWhere(['like', 'lastNames', $this->lastNames])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'movile', $this->movile]);
return $dataProvider;
}
Code from controllers/PersonalDataController.php
public function actionIndex()
{
$searchModel = new PersonalDataSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Code from views/personal-data/index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'names',
'lastNames',
'email:email',
'movile',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
This view originally show all rows from Personal_data table from all registered people, but I want just show Personal_Data from Students, I added this line:
$query = PersonalData::find()->joinWith('Students'])->all();
and I have this error:
PHP Fatal Error – yii\base\ErrorException
Call to a member function andFilterWhere() on array
how can i solve this problem?
Remove ->all() from
$query = PersonalData::find()->joinWith('Students'])->all();
Data provider is taking care of fetching the data from DB, you just need to build the query (all() is fetching the data). With just a query you can add filters to it so there will be no error for andFilterWhere()
I have a football match function. But always display same team on home or away.
Here's my code,
Model [Match] :
use app\models\Team;
...
public function getTeam()
{
return $this->hasOne(Team::className(), ['id' => 'home', 'id' => 'away']);
}
...
Team model is list of all team
Match table only keep id of Team on Home Field and Away Field
Model [MatchSearch] :
....
public $team_home;
public $team_away;
public function rules()
{
return [
[['home', 'away'], 'integer'],
[['team_home', 'team_away'], 'safe'],
];
}
...
public function search($params)
{
$query = Match::find()->joinWith(['team']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['team_home'] = [
'asc' => ['team.team' => SORT_ASC],
'desc' => ['team.team' => SORT_DESC],
];
$dataProvider->sort->attributes['team_away'] = [
'asc' => ['team.team' => SORT_ASC],
'desc' => ['team.team' => SORT_DESC],
];
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'home' => $this->home,
'away' => $this->away,
]);
$query->andFilterWhere(['like', 'team.team', $this->team_home])
->andFilterWhere(['like', 'team.team', $this->team_away]);
return $dataProvider;
}
Views [Index] :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'home',
'value' => function($data) {
return $data->team->team;
},
],
[
'attribute' => 'away',
'value' => function($data) {
return $data->team->team;
},
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
But the result always show the Away team both Home or Away :
Home :
Team Away
Away :
Team Away
How to fix this?
You can use inner join
$query = Match::find()
->innerJoin('team_tname as home', '`team_taame`.`id` = `match_table_name`.`home`')
->innerJoin('team_taname as away', '`team_name`.`id` = `match_table_name`.`away`');
the you should refer to the column name using the proper table alias
I am trying to combine 3 tables in the my ActiveRecord Search().
I have this table
employees
id
first_name
projects
id
name
project_assignment
id
employee_id
project_id
date_added
date_removed
I am using GridView to display all the employees in my database.
Now, I wanted to display project where the employee is being assigned. So having said this, obviously we need these 3 tables to connect.
In my Employees.php Model, i have this code:
public function getproject_assignment()
{
return $this->hasMany(ProjectAssignment::className(), ['employee_id' => 'id']);
}
In my ProjectAssignment.php model
/**
* #return \yii\db\ActiveQuery
*/
public function getEmployee()
{
return $this->hasOne(Employees::className(), ['id' => 'employee_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProject()
{
return $this->hasOne(Projects::className(), ['id' => 'project_id']);
}
In my EmployeeSearch.php
class EmployeesSearch extends Employees
{
public $project_name;
public function rules()
{
return [
[['id', 'employment_status_id'], 'integer'],
[['project_name','string_id', 'first_name', 'last_name', 'middle_name', 'gender', 'birth_date', 'civil_status', 'phone', 'address', 'zip', 'email', 'position', 'start_date', 'tin', 'philhealth', 'sss', 'hdmf', 'photo_location'], 'safe'],
];
}
public function search($params)
{
$query = Employees::find();
$query->addSelect(['projects.name as project_name','employees.*']);
$query->leftJoin('project_assignment','project_assignment.employee_id = employees.id');
$query->leftJoin('projects','projects.id = project_assignment.project_id');
$query->andWhere([
'project_assignment.date_removed' => NULL
]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => array('pageSize' => 20),
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
]);
$query->andWhere([
'employees.deleted_at' => NULL
// 'projects.deleted_at' => NULL
]);
$query->andFilterWhere(['like', 'string_id', $this->string_id])
->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'last_name', $this->last_name])
->andFilterWhere(['like', 'middle_name', $this->middle_name])
->andFilterWhere(['like', 'gender', $this->gender])
->andFilterWhere(['like', 'civil_status', $this->civil_status])
->andFilterWhere(['like', 'phone', $this->phone])
->andFilterWhere(['like', 'address', $this->address])
->andFilterWhere(['like', 'zip', $this->zip])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'position', $this->position])
->andFilterWhere(['like', 'tin', $this->tin])
->andFilterWhere(['like', 'philhealth', $this->philhealth])
->andFilterWhere(['like', 'sss', $this->sss])
->andFilterWhere(['like', 'hdmf', $this->hdmf])
->andFilterWhere(['like', 'photo_location', $this->photo_location]);
return $dataProvider;
}
In my index.php (view file)
$gridColumns = [
[
'attribute' => 'Project',
'value' => 'projects', //the value means that this is the value of the column
//the zip here is the get parameter
'filter' => Html::activeDropDownList($searchModel, 'project_name', ArrayHelper::map(\app\models\Projects::find()->asArray()->all(), 'id', 'name'),['class'=>'form-control','prompt' => 'Select Project']),
],
'first_name',
'middle_name',
'last_name',
// 'position',
[
'attribute' => 'position',
'value' => 'position',
'filter' => Html::activeDropDownList($searchModel, 'position', ArrayHelper::map(Employees::find()->groupBy('position')->asArray()->all(), 'position', 'position'),['class'=>'form-control','prompt' => 'Select Position']),
],
['class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}'],
];
<?php echo
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'export' => [
'fontAwesome' => true,
]
]);
?>
The problem here is the Project column is not displaying anything.
Here's a screenshot:
When I checked on Yii Debuger, this sql query has been ran:
SELECT `projects`.`name` AS `project_name`, `employees`.* FROM `employees` LEFT JOIN `project_assignment` ON project_assignment.employee_id = employees.id LEFT JOIN `projects` ON projects.id = project_assignment.project_id WHERE (`project_assignment`.`date_removed` IS NULL) AND (`employees`.`deleted_at` IS NULL) LIMIT 20
This query is correct and what I was expecting. The only problem is that the Project column is not displaying as the screenshot that i showed you above.
I am not sure how to make this work. Been scratching my head for a couple of hours already.
Any help please. Thank You!
'value' => 'projects', //the value means that this is the value of the column
Actually the value here can be string or closure. If it is a string then it means that a string representing the attribute name to be displayed in this column as documentation says. Try to use closure. In your case it will be like this:
'value' => function ($model, $key, $index, $column){
return $model->project->name;
}
for kartik\grid\GridView;
'class' => 'kartik\grid\EditableColumn',
'attribute'=>'myAttribute',
'header' => 'myHeader',
'editableOptions' => [
'inputType' => \kartik\editable\Editable::INPUT_TEXT,
'valueIfNull' => '-',
/**
* #var string the value to be displayed. If not set, this will default to the attribute value. If the attribute
* value is null, then this will display the value as set in [[valueIfNull]].
*/
public $displayValue;