three table based relation display in yii gridview - php

I'm getting foreign key relation based display ids in the gridviews. How to get values instead of ids? Code in my gridview is following:
$criteria->compare('education.UniversityNameid',$this->UniversityName, true);
my gridviews inside code
array(
'name' => 'UniversityName',
'type' => 'raw',
'value'=>'(empty($data->education->UniversityNameid))? "" : Yii::app()->params["currencySymbol"]." ".$data->education->UniversityNameid',
),

You have to set up a relation in your model "University" like this
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'UniversityName' => array(self::BELONGS_TO, 'University', 'UniversityNameid'),
);
}
thank you can access the Name
$data->education->UniversityName

Set the relation in your model like
'u' => array(self::BELONGS_TO, 'University', 'UniversityNameid'),
and acess it like
'attributes'=>array(
array('name'=>'u.UniversityName',
'label'=>'University',),
),

Related

Print all values of an array in CDetailView Yii

I'm currently new to Yii and have some problems in my app.
I have 2 AR (Employee and Children) with the relations is Employee has_many Children. Now when we go into the view of Employee (in the view&id=blablabla not in index), I want to list all the children that the Employee have.
I have made a function in EmployeeController class to retrieve the children from my db
$anak = Anak::Model()->findAll(array(
'condition'=>'id_karyawan=:id_karyawan',
'params'=>array(':id_karyawan'=>$id_karyawan)));
//return $anak;
foreach ($anak as $data){
return $data->namaanak;
}
the problem is, it only showing 1 data (the first one, to be exact) of the children, even though in my db the Employee has 3 children. When I try to count of query result, it's showing 3.
My employee/view is like this
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id_karyawan',
'nama',
array(
'name'=>'idjabatan',
'value'=>$model->findByPk($model->id_karyawan)->jabatan->namajabatan,
),
array(
'name'=>'gaji',
'value'=>Yii::app()->numberFormatter->formatCurrency($model->findByPk($model->id_karyawan)->jabatan->gaji, 'Rp'),
),
'alamat',
array(
'name'=>'ttl',
'value'=>$model->tempatlahir.', '.Yii::app()->dateFormatter->format("dd MMMM yyyy", $model->tgllahir),
),
array(
'name'=>'Istri',
'value'=>Istri::model()->getNama($model->id_karyawan),
'type'=>'raw'
),
array(
'name'=>'Anak',
'value'=>$this->getAnak($model->id_karyawan),
'type'=>'raw'
)
),
I have tried to google it, but i couldn't find any working answer :(
PS: karyawan = employee, anak = children.
You are only getting the first related value because you are returning it right away inside your foreach loop in the function. Gather all the related models first then return that and work with that data.
You can also skip that extra function inside your controller. If you use Gii, it should have already set up the proper Employee HAS_MANY children relation for you, so you could use that to pull all related models for each Employee model you are looking at. See below for a quick example
Employee model:
public function relations()
{
return array(
'children' => array(self::HAS_MANY, 'Child', 'employee_id'),
);
}
View file, passing an employee model to CDetailView:
$this->widget('zii.widgets.CDetailView', array(
'data' => $model,
'attributes'=>array(
array(
'name' => 'Children',
'value' => function ($data) {
// Get all related children using the relation defined in the Employee model and use CHtml::listData to store data inside the $children variable as an array using `id` as key and `child_name` as value
$children = CHtml::listData($data->children, 'id', 'child_name');
// Return names as a comma separated list
return implode(', ', $children);
},
'type'=>'raw'
)
)
);
My tables/column names probably don't match up with what you have but hopefully this helps.

Accessing value of indirectly related models

I am displaying a CGridView below CDetailView on view.php page for Company model. I have problem in displaying values in CGridView using company details. The company model has an array of CompanyAddresses which is used as CArrayDataProvider for CGridView.
$config = array();
$dataProvider = new CArrayDataProvider($rawData=$model->companyAddresses,$config);
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider
, 'columns'=>array(
//'id',
array('header'=>'SN.',
//'value'=>'++$row', // may nt work with pagination but the below does work
'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
'address',
array(
'name'=>'Tehsil',
//'value'=> Utility::getTehsilName(Tehsil::model()->findByPk('tehsil_id')),
'value'=> Utility::getTehsilName($this->loadModel('tehsil_id')),
//'value'=> Tehsil::model()->findByAttributes( array('id' => 'tehsil_id' ) )->name,
),
array(
'name'=>'address_tag_id',
'value'=>AddressTag::model()->findByPk('address_tag_id'),
),
)
));
I am not able to fetch Tehsil_Name from Tehsil Table which has its ID inside CompanyAddress table.
Your using value attribute is wrong, check this:
'value'=>function($data){
return Utility::getTehsilName($data->tehsil_id);
},
value is a php expression that is evaluated to produce the contents of the gridview cell as below
'value' => 'Utility::getTehsilName($this->grid->controller->loadModel($data->tehsil_id))'
If you had used relation chaining to solve this your expression would have been simplified to say:
'value' => '$data->model1->tehsil->name'
where model1 is the middle relation.

Yii - Joins on tables are not working

I want to get the data from two tables. I have used the below code to do so. I am new to Yii, if I am doing it the wrong way, please suggest the right way.
Here is the code of controller:
$dataProvider=new CActiveDataProvider('Users', array(
'criteria'=>array(
'with'=>'leave',
'together'=>true,
'condition'=>'leave.user_id=:user_id',
'params'=>array(':user_id'=>$this->loadModel(Yii::app()->user->getId())->user_id),
),
));
$this->render('admin',array(
'dataProvider'=>$dataProvider,
));
Here is the code of view:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'users-grid',
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'header' => 'Leave Type',
'name'=>'leave_type',
'value'=>'$data->leave->leave_type',
),
'employee_code',
'username',
'password',
array(
'class'=>'CButtonColumn',
),
),
));
My Problem is:
I am joining two tables User and Leave. I want to get the data of users from Leave table as well as the users table. the above code shows me data from user table, when i try to show data from Leave table it throws me following error:
Trying to get property of non-object
UPDATE
Here is my user model relations:
return array(
'leaves' => array(self::HAS_MANY, 'Leaves', 'leave_id'),
'creator' => array(self::BELONGS_TO, 'Users', 'created_by'),
'updator' => array(self::BELONGS_TO, 'Users', 'modified_by'),
'leave' => array(self::HAS_MANY, 'Leaves', 'user_id'),
);
Here is my leave model relations:
return array(
'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
'creator' => array(self::BELONGS_TO, 'Users', 'created_by'),
'updator' => array(self::BELONGS_TO, 'Users', 'modified_by'),
);
You can't display leave relation, because it's a HAS_MANY, I mean, in your $data->leave you have an array of Leave objects.
You should implement implode function, for example:
'value'=> "implode(', ', array_map(function($object) { return $object->leave_type; },
$data->leave))"
BTW, leave relation i think should be a HAS_ONE instead of HAS_MANY, and in this case, you don't need in an implode function in GridView
'value'=>'$data->leave->leave_type', // WRONG
$data->leave = array of objects and you could not access directly leave_type from it. That array was returned from your below relation:
'leave' => array(self::HAS_MANY, 'Leaves', 'user_id'),
I'm not sure the leave type which you want to access and relate it with user. But in this case, the solution is you can add more relation to just access first leave record of user
'singleLeave' => array(self::HAS_ONE, 'Leaves', 'user_id'), // add this line on Model User
And then you can access it properly
'value'=>'$data->singleLeave->leave_type',
Actually, in the first approach, the $data->leave should populate array of Leaves and from there, each Leave record should have to go into child views, and this is the point where you have to go detail

YII CGridView. Trying to show attribute from other table. Relation not working

