How to filter data?

The library provides ability to filter data by one or several criteria. In this case, only items which meet the requirement of criteria will be shown (applicable for all the components that operate on data). To filter data set you need to call the filter() method. Each time the method is called, all data is re-filtered (previous results aren't preserved). It's possible to call the filter method in two modes:

  • filter(property,value)
    This approach is used for 'contains' filtering. It is simple, but isn't flexible. The method shows items where 'property' (the first parameter) contains 'value' (the second parameter). Such a filtering isn't case-sensitive:
$$("grid").filter("type","video");
  • filter(function)
    Using function as a parameter allows to define different filter rules and to filter by multiple properties. Filtering function is called for each object of the data set, and if it returns true, the object will be displayed:
$$("grid").filter(function(obj){
        if (obj.sales > 10 && obj.company == "Company 3") return true;
        return false;
})

Example

We'll create a window that will contain a list of movies. By using filter() method we'll display just films created in 2010 year.

Our actions:

  1. Define a window and a list component inside it.
  2. Attach event 'onxle' which is invoked when XML parsing is over. We use exactly it to synchronize data loading and filtering processes.
  3. Specify filter criteria.

HTML code

FilterExample.html

<body>
   <script type="text/javascript" charset="utf-8">
	dhx.ui({
		  height:215,
		  view:"window",
	      head:{
			view:"toolbar", type:"MainBar",
			data:[{type:"label", label:"2010 Movies "}]
		  },
          body:{view:"list", id:"mylist", url:"movies.xml", datatype:"xml",
			  template:"#name#", select:true, type: { width: 300 }
		  },
	  top:20,
          left:20,
          move:true
    });
	$$("mylist").attachEvent("onxle", function(){
			this.filter("#year#","2010");
	});
   </script>
</body>

XML structure

movies.xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <item id="1">
    <name>The Gold Rush</name>
    <year> 1925 </year>
  </item>
  <item id="2">
    <name>The Last Airbender</name>
    <year> 2010 </year>
  </item>
  <item id="3">
    <name>Gone With The Wind</name>
    <year>1939</year>
  </item>
  <item id="4">
    <name>The A-Team</name>
    <year>2010</year>
  </item>
  <item id="5">
    <name>Piranha 3D</name>
    <year>2010</year>
  </item>
  <item id="6">
    <name>Fantasia</name>
    <year> 1940 </year>
  </item>
  <item id="7">
    <name>The Book of Eli</name>
    <year>2010</year>
  </item>
  <item id="8">
    <name>King Kong</name>
    <year>1933</year>
  </item>
</data>