Andrew Connell [MVP MOSS]
1402 Posts |  39 Articles |  3659 Comments
.NET  |  MCMS  |  SharePoint  |  Office System
SharePoint Quick Links
Article Categories
Archives
Post Categories


Add to Technorati Favorites

The Content Query Web Part (CQWP) is an absolutely killer for MOSS 2007 Publishing sites. It is one of the best performing rollup Web Parts available to developers and should always be considered before rolling your own solution. You can even do some really sick customization to the presentation of the results produced by the CQWP as shown in this post on the ECM team blog by George Parantatos, a PM on the product team:

» ECM Team Blog: Configuring & Customizing the CQWP

However there are two things I always hear about the CQWP in terms of wish list type stuff:

  1. It doesn’t contain any built-in paging mechanism… yeah, I too wish for this.
  2. It doesn’t support dynamic filtering. For instance, I have to manually specify the filtering values rather than have them be dynamically set.

Before you rush off and roll your own, stop, get a cup of coffee, and saddle up next to your laptop. With just a few lines of code you can utilize the provided CQWP but add your own customizations. Take the second pain point: no dynamic filtering. Let’s say you have a slew of content and you want to dynamically set the filtering values, say for example, using values on the query string.

So, we start with a site filled with pages. In the below screen shot, you’ll see a subsite called Widgets that contains 10 pages. Each of these pages contains some bogus content, but there is a field called Division that has one of a few different values in it.

PagesLibrary

When I add the OOTB CQWP to the page, the default view gives me all pages in the site:

NoCustomizations

I could tweak the filtering values in the Task Pane by setting the Division field to Europe. But… what if I want to make this dynamic?

OK, time to whip open Visual Studio. What I’ll do is create a new Web Part that inherits directly from the CQWP: Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart. Let’s take a look at the properties available to us. Hey, I see two that are good candidates: FilterField1 & FilterValue1. No guessing involved, the names say exactly what they do. So, what if I set the values of those properties on the fly, but let the rest of the CQWP do its work? Ah… now it’s party time!

What I’ll do is override the OnLoad() method and do a quick check to see if there is something expected on the query string… if not, then I need to just stop here… nothing to do. But, if there IS something there… ah… now that’s where I want to add my special sauce. Here’s the code, followed by an explanation.

Code

