How to add custom filters to components

From Joomla! Documentation

This page has been archived. This page contains information for an unsupported Joomla! version or is no longer relevant. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.


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.
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'. For a better understanding of the code samples, the db table is called 'my_company' and the fields are: id, name, state, company, somefield, someotherfieldtosearchin.

Extend JFormFieldList (models / fields / fieldname.php)[edit]

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.

My 'companies' dropdown element:


defined('JPATH_BASE') or die;


 * Custom Field class for the Joomla Framework.
 * @package		Joomla.Administrator
 * @subpackage	        com_my
 * @since		1.6
class JFormFieldMyCompany extends JFormFieldList
	 * The form field type.
	 * @var		string
	 * @since	1.6
	protected $type = 'MyCompany';

	 * Method to get the field options.
	 * @return	array	The field option objects.
	 * @since	1.6
	public function getOptions()
		// Initialize variables.
		$options = array();

		$db	= JFactory::getDbo();
		$query	= $db->getQuery(true);

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

		// Get the options.

		$options = $db->loadObjectList();

		// Check for a database error.
		if ($db->getErrorNum()) {
			JError::raiseWarning(500, $db->getErrorMsg());

		return $options;

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->where('state = 1');

Change the table 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 Model (models / zzz.php)[edit]

In your model you have to include these two functions:

//Add this handy array with database fields to search in
	protected $searchInFields = array('text','','someotherfieldtosearchin');

//Override construct to allow filtering and ordering on our fields
	public function __construct($config = array()) {

	protected function getListQuery(){
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);

                //CHANGE THIS QUERY AS YOU NEED...
                $query->select('id As value, name As text, somefield')
			->from('#__my_companies AS a')
			->order(	$db->escape($this->getState('list.ordering', '')) . ' ' .
					$db->escape($this->getState('list.direction', 'desc')));

		// Filter search // Extra: Search more than one fields and for multiple words
		$regex = str_replace(' ', '|', $this->getState(''));
		if (!empty($regex)) {
			$regex=' REGEXP '.$db->quote($regex);
			$query->where('('.implode($regex.' OR ',$this->searchInFields).$regex.')');

		// Filter company
		$company= $db->escape($this->getState(''));
		if (!empty($company)) {
		// Filter by state (published, trashed, etc.)
		$state = $db->escape($this->getState('filter.state'));
		if (is_numeric($state)) {
			$query->where('a.state = ' . (int) $state);
		elseif ($state === '') {
			$query->where('(a.state = 0 OR a.state = 1)');
		//echo $db->replacePrefix( (string) $query );//debug
		return $query;
	 * Method to auto-populate the model state.
	 * Note. Calling getState in this method will result in recursion.
	 * @since	1.6
	protected function populateState($ordering = null, $direction = null)
		// Initialise variables.
		$app = JFactory::getApplication('administrator');
		// Load the filter state.
		$search = $app->getUserStateFromRequest($this->context.'', 'filter_search');
		//Omit double (white-)spaces and set state
		$this->setState('', preg_replace('/\s+/',' ', $search));
		//Filter (dropdown) state
		$state = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_state', '', 'string');
		$this->setState('filter.state', $state);

		//Filter (dropdown) company
		$company= $app->getUserStateFromRequest($this->context.'', 'filter_company', '', 'string');
		$this->setState('', $company);
		//Takes care of states: list. limit / start / ordering / direction
		parent::populateState('', 'asc');

For the frontend: your $app variable looks like this:

  protected function populateState($ordering = null, $direction = null)
                // Initialise variables.
                $app = JFactory::getApplication();

Modify View (views / zzz / view.html.php)[edit]

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('');

Modify Template (views / zzz / tmpl / default.php)[edit]


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!!

In your template file, this fieldset reflects filter options:

	<fieldset id="filter-bar">
		<div class="filter-search fltlft">
			<input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->searchterms); ?>" title="<?php echo JText::_('Search in company, etc.'); ?>" />
			<button type="submit">
				<?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?>
			<button type="button" onclick="'filter_search').value='';this.form.submit();">
				<?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?>
		<div class="filter-select fltrt">
			<select name="filter_state" class="inputbox" onchange="this.form.submit()">
				<option value="">
					<?php echo JText::_('JOPTION_SELECT_PUBLISHED');?>
				<?php echo JHtml::_('select.options', JHtml::_('jgrid.publishedOptions', array('archived'=>false)), 'value', 'text', $this->state->get('filter.state'), true);?>
			<select name="filter_type" class="inputbox" onchange="this.form.submit()">
				<option value=""> - Select Company - </option>
				<?php echo JHtml::_('select.options', $companyOptions, 'value', 'text', $this->state->get(''));?>


Remark: the name of the select tag must be the same as defined in the populateState function. In the example:

    //populateState function
    $state = $this->getUserStateFromRequest($this->context.'.filter.state', 'filter_state', '', 'string');

    <select name="filter_state" class="inputbox" onchange="this.form.submit()">

Extra: highlighting search terms[edit]

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


Add this somewhere at top somehwere:

$searchterms = $this->state->get('');

//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.


<span id="highlighter-start"></span>
	<table class="adminlist">
<span id="highlighter-end"></span>


If your default admin template doesn't have required css, you should add the class in your component css.

Example in controller:

JHtml::stylesheet('com_peopleactions/admin.css', array(), true);

In admin.css:

.highlight {   background: none repeat scroll 0 0 #FFFF00; }


Javier Constanzo