Skip to main content

Cloud

Using the content query web part with a custom query

As you may have noticed, I am on a content query web part (CQWP) kick these days… J Here is one more installment in the saga…

I have a requirement to create a CQWP that shows the pages in a pages library that have a custom date field that is between today and a week from today. I tried to do this via the CQWP UI but that UI won’t let you enter in a date in the format of Today + 7; it only allows you to specify a specific date. What I needed was a sliding window and I couldn’t figure out how to do that via the UI.

Along comes an MSDN article about customizing the CQWP using custom properties. Once you read this article, make sure that you read the entries at the bottom that are an addendum to the article. If you don’t, you will be banging your head against the wall trying to get it to work. This article shows you how to set the QueryOverride property of the web part to bypass the query UI and set your own CAML query.

The one gotcha that I encountered with this is the difference between using the string "[Today]" and the string "<Today />" to specify the current date. The article shows using the XML tag "<Today />" but it is a valid CAML query if you use "[Today]" to specify today’s date. In order to formulate my query, I used the U2U CAML Creator (found here). This tool uses the "[Today]" string to formulate its queries. My big problem was that my query worked in the CAML Creator but did not work in the web part. Once I changed my web part file (.webpart) to use the "<Today/>" string, everything worked as planned.

The moral of this story is that if you are creating date based queries to implement the QueryOverride property, don’t use the "[Today]" format and use the "<Today/>" format. If you need to set a date range, you can use code that looks like this:

<Where>
<And>
<Geq>
<FieldRef Name="EventStartDate" />
<Value Type="DateTime"><Today/></Value>
</Geq>
<Lt>
<FieldRef Name="EventStartDate" />
<Value Type="DateTime"><Today OffsetDays="7"/></Value>
</Lt>
</And>
</Where>

The "OffsetDays" attribute of the <Today/> element allows you to create that sliding window.

Hope this helps…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PointBridge Blogs

More from this Author

Follow Us