Retrieving Related Data In View

I am busy getting to grips with Yii and AR and MVC so i will probably have a lot of questions, you don’t need to give me an exact answer, a pointer to a tutorial or previous, related topic will also be appreciated.

My current problem is this:

I would like the table produced by the admin view to show the name value from the related table rather than simply the id stored in the main table.

example:

Main table contains:

Client Name | Client Type

Bobby Robert| 1

Client_Type Table contains:

1 | Happy

2 | Angry

3 | Stupid

etc

Kindly

I believe you are asking how to display different information in the Admin view that is generated by Gii, so that is what my answer pertains to.

The admin view uses CGridView.

You can update the column in the grid view with the following code:




$this->widget('zii.widget.grid.CGridView',array(

         'dataProvider'=>$dataProvider,

         'columns'=>array(

               'client_name',

               'client_type.name'

          )

));



As you can see, in the columns option you can reference table relations using the format relationName.cloumnName. There is many more ways to customize this, so I suggest looking at the documentation for the class above.

Have a look at my RelatedBehaviorSearch Extension which makes this easier (including search capability) and which also proposes a demo.

if your relations are set correctly in your model you can just use the attribute name. You can also use the 4th one down. Note that the filter in the top will be disabled without using the attribute name as it is set in the relation in your model. I just copied and pasted a few that i have used in the past (wayyy more than you asked for but maybe it will help some other people too). Please note the type being raw, html etc. this is important!

These aren’t all of the options but it should surely give you an idea of how easy it is once you get the hang of it.




Here is just an idea of things you can do with the gridview widget


<?php $this->widget('zii.widgets.grid.CGridView', array(

'id'=>'parts-grid',

'dataProvider'=>$model->search(),

'itemsCssClass'=>'table table-striped table-bordered table-hover',//custom css classes

'template' => "{items}{pager}", //template {sorter} is another as well as i think one more default one

'htmlOptions'=>array('style'=>'cursor: pointer;'),///just adds a curser when hovering over the rows b/c of the next line

'selectionChanged'=>"function(id){window.location='" . Yii::app()->urlManager->createUrl('products/parts/view', array('id'=>'')) .'/'."' + $.fn.yiiGridView.getSelection(id);}", just links the row to the actual item instead of clicking view icon at the right.

'filter'=>$model,

'pager' => array(

'header' => false,

),

'columns'=>array(

......

Here is a link to email in admin:


array(

'name'=>'Email Address',

'type'=>'raw',

'value'=>'CHtml::link(CHtml::encode($data->email_address), "mailto:".$data->email_address)',

),




Here is a link in Admin:


array(

        'name' => 'name',

        'type'=>'raw',

        'value' => 'CHtml::link(CHtml::encode($data->name),array("companies/view","id"=>$data->id))',

        'headerHtmlOptions' => array('style'=>'text-align:center; vertical-align: middle;font-size: 20px !important;'),

        'htmlOptions'=>array('style'=>'text-align:center; vertical-align: middle;'),

        

),

here is a link to a webpage in a new window from admin


array(

        'class'=>'CLinkColumn',

        'labelExpression'=>'CHtml::encode($data["website"])',

        'urlExpression' => '"http://".$data["website"]',

        'linkHtmlOptions'=>array('target'=>'_blank'),

        'headerHtmlOptions' => array('style'=>'text-align:center; vertical-align: middle;font-size: 20px !important;'),

        'htmlOptions'=>array('style'=>'text-align:center; vertical-align: middle;'),

        'header'=>'Website',        

),


Here is showing related name instead of number


array(

        'name'=>'country',

        'type'=>'raw',

        'value' => '$data->country0->abbreviation',

        'headerHtmlOptions' => array('style'=>'text-align:center; vertical-align: middle;font-size: 20px !important;'),

        'htmlOptions'=>array('style'=>'text-align:center; vertical-align: middle;'),

),


Here is Converting from 1 and 0 to yes and no in admin also adding a drop down filter to top instead of search box. you could also make it be Active / inactive, blue / green... it doesn't have to be just a yes and no. but it can only be two attributes.  like 0 and 1 , or say yes / no it will just check for those values and print what you say it to print. i.e. yes


array(

        'name'=>'celsius', 

        'type'=>'raw',

        'value' =>'$data->ppm? "Yes": "No"', //converts my 1 and 0 to Active / Inactive

        'filter' => array('0' => 'No', '1' => 'Yes'), // Adds a dropdown to the filter

        'headerHtmlOptions' => array('style'=>'text-align:center; vertical-align: middle;font-size: 20px !important;'),

        'htmlOptions'=>array('style'=>'text-align:center; vertical-align: middle;')

),


Here is one with a date in the column ...note if it is null then it throws an error sometimes so you will need to check for it first


array(

        'header'=>'Checked Out Date',

        'name' => 'outdate',

        'value'=>'date("M-d-Y h:i:A",strtotime($data->outdate))',

        'htmlOptions'=>array('style'=>'text-align:center; vertical-align: middle;'),

        'headerHtmlOptions' => array('style'=>'text-align:center; vertical-align: middle;font-size: 20px !important;'),

),


Lastly, here is a custom cbutton column at the end with different icons and a button I added bc I allow users to export to excel so it calls to that controller action.


array(

    'class'=>'CButtonColumn',

    'header'=>'Options',

    'headerHtmlOptions' => array('style'=>'min-width: 115px;  width: 115px; text-align:center; vertical-align: middle;font-size: 20px !important;'),

    'htmlOptions'=>array('style'=>'min-width: 115px; width: 115px; text-align:center; vertical-align: middle; '),

    'deleteConfirmation'=>"js:'Do you really want to delete this asset with Serial Number '+$(this).parent().parent().children(':nth-child(4)').text()+'?'",

    'template'=>'{view}{update}{excel}{delete}',

    'buttons' => array(

        'delete' => array(

            'imageUrl' => Yii::app()->theme->baseUrl . '/img/icons/delete.png', // image URL of the button.If not set or false,a text link is used

         ),

        'update' => array(

            'imageUrl' =>Yii::app()->theme->baseUrl . '/img/icons/update.png', // image URL of the button.   If not set or false, a text link is used

        ),

        'view' => array(

            'imageUrl' =>Yii::app()->theme->baseUrl . '/img/icons/view.png', // image URL of the button.   If not set or false, a text link is used

        ),

        'excel' => array(

            'label'=>'Excel',

            'options'=>array('title'=>'Export To Excel'),

            'imageUrl' =>Yii::app()->theme->baseUrl . '/img/icons/excel.png', // image URL of the button.   If not set or false, a text link is used

            'url'=>'Yii::app()->createUrl("products/products/admin/?&export=true", array())',

        ),

    ),

),



good luck and happy coding!