This is driving me nuts. I read many responses and tutorials and i can't pin point the problem here.
I have 2 Tables: tblEmpleado and tblProfesion Here is an image of the MySQL relations they have (Marked on red)
I want to display on a CGridView the attribute "Descripcion" from the table tblProfesion when displaying the data from tblEmpleado.
I tried using claveProfesion.descripcion without avail (It shows the INT number of the FK just fine without the ".descripcion" part). Also tried using something like:
array(
'header'=>'tableHeaderName',
'value'=>'(isset($data->claveProfesion)) ? $data->claveProfesion->descripcion : null', )
getting "Trying to get property of non-object".
Here is the Empleados.php relation part of the model code:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'tblcelulars' => array(self::HAS_MANY, 'Tblcelular', 'claveEmpleado'),
'tblcuentabancos' => array(self::HAS_MANY, 'Tblcuentabanco', 'claveEmpleado'),
'idCentroTrabajo' => array(self::BELONGS_TO, 'Tblcentrotrabajo', 'idCentroTrabajo'),
'convenio' => array(self::BELONGS_TO, 'Tblconvenio', 'convenio'),
'claveProfesion' => array(self::BELONGS_TO, 'Tblprofesion', 'claveProfesion'),
);
}
And the CGridView part of the Admin.php View code
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'empleados-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'claveEmpleado',
'nombreEmpleado',
'idCentroTrabajo',
array(
'header'=>'tableHeaderName',
'value'=>'($data->claveProfesion!=null) ? $data->claveProfesion->descripcion : null',
),
'aniosExperiencia',
'telefono2',
'email',
...
array(
'class'=>'CButtonColumn',
),
),
)); ?>
And last, i don't know if its related but in the Model class "Profesiones.php" the relation is as follow:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'tblempleados' => array(self::HAS_MANY, 'Tblempleado', 'claveProfesion'),
);
}
Could anyone help me out with this?
Your column and your relation both have the same name claveProfesion. As such Yii is returning the column instead of the relation when you call claveProfesion. To resolve it rename your relation to something else e.g claveProfesionObject
public function relations()
{
return array(
...
'claveProfesionObject' => array(self::BELONGS_TO, 'Tblprofesion', 'claveProfesion'),
);
}

Data isn't displaying from another table in CGridView Widget

I have two table Event and EventCategory. I am using zii.widgets.grid.CGridView widget to display all the events in the admin section.
I have created the following relations between tables.
Relation in EventCategory model:
'event' => array(self::HAS_MANY, 'Event', 'category_id'),
Relation in Event model:
'category' => array(self::BELONGS_TO, 'EventCategory', 'category_id'),
The following code I am using to display the Events:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'event-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'summaryText'=> '',
'columns'=>array(
array('header'=>'Id','name'=>'event_id','filter'=>''),
'event_code',
'category.evntcatm_name',
'event_name',
array(
'class'=>'CButtonColumn',
'htmlOptions'=>array('class'=>'actions aligncenter'),
'deleteButtonImageUrl'=>false,
'updateButtonImageUrl'=>false,
'viewButtonImageUrl'=>false
),
),
)); ?>
'category.evntcatm_name' doesn't display anything. It is just creating the blank column with NO ERROR. What I am missing here.
Please try something like it
$data->category->evntcatm_name
You should use code like this:
'columns' = array(
/*YOUR DATA*/
array(
'name' => 'category_id',
'value' => function($data) {
return !empty($data->category) ? $data->category->evntcatm_name : null;
}),
)
This way can solve your problem with "Trying to get property of non-object". If you see blank cell in grid that means you miss relation (or it doesnt exist, in this way you should check relation condition or database)
Here is a few wild guesses:
Is category.evntcatm_name correctly spelled?
Is there actually data in the evntcatm_name field to begin with?
I know it might sound too simple to miss, but the error almost has to be on that level.
Try finding a category using the primary key and output it's evntcatm_name.
$cat = EventCategory::model()->findByPk(1);
echo $cat->evntcatm_name;
Maybe if you could share your schema for those two tables?
You can use
array(
'header' => 'Category Title',
'value' => '$data->category->evntcatm_name'
),
instead of 'category.evntcatm_name'
The model instance is not object now in the Cgidview:
Try
$data['category']['evntcatm_name'];

Categories