First, I need to set the chaining operator. That is the AND/OR switch you set when you are setting filter values using the Task Pane for the CQWP. In this case, I just want to set the Filter1ChainingOperator to OR the two values (line #15). Next, I need to get the name of the field & value to filter by from the query string (lines #18 & 22). Before going further, we need to deal with a little curve ball the CQWP throws at us. When it filters on a specific field, it does so not using the field by name, but by the field’s ID. So we need to get the field’s GUID which we can do by looking at the current lists’s Fields property (or, more specifically, we can look at any item in the list as I do in the code above) (line #20). Last but not least, set the values on the CQWP’s fields (lines # 25 & 26).

Now… package everything up and deploy it just like any other Web Part. All that’s left is to add it to a page. Initially it does the exact same thing as the stock CQWP because no query string filter values are set. But when you add them manually (or through some link on your site), you’ll see it does the filtering as shown in the following image! You can even see the values are set when you look at the query builder in the Task Pane.

Customizations

And there you have it… a subclassed CQWP implementing dynamic filtering in less than 30 lines of code. Hey, if you look at the guts of the solution, the whole thing is really only 8 lines of code in the OnLoad() method! Now that’s easy!

You can download the source of the project I created to pick through it yourself. There’s already a WSP in the ZIP that you can deploy to see this guy in action.

» ContentQueryExWebPart – dynamic filtering sample source

posted on Monday, February 18, 2008 4:18 PM

Feedback

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/19/2008 1:17 AM Waldek Mastykarz
Gravatar Great post presenting the power of extensibility of SharePoint.
CQWP is definitely a great part of SharePoint: especially when you look at the performance considerations. What holds me back is the way you would deploy it including the custom XSL styles. As either overwriting or extending the existing ItemStyle.xsl isn't an option, it seems like the only one left out there is exporting the CQWP, changing the references to point to some CustomItemStyle.xsl and then use that instance. Am I right or am I missing something?

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/19/2008 2:21 AM Kristof Eschberger
Gravatar hooray! you're my hero!
great post, thanks!

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/19/2008 8:31 AM AC [MVP MOSS]
Gravatar Waldek-
That's how I do it.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/19/2008 4:41 PM Chris
Gravatar Great post. Was wondering if you have come across how to be able to expand/collapse a grouping header? I am able to get everything else working correctly but also want the functionality to be able to expand/collapse headers with the CQWP.

Thanks

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/22/2008 6:10 PM George Perantatos
Waldek, what is preventing you from editing the ItemStyle.xsl to customize styles?

As a side note, you also have the option of making a web part available in the web part gallery that's pre-configured to point to your own XSL, so when users drag/drop it on their pages it's picking up CustomItemStyle.xsl and not ItemStyle.xsl.

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/23/2008 6:00 AM Waldek Mastykarz
Gravatar George-

As it is totally plausible you will manually edit the ItemStyle.xsl in your dev environment, it is not something you are likely to do while deploying your solution to the production env. As you are not allowed to modify through your custom Feature any file provisioned by another Feature, the only possibility left out there is provisioning your own CustomItemStyle.xsl containing the required templates.
I know that you can create your own preconfigured instances of CQWP. Yet it doesn't always seem right if you compare the amount of work you need to do in order to make the CQWP does slightly something else than expected. I think that understanding the way the CQWP works would allow SharePoint developers to create their own Web Parts leveraging the great performance approach used by the CQWP and yet providing a higher flexibility level.

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 2/23/2008 9:52 AM AC [MVP MOSS]
Gravatar George/Waldek-
While customizing the ItemStyle.xsl file is certainly an option, in the real world I don't see it as a good one. The primary reason is because customizing it affects all instances that use it which I find most people don't like in the real world. They would rather customize it for a specific instance, at least 50%+ say this from my exp. Thus, it's basically manditory that you have to create custom XSL files. One negative thing about this is not being able to put an absolute link in the Web Part definition... you have to put a relative link back to the file which is a challenge in bigger sites.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 3/17/2008 11:07 AM Joaquín
Gravatar Very nice article.

It happens to me that filtering properties are used only after I've edited web part properties and saved them.

It looks like "customization engine" knows no user has modified webpart properties so it uses its default values all the time (no filtering).

If after inserting the web part in may page I check its properties, I see they are correctly set.
I then I jus press apply button filtering happens from then on.

How could I solve this. Am I doing anything wrong?
Any help would be appreciated.

Thanks,
Joaquín.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/10/2008 2:37 AM Bo Huge
Gravatar Hi,

Which properties do I have to change in order to make my customItemStyle.xsl visible to the WP? An how do I reference it? I tried changing ItemXslLink to /Style Library/XSL Style Sheets/MyCustomItemStyle.xsl, but the CQWP tells me it can't find the xsl. Am I forgetting something?

Thanks in advance.

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/10/2008 10:07 AM AC [MVP MOSS]
Gravatar Bo-
That's the correct property (ItemXslLink). If the CQWP is nested in a subdirectory you might have to get creative pointing to the the XSL file.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/17/2008 9:19 AM Troy
Gravatar Hi!

Thanks for the great tips, Andrew! Do you know of any way to modify the CQWP to work outside of the Site Collection scope? There is a big demand in our company for a rollup like CQWP part that works across different Site Collections .

Thanks again!
Troy

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/17/2008 1:02 PM AC [MVP MOSS]
Gravatar Troy-
No... it is not possible for the CQWP to be scoped outside the current site collection. However I'd recommend you check this Web Part out: http://www.lightningtools.com/pages/lightning-conductor-web-part.aspx. It does a great job of acting like a cross-site collection CQWP.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/18/2008 2:09 PM Troy
Gravatar Thanks Andrew!

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/22/2008 12:38 AM Anthony Kasses
Gravatar Hi Andrew,

Really nice article.

What if I want to return random pages/items from that site? Can this be done by overriding the CQWP as well, or do I need to start from scratch with a custom web part. Seems a pity to do that because this OOB web part is exactly what I need, ..I've written the xslt, ....just missing, like you say, more dynamic filter options.

thanks.

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 4/22/2008 9:00 AM AC [MVP MOSS]
Gravatar Anthony-
You might be able to do this with some sort of fancy XSLT that randomized the result set passed down by the CQWP. Or you could take the CQWP an make it do some randomized filter to pull the content back too.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 5/7/2008 6:43 AM superolaf
Gravatar Hi, I have some problems while trying to sort my CQWP based on my own fields, added under commonfields in the web part. I get the following error:

Value does not fall within the expected range.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Value does not fall within the expected range.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[ArgumentException: Value does not fall within the expected range.]
Microsoft.SharePoint.SPFieldCollection.GetFieldByDisplayName(String strDisplayName, Boolean bThrowException) +153
Microsoft.SharePoint.SPFieldCollection.get_Item(String strDisplayName) +61
ContentQueryExWebPart.ContentQueryExWebPart.OnLoad(EventArgs e) +578
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2604

Can someone help me with this?

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 5/7/2008 7:49 AM AC [MVP MOSS]
Gravatar superolaf-
Not possible to say without knowing exactly what's going on. My guess is you are setting a value (or not setting a value) on a field the CQWP needs. Debug that Web Part and find out what property you're trying to set or what property is throwing an error. From the call stack, it's something about a specific field.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 5/23/2008 9:43 AM mark
Gravatar i want to cehck page column with cqwp list field for filter. pls help me out

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 5/23/2008 10:28 AM AC [MVP MOSS]
Gravatar Mark-
From within the same class you're subclassing, just look at the current page's fields using SPContext.Current.ListItem.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 5/26/2008 5:18 AM Bo Huge
Regarding customitemstyle.xsl. Changing the reference using the property ItemxslLing works, if I create my site coll from the root, but if I create the site coll. under sites (server/sites/sitecoll) the link doesn't work. I then get the error: Xsl cannot be found...

Has anyone found a way to handle this?

Best regards.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 6/2/2008 5:24 PM Mdeveloper
Gravatar Anyone can help me how to add sorting to the content query webaprt?

~Mdeveloper

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 6/3/2008 7:34 AM AC [MVP MOSS]
Gravatar Mdeveloper-
It's there OOTB

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 6/6/2008 11:08 AM arec
Great MAN!!! Clear and Simple

Thanks!!

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 6/27/2008 2:02 PM Steve
Gravatar Hi, thx for this..its a great post, really helpful.

I wondered if you have experienced any problems with spaces e.g. If the value in the list has a space in, this method doesnt work.
I have %20 in the URL for the space, and when I trace the value it shows the space, but does not return and results.
Search for values without spaces...works perfect.

Any ideas??

Thx.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/3/2008 6:07 AM bhargavi
Gravatar a very good post... i wanted to check if we can achieve the expand/collapse of the grop headers in CQWP. Is this possible with content query webpart?



# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/3/2008 7:32 AM AC [MVP MOSS]
Gravatar bhargavi-
Sure... you can do that but it won't be done with a subclassed CQWP. Instead you want to look at doing something with custom styles and injecting your own DHTML that knows how to collapse groups.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/7/2008 5:21 PM paisley
Gravatar Steve -- RE: the "space" issue
the encoded value is _x0020_ not %20


 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/9/2008 2:04 AM Meera
Gravatar Great post.....great idea....thanx a lot !!
Is there any way we can use CQWP to display the latest 5 documents....to be more precise....the most recent 5 documents added to document libraries in a site??
How can we use a timer in conjunction with CQWP?

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/9/2008 9:55 AM AC [MVP MOSS]
Gravatar Meera-
Sure you can do that. Just sort the modified/created date in descending order, select only libraries of type Document Library, and set the paging to 5. You don't need any custom code here! I don't get your question about timers.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/14/2008 6:19 AM Kieran
Hi Andrew,

I've downloaded and installed the wsp. Then activated in my MOSS site. When I try to add it to a page I get a dialog:

Unable to add the selected web part(s)

ContentQueryExWebPart: An error has occured.

Any idea's?

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/14/2008 9:11 AM AC [MVP MOSS]
Gravatar Kieran-
Nope... not with that information. Look at the SharePoint logs, turn off the custom errors and turn on the call stack to give you more details.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 7/21/2008 5:59 AM Kieran
Andrew,

It seemed I needed to change the trust level to medium to get this to work - Is that the best approach?

All the best.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 8/5/2008 4:30 AM Kieran
Hi Andrew,

Would it be possible to make this sub classed web part filter the returned values based upon a parameter passed in on the url that decides which site to display items for?

For example:

?Filter1Field=Division&Filter1Value=Europe&Site=Departments

I'm trying to prevent having to duplicate the contentquerywebpart on different pages in different sites and instead have one page that takes care of things.

All the best

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 8/5/2008 8:51 AM AC [MVP MOSS]
Gravatar Kieran-
Sure... that's just another property of the CQWP. Look at the WebURL property on the CQWP.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 8/13/2008 10:54 AM James McDonnell
Gravatar Hi Andrew,
I'm having the same problem that Joaquín posted back in March:
It happens to me that filtering properties are used only after I've edited web part properties and saved them.

It looks like "customization engine" knows no user has modified webpart properties so it uses its default values all the time (no filtering).

If after inserting the web part in may page I check its properties, I see they are correctly set.
I then I just press apply button filtering happens from then on.

How could I solve this. Am I doing anything wrong?
Any help would be appreciated.


 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 8/14/2008 5:17 AM Tim
Gravatar Nice article thanks, CQWP is indeed very useful. I wonder though if the purpose to which I am trying to apply it now is correct or if I am asking the wrong web part to do something it can't.

I often have clients ask me to build a page that displays sites, or lists or libraries and display the results as a weburl. They are looking for a dynamically created "site" map. If the add a new wiki library then the link to the new library will be added to the page. Add a new discussion and bingo, new link. And of course add a blog or team site and the link to the site is also dynamically created.

I am struggling trying to understand which the right web part is. I can find zero documentation on the "sites in category" web part so have been putting effort into the CQWP. But am I wasting my time? Would appreciate any guidance offered very much.

Cheers

Tim

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 8/15/2008 4:47 PM Mike Sharp
Gravatar Hi Tim,

Have you looked at AccessChecker on Codeplex? This is intended for site administrators, but it's not too much of a stretch to think of this as a site map. It not only provides a site map, but it's security trimmed as well:

http://www.codeplex.com/AccessChecker

Regards,
Mike Sharp

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 10/14/2008 2:29 PM Ketan
Gravatar Hi Andrew,
Can we add the dynamic filter as a dropdown control to the CQWP, so that the user can on the fly change the filter criteria and the CQWP will only display the filtered items. To add one more twist can this be added to a UPDATEPANEL, to get the ASYNC (AJAXED :) ) effect, so that the entire page will not post back.
Appreciate your response.
Any steps towards achieving this.

