Making a context sensitive content query web part

conker8[1]I will start by explaining the picture – after I thought of the title of this blog post the very next thing I thought of was from Conker’s Bad Fur day (which if you haven’t played, go and get it. It was originally released on the N64 but is also on the Xbox and I believe is backwards compatible with the 360). Anyway there is a scene in it where a drunk scarecrow is trying to explain what context sensitive is to conker, who at this point is also still a bit drunk – good times.

Anyway, onto the serious stuff. The requirement I am solving with this one is to make a content query web part automatically pick up items from the current web without me having to tell it where that web is. let me explain that a bit better – I am using a delegate control to put a content query web part into a page layout, and the page layout will be used across the entire site collection. I want the content query web part to display items based on the current site when a user browses to a page that uses this layout – so in other words, the web part needs to be context sensitive … sensitive to context (another Conker reference there).

So the bad news is OOTB you need to specify the WebURL property to tell the web part where to get its items from, the good news though is that it is very, very easy to override the content query web part to add this functionality. Here is the entire class that I wrote to add this functionality:

public class CurrentSiteContentQuery : Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.WebUrl = this.WebUrl.ToLower().Replace("~site", SPContext.Current.Web.ServerRelativeUrl);

    }
}

Yep, thats it. When I put “~site” into the WebURL property that will resolve to the current URL that is gets from the SPContext property. So now I just tell my delegate control to use my web part instead of the OOTB one and I’m done, context sensitive queries are now appearing in my page layouts. Its a beautiful thing.


    • Brian Farnhill
    • January 27th, 2008

    Using the delegate control means the web part can be updated independantly of the page layout. Makes things more isolated rather than joing it all togther in the page layout itself

    • Marius
    • January 27th, 2008

    Hi Brian,
    I need to follow the exact same scenario you describe, however I do not quite grasp why you use the DelegateControl in the 1st place, instead of..e.g. deploy the custom page layout directly having your custom CQWP within. Otherwise, quite a good trick, thank you, Marius c.

  1. No trackbacks yet.