Thursday, 15 November 2007

Sharepoint 2007: Creating a custom advanced search webpart - Part 1

Following the post about the Creating a custom advanced search box in moss 2007 article, I did a few customisations of my own.

So let's give a few examples of what can be done with this new toy:

Remember that you need to create a web part page, and add a Content Editor Web Part and a Search Core Results web part (as defined by the linked article).

1. Creating a search box limited to a single scope (without the user having to select the scope to limit too)
Typically you'll have clients who want advanced search capabilities limited only to certain lists only. The way we usually do this is to create a custom search scope and then enable the Scopes in the advanced search. This is ok but not good enough for some clients who want to make this capability transparent to the user. Therefore we create a custom advanced search which by default only limits results to a particular scope.

We need to add the following code to the Content Editor Web Part

<input name="nameprefix$ASB_TQS_AndQ_tb">
<input name="nameprefix$ASB_TQS_PhraseQ_tb">
<input name="nameprefix$ASB_TQS_OrQ_tb">

This codes will create the three text boxes which will give us:

  • Search All of these words
  • Exact phrase
  • Any of these words


Next is the search scope limitation. This requires some more tinkering. First of all go to advanced search page which is available by default. Enable the scope picker in the Advanced Search Web part options. Then view the source of the page, and find the name of the search scope you want to limit to. This will be in a label which has should have end with a name similar to the following: ASB_SS_scb_x_x where each x is a number. In my case I have ASB_SS_scb_1_4.

This is the parameter we need to send to the search. Therefore you need to create a hidden input box with this parameter:

<input name="nameprefix$ASB_SS_scb_1_4" value="nameprefix$ASB_SS_scb_1_4" type="hidden" >

This will send this parameter automatically to the search instead of requiring the user to check the required scope checkbox.

The last thing to do is define the Search box and the postback to the page which will display the results.

Complete code:

<input name="nameprefix$ASB_TQS_AndQ_tb" type="text" /></td></tr><tr><td><input type="hidden" name="nameprefix$ASB_SS_scb_1_4" value="nameprefix$ASB_SS_scb_1_4"/>

<INPUT id="Submit1" onclick='WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("nameprefix$ASB_BS_SRCH_1", "", false, "", "/Pages/CustomSearch.aspx", false, false))' type="submit" name="nameprefix$ASB_BS_SRCH_1" value="Search" />

So here we are limiting your advanced search to a particular scope only. Part 2 will deal with creating a drop down to limit search results to particular metadata / categories only. For more details on how this was created, visit Tom Clarkson's post.