Filtering Lists

Filters add an extra panel above admin lists that allow you to filter the list by specified parameters. You can create different facets to filter by, when clicked these open a popup to configure how the list should be filtered.

Developing a filter class

The filter class defines a single facet that can be used to filter the list results. It should reside in your module classes folder, contain the _Filter suffix and extend the Db_Data_Filter class.

Let's say we want to filter a list of blog posts by the category that they belong to, create a filter class like so:

<?php

class Blog_Category_Filter extends Db_Data_Filter
{
	public $model_class_name = 'Blog_Category';
	public $list_columns = array('name');

	public function apply_to_model($model, $keys, $context = null)
	{
		$model->where('category_id in (?)', array($keys));
	}
}

If the blog post has many categories instead, the filter class would be:

<?php

class Blog_Category_Filter extends Db_Data_Filter
{
	public $model_class_name = 'Blog_Category';
	public $list_columns = array('name');

	public function apply_to_model($model, $keys, $context = null)
	{
		$model->where('(
			select count(*) 
			from 
				blog_posts_categories 
			where 
				blog_category_id in (?) 
				and blog_post_id = blog_posts.id
		) > 0', array($keys));
	}
}

In both examples we apply an SQL condition to the blog $model object with an array of $keys containing the ID values of the categories.

Updating the controller class

With the filter class ready, the next step is to $implement it in the Blog_Posts controller class. 

<?php

class Blog_Posts extends Admin_Controller
{
	public $implement = 'Db_List_Behavior, Db_Form_Behavior, Db_Filter_Behavior';
	[...]
}

Define these fields as they are mandatory and must exist in the controler class:

public $list_options = array();
public $list_custom_prepare_func = null;

Define and modify these fields for the filter configuration:

public $filter_list_title = 'Filter posts';
public $filter_on_apply = 'listReload();';
public $filter_on_remove = 'listReload();';
public $filter_filters = array(
	'category' => array(
		'name' => 'Category',
		'class_name' => 'Blog_Category_Filter',
		'prompt' => 'Please choose post categories you want to include to the list.',
		'added_list_title' => 'Added Categories'
	)
);

The ftiler isn't applied to the list automatically, you may want to apply extra conditions to the list, so we define a standard preparation method to bring it all together:

public function list_prepare_data()
{
	$obj = new Blog_Post();
	$this->filter_apply_to_model($obj);
	return $obj;
}

Updating the list view file

Finally we need to update the list view file index.htm which contains the list_render() method call. By default this method does not include the filters, so we must pass the parameter render_filters for the filers to be displayed.

<?= $this->list_render(array('list_render_filters' => true)) ?>