Regards



# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 10/14/2008 3:30 PM AC [MVP MOSS]
Gravatar Ketan-
I don't see why you couldn't do this... but it's all custom stuff (ala subclassed). Steps? Yeah... go try it yourself :)

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 10/16/2008 9:15 AM Ketan
Gravatar Thanks for the quick response Andrew, I am new to AJAX and MOSS also. Can you please let me know what would be the steps to implement this for AJAX style CQWP. Is it like subclass the CQWP, expose the column property (basically set the column/field that will allow users to select the filter critieria i.e. the field value). Can we put webparts directly into the UpdatePanel of AJAX controls.
I am sorry to bother you again on this, but as your the champ of WCM I thought only guru can answer me the best.

Thank you

# re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 10/16/2008 12:30 PM AC [MVP MOSS]
Gravatar Ketan-
I'm not sure you can easily throw a CQWP into the UpdatePanel... you'd just have to try it. Sorry I can't provide more guidance here... would require just taking time to try some stuff out.

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 10/22/2008 2:47 AM wibrand
Gravatar Hi Andrew.

Great post about the CQWP.

I have implemented it on a page where dynamic filtering is needed, but my problem is that I need to have two filter values. When I have implemented this – the CQWP won’t filter correctly. When I look in the edit webpart settings on the front end, I can see my two filter fields and values, but I have to press apply on for the CQWP to show me the correct result.

I can’t figure out why this is a problem.

Cheers


 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 10/23/2008 11:41 PM MOSSBUDDY
Gravatar AWESOME POST and what else can we expect from a great guy ANDREW.
This is really very good stuff and right on target for one of my requirements, thanks Andrew for sharing this with us.

I would like to ask as we filter the CQWP by clicking on some link and then going to a page that contains this CQWP that filters the results, is there anyway to set the TITLE of the CQWP as the selected FILTER criteria?
i.e. if I am on some page that shows 10 items and if I click on one of the items it takes me to the detailed page for that item (via the filter criteria of CQWP) and also set the title of the CQWP to the selected criteria, can we do this in the Onload event of CQWP?

 re: Subclassing the Content Query Web Part: Adding Dynamic Filtering 11/6/2008 11:27 AM Thomas
Gravatar I have a DataSheet View webpart. Is there any method to filter it dynamically by reading value from querystring?

Thank You,
Thomas

Post Feedback

Title:
Name:
Email:
(email will not be displayed)
Url:
Comments: 
Please add 3 and 3 and type the answer here:    
All Comments Are Filtered & Moderated
Unfortunately comment spammers are just too effecient and are constantly dirtying up blogs with irrelivant and unwanted comments trying to improve their standing on search engines. All comments on this blog are moderated. I do not censor comments, but I don't approve comments with vulger language or those soliciting products. Most of the time comments are approved within a few hours of being submitted with the only exception when I'm traveling.

Why are you asking for my email address?
The only reason I'm asking for your email address, which isn't required to submit a comment, is to provide a gravatar if you've created an account for yourself and associated your email address with a small image. If you have a gravatar created for the email address you submit, it will appear next to your comment. Otherwise nothing will appear.

What is a gravatar?
A gravatar is a "globally recognized avatar." You can get more information about gravatars, as well as create your own for free, at www.gravatar.com. You can also view my gravatar here.


Copyright © 2003 - 2008 Andrew Connell
Creative Commons License 
This work is licensed under a Creative Commons License
Site design by Heather Solomon.

 
 
MOSS WCM Training
Looking for MOSS 2007 WCM developer training? Look no further! I teach my 4-day hands-on and 5-day online WCM classes for developers I offer through the Ted Pattison Group.

Get more information on the WCM courses!


Upcoming Classes
 Hands-on WCM:
 » Tampa, FL
   Jan 12-15, 2009
 Online WCM:
 » Dec 8-12, 2008


» Register today!

JAX Office Geeks
Jacksonville Office Geeks (JOG)
JOG is a special interest group in Jacksonville, FL dedicated to bringing the local SharePoint commnity together to share tips, tricks, ideas and best practices for developing solutions on the SharePoint platform.

Next meeting details...
When:
Thur. Nov 20th, 2008
  6-8p EDT
Topic:
Creating & Debugging Custom Timer Jobs in WSS

Speaker:
Andrew Connell, MVP MOSS

RSVP Today!


» Subscribe to the JOG newsletter