ExtJS grid default filter

10 Dec

Recently I came around the situation in which it was required to provide a set of default filters that should be applied to grid during it’s initialization stage so it comes filtered by some specific rules.

ExtJS has it’s ways of doing so and it’s really easy to add a filter to grids column:

Take into account that this sample grid uses remote store (but this will also work with local once).

As you can see on lines from 27-29, default filter value has been set to display both statuses ‘online’ and ‘offline’ but you can set either value separately.

The problem with this approach occurs when you want this filter values set dynamically. More precise – I wanted to route my application with specific set of filter rules set in url, like:


I won’t explain in detail the ways of routing in ExtJS, you can read more about it here (Controlling an Application with Router).


For what it concerns our scenario here, let’s assume that my routing to above-mentioned grid uses this logic:

As you can see, I’m passing two arguments to route handler, filter and value, but I’m not using them at this moment just to show you the routing part.

Next I’m going to modify this handler and add default filters that are going to be processed with a fine plugin.

As you can see I used filter and value arguments and passed them to defaultFilters object’s properties in our grid constructor, note that I haven’t used Ext.util.Filter method since it’s not needed. Also in real world you would like to check if those arguments are passed, etc.

Now what we need to do is to write out our plugin that will handle this approach and than assign it to grid.

The plugin

The plugin will extend Ext.grid.filters.Filters class in one small detail in init method.

As you can see in the code above, we’re checking whether the grid has defaultFilters property set and if it has one, we’ll iterate through each column to check if it’s filter has been set. If there is one, we’ll merge constructors of column’s filter property and our defaultFilter.

At the end, the plugin will initialize columns and render them with default properties set accordingly.

One more thing to do is to assign this plugin to our grid and we’re ready to rock: