Overview

This is a how-to on how to add ordering and filtering (search, custom dropdown, state) to a component backend page.
This approach is almost exactly the same for the frontend.

General Information

Can anyone confirm this (same frontend)? and if so: Might want to change and redirect this article's title.

In general, the process of adding a custom field filter breaks down into the following steps:

Creating the class that will generate the form dropdown options

Adapting the view to display the form dropdown input

Adapting the model to retrieve data from DB & to set submission values in the Joomla 'state'

Extend JFormFieldList (models / fields / fieldname.php)

Frequently your filter fields will be very basic; probably simply a dropdown list of one of the columns being displayed on the current page. Regardless, you will need to create your own field element. This really isn't a big deal - this file will probably be less than 70 lines, including comments. The code below will generate the dropdown element to filter by companies. For more information and complex examples on creating this class see Creating_a_custom_form_field_type.

Obviously, there is only one section here that needs to be customized:

$query->select('id As value, name As text');$query->from('#__my_companies AS a');$query->order('a.name');$query->where('state = 1');

Change the database name and adjust the sql as necessary. This will produce the text and values for the select element options. I highly recommend not changing the value and text names. Although I did not test this theory, it seems likely that ancestor classes are expecting these names as keys in the resulting array.

Modify View (views / zzz / view.html.php)

In you view class, you have to set the state, like this:

$this->items=$this->get('Items');$this->pagination=$this->get('Pagination');$this->state=$this->get('State');//Following variables used more than once$this->sortColumn=$this->state->get('list.ordering');$this->sortDirection=$this->state->get('list.direction');$this->searchterms=$this->state->get('filter.search');

Modify Template (views / zzz / tmpl / default.php)

Basic

Top of template somewhere:

//Get companie options
JFormHelper::addFieldPath(JPATH_COMPONENT .'/models/fields');$companies= JFormHelper::loadFieldType('MyCompany',false);$companyOptions=$companies->getOptions();// works only if you set your field getOptions on public!!

Extra: highlighting search terms

Here is some extra to visually mark the found search terms in the results page.

Template

Add this somewhere at top somehwere:

$searchterms=$this->state->get('filter.search');//Highlight search terms with js (if we did a search => more performant and otherwise crash)if(strlen($searchterms)>1) JHtml::_('behavior.highlighter',explode(' ',$searchterms));

And further in your template, enclose the specific fields with the default highlighter finder.