WebDrawer sorting

Intro

Chatting with one of our customers I mentioned that implementing sorting in WebDrawer would be pretty simple to implement, probably time to demonstrate that.  Life has been fairly full lately coming up to the pointy end of a release cycle at work and also at home with the imminent arrival of son number 3.  Anyway, took a break from scheduled work this morning...

The scenario

By default the only sort-able property in the record search results is the record number.  You can, however, easily add other properties via the route defaults in hptrim.config, this is documented in the ServiceAPI help and in a number of previous posts on this site.  If you have sortable columns in the search results this code will allow you to convert them to links to sort your search results.

The Code (step 1)

In 83 you will be editing resultsList.cshtml, in prior versions edit searchResults.cshtml.

Add this code to the top, immediately below any 'using' statements.

@functions {

    public string getSort(PropertyOrFieldDef pfdef)
    {        
        if (pfdef.IsAProperty && pfdef.Property.SearchClauseId != SearchClauseIds.Unknown)
        {
            var searchClauses = this.TrimHelper.SearchClausesFor(this.TrimHelper.TrimType);
            SearchClauseDef searchClause = searchClauses.First(sc => sc.Id == pfdef.Property.SearchClauseId);
            var qs = new System.Collections.Specialized.NameValueCollection(this.Request.QueryString);
            
            string sortBy = searchClause.Name + "-";
            foreach (string key in qs.Keys)
            {
                if (qs[key] == searchClause.Name + "-")
                {
                    sortBy = searchClause.Name;
                }                
            }
            qs["sortby"] = sortBy;
            return qs.ToFormUrlEncoded();
        }
        return null;
    }
}

The Code (step 2)

Next find the TH element and replace it with this.

var sortUrl = getSort(pfdef);
if (sortUrl != null)
{                               
    <th><a href="?@sortUrl">@pfdef.Caption</a></th>
}
else
{
    <th>@pfdef.Caption</th>
}

Warning

I have done minimal testing on this, use at your own risk.

Update for 9.x

Due to a change in the underlying framework in 9.x we have one change required in the above code.  The line that once looked like this:

var qs = new System.Collections.Specialized.NameValueCollection(this.Request.QueryString);

should now look like this:

var qs = new System.Collections.Specialized.NameValueCollection(HttpContext.Current.Request.QueryString);
Written on March 29, 2016