Searching and Filtering is implemented through a form that is displayed above the list of items in the back-end. Site administrators can search or filter the data as per the fields defined in the form.

Step 1: Define XML Form

You need to define the form in xml file in the models/forms folder.

The file name of the form file should start with filter_ and then add the name of the model file name. For example, filter_articles.xml

<?xml version="1.0" encoding="utf-8"?>
<form>
<fields name="filter">
<field
name="search"
type="text"
label="COM_BANNERS_SEARCH_IN_TITLE"
hint="JSEARCH_FILTER"
class="js-stools-search-string"
/>
<field
name="published"
type="status"
label="JOPTION_SELECT_PUBLISHED"
statuses="0,1"
description="JOPTION_SELECT_PUBLISHED_DESC"
onchange="this.form.submit();"
>
<option value="">JOPTION_SELECT_PUBLISHED</option>
</field>
</fields>
<fields name="list">
<field
name="limit"
type="limitbox"
class="input-mini"
default="25"
label="COM_CONTENT_LIST_LIMIT"
description="COM_HELLOWORLD_LIST_LIMIT_DESC"
onchange="this.form.submit();"
/>
</fields>
</form>

Step 2: View File

Add the following code in the view file:

// Adding Filters
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');

Above lines of code will make a call to the model file for functions getFilterForm() and getActiveFilters(). These functions are automatically included through inheritance when you extend your model class with JModelList.

Step 3: Display Form - Template File

Next, you need to actually display the form in the back-end. Add the following code in the form tag, before starting the table.

<?php echo JLayoutHelper::render('joomla.searchtools.default', array('view' => $this)); ?>

Step 4: Modify Query For Search - Model File

You need to modify the query in the function getListQuery() and add where clause if something is entered in the search box.

// Filter: like / search
$search = $this->getState('filter.search');

if (!empty($search))
{
$like = $db->quote('%' . $search . '%');
$query->where('title LIKE ' . $like);
}

Step 5: Modify Query For Filter - Model File

You need to modify the query to apply filters. For example, for status filter,

// Filter by published state
$published = $this->getState('filter.published');

if (is_numeric($published))
{
$query->where('published = ' . (int) $published);
}
elseif ($published === '')
{
$query->where('(published IN (0, 1))');
}

Similarly, you need to modify the query for the other filters in the XML form as well.