Spry

Let users sort data

You can add spry:sort attributes to your dynamic region that allow users to interact with the data. This section uses the table code from Create a Spry dynamic region and display data as an example.

  1. Locate the place in the code where you want to add the spry:sort attribute or attributes. In this example, the attributes are added to two column headers in a table that displays the data.
  2. Add a spry:sort attribute to the appropriate column header tags, using the following form:
    spry:sort="columnName"

    The value defined in the spry:sort attribute tells the data set which column to use when sorting the data

    For example, adding the following spry:sort attributes (in bold) to column header tags sorts the dynamic region data according to the specified value whenever the user clicks a column header on the page.

    <div id="Specials_DIV" spry:region="dsSpecials">
    	<table id="Specials_Table" class="main">
    		<tr>	
    			<th spry:sort="item">Item</th>
    			<th spry:sort="description">Description</th>
    			<th>Price</th>	
    		</tr>	
    		<tr spry:repeat="dsSpecials">	
    			<td>{item}</td>
    			<td>{description}</td>
    			<td>{price}</td>	
    		</tr>	
    	</table>
    </div>

    Clicking Item on the page sorts the data alphabetically according to the menu item name, and clicking Description on the page sorts the data alphabetically according to the menu item’s description.

Numerical sorting

By default, all data in the data set (including numbers) is considered text, and sorts alphabetically. To sort numerically (for example, to sort by price of menu item), you can use the setColumnType data set method to change the data type of the price column from text to numbers. The method takes the following form:

datasetName.setColumnType("columnName", "number");

Using the preceding example, you would add the setColumnType method to the head tag of your document, after you create the data set (in bold):

<script type="text/javascript">
	var dsSpecials = new Spry.Data.XMLDataSet("data/cafetownsend.xml", "specials/menu_item"); 	
	dsSpecials.setColumnType("price", "number");
</script>

The expression calls the setColumnType method on the dsSpecials data set object, which you’ve already defined. The setColumnType method takes two parameters: the name of the data set column to retype ("price") and the desired data type ("number").

You can now add the spry:sort attribute to the price column so that all three columns in the HTML table are sortable when the user clicks any of the table headers:

<div id="Specials_DIV" spry:region="dsSpecials">
	<table id="Specials_Table" class="main">
		<tr>		
			<th spry:sort="item">Item</th>			
			<th spry:sort="description">Description</th>			
			<th spry:sort="price">Price</th>
		</tr>		
		<tr spry:repeat="dsSpecials">
			<td>{item}</td>
			<td>{description}</td>			
			<td>{price}</td>
		</tr>	
	</table>
</div>