Thursday, January 6, 2011

A related hyperlink column in CGridView, CDetailView, CListView

Say you have an order table and it has a status id. You want to display the status name and not the id, as a hyperlink, that links to the status view page, where you can see other info about that status. Here's how to do it:

relation name: status_relation
id field: status_id
name field: name
related controller name: status_controller
label: Status

In your 'columns' array in a CGridView declaration:

array('name'=>'status_id', 'type'=>'raw', 'value'=>'CHtml::link($data->status_relation->name, array("status_controller/view", "id"=>$data->status_id))', 'header'=>'Status'),

watch your single and double quotes

$data is the name of the model record when inside a CGridView

This method allows for searching and sorting, as long as you adjust your model's search function as per the previous post.

In your 'attributes' array in your CDetailView:
array('label'=>'Status', 'type'=>'raw', 'value'=>CHtml::link($model->status_relation->name, array('status_controller/view','id'=>$model->status_id))),

In the _view of your CListView:
CHtml::link(CHtml::encode($data->status->name), array('status_contoller/view', 'id'=>$data->status_id)); 

6 comments:

  1. I don't understand in part "related controller name: status_controller", where you get it? is it came from controller file? I have try that, but it say "Property "Client.client_id" is not defined." are this have relation with has_many?

    ReplyDelete
  2. What id your "status_controller" is nullable? IS there a way to put the "Not Set" in for that case and not get the error on the "getting property of non-object"

    ReplyDelete
  3. question, is it possible to change the link to other controller?

    ReplyDelete