Friday, December 7, 2012

Create Ordered Drop Down List in CGridView

In CGridView it can be really useful to have a drop down to quickly filter a list. For example you may want to create a filter based on Business Name. To quickly filter the list in CGridView adding a drop down list is an excellent option.


For the drop down to be useful often time you will need to create an ordered drop down list and using Yii's Active Record makes this fairly easy to do. Firstly the code:

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'client-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'provider_id',
array(
'name'=>'business_name',
'filter'=>CHtml::listData(Client::model()->findAll(array('condition'=>'active=1',
'order'=>'business_name ASC')),
'business_name','business_name'), //REALLY IMPORTANT
'type'=>'raw',
'value'=>'CHtml::link($data->business_name, array("client/view","id"=>$data->id))',
'htmlOptions'=>array('width'=>'100'),
),
'business_address',
'business_suburb',
'business_postcode',
                array(
'class'=>'CButtonColumn',
),
),
)); ?>

You will notice the I have used a query to return the results to the filter and ordered the Business Name. Take note of  'business_name','business_name' - If you do not use the actual attribute name in this format you will not get the drop down list returning the correct result or the filter will not work. Do not be tempted to use 'id', 'business_name' as you would typically do as this will return a valid drop down list however the filter function will not work. If you want to add a hyperlink to the filter results then ensure you use 'type'=>'raw' (see CFormatter for more information on the various 'types' available).

No comments: