Wednesday, June 12, 2013

SharePoint 2013 Search: Getting a Value From the Previous Search Result

If you have been playing around with the new Search Display Templates, you have probably seen lots of references to ctx.CurrentItem. This is the current search result item from the result set. However, what about the previous item? Maybe you want to group results or only display certain values if the previous value is different than the current value. The value may be of any managed property or regular property of the CurrentItem object.

There isn't a PreviousItem object so I needed to figure out a different way to get to the previous item. The CurrentItem has a ParentTableReference which contains a collection of ResultRows. Perfect!

The ctx object stores the CurrentItemIdx which can be used to get a particular ResultRow and any property of the search result object (treat it like the CurrentItem).

So now I can get any result value relative to the current result item by using the index as a pointer. The previous item would be ctx.CurrentItemIdx - 1 and the next item would be ctx.CurrentItemIdx + 1.

Here is the logic in a nutshell:

<!--#_ 
        if (!Srch.U.n(ctx.CurrentItem.ParentTableReference) && ctx.CurrentItem.ParentTableReference.TotalRows > 1) {
           var previousIndex = ctx.CurrentItemIdx - 1;
           if (previousIndex >= 0)
           {
                var previousValue = ctx.CurrentItem.ParentTableReference.ResultRows[previousIndex].<<property>>;
               <<<add other conditions and set flags here>>
           }
        }
_#-->



You can now check the previous value of a property against the ctx.CurrentItem value of the property and alter the display or perform other functions accordingly.

Let me know if you find a better way!


 

3 comments:

  1. Using JavaScript, do you know a way to check if a certain URL is a container or folder and not a library?

    ReplyDelete
    Replies
    1. There is an IsContainer managed property that you can include. It is boolean. Do you mean in general or within search?

      Delete