Jan 6, 2011

Episerver CMS 6 search

Had to make some additional staff in EPiServer search functionality. I had to add ability to filter pages by category, page type, and keyword in content. Firstly I have tried to do it with DataFactory.Instance.FindPagesWithCriteria method. But the thing is that I couldn’t  find a way to filter data by search keyword.

I knew that SearchDataSource does this somehow and wanted to reuse that logic. But when I looked at it in reflector, I found a method 100 lines long doing some really fancy staff to make select by keywords. So the best way to make search that I need is to do it through SearchDataSource.

Fortunately it provides public property called Criteria. It is a criteria that are going to be passed for underlying DataFactory.FindPagesWithCriteria call.

So the search that I needed could be implemented in the this way. Aspx part:

<EPiServer:SearchDataSource ID="uiSearchDataSource" runat="server" EnableVisibleInMenu="false"
                            PageLink="<%# PageReference.StartPage %>">
    <SelectParameters>
        <asp:QueryStringParameter Name="SearchQuery" QueryStringField="search" DefaultValue="" />
    </SelectParameters>
</EPiServer:SearchDataSource>

And in code behind:

var pageTypeCategory = new PropertyCriteriaControl(new PropertyCriteria
                            {
                                Condition = CompareCondition.Equal,
                                Name = "PageTypeID",
                                Type = PropertyDataType.PageType,
                                Value = PageType.Load("Article").ID.ToString(),
                                Required = true
                            });

var pageTypeCategory1 = new PropertyCriteriaControl(new PropertyCriteria
                            {
                                Condition = CompareCondition.Equal,
                                Name = "PageCategory",
                                Type = PropertyDataType.Category,
                                Value = Category.Find("category2").ID.ToString(),
                                Required = true
                            });

this.uiSearchDataSource.Criteria.Add(pageTypeCategory);
this.uiSearchDataSource.Criteria.Add(pageTypeCategory1);

Note that Name property of each criteria should be as shown in code above, otherwise it won’t work. Hope it helps someone!