Yii – Only fill filter dropdown with used options

Sometimes you want to show a filter dropdown but by default it will show all value options even if not assigned to anything. You can use findAll with criteria to only bring back items which are in use…


$criteria = new CDbCriteria;
$criteria->join = 'INNER JOIN organisation ON organisation.category_id = t.category_id';

if($_GET['school_id'])
{
	$criteria->condition = 'organisation.school_id = ' . $_GET['school_id'];
}
else
{

}

$categories = OrganisationCategory::model()->findAll($criteria);
$categories_array = array();
foreach($categories as $category)
{
	$categories_array[$category->category_id] = $category->name;
}


$columns = array(
	'name',
	array(
		'name'=>'category_id',
		'value' => 'OrganisationCategory::model()->findByPk($data->category_id)->name',
		'filter' => $categories_array
[...]

[carousel keywords=”yii” tag=”fetchit-21″]

Yii CGridView default Order

If you want to set a default sort order for a CGridView, often used in admin views you can do so in the controller as part of the search() function:

$dataProvider = new CActiveDataProvider(get_class($this), array(
	'criteria'=>$criteria,
	'sort' => array('defaultOrder' => 'name')
));

[carousel keywords=”yii” tag=”fetchit-21″]