Monday 11 March 2013

Display Content Query Web Part Results in a Grid / Table

Overview and Objective

Out of the box, MOSS’ Content Query Web Part (CQWP) displays its results in a list format, similar to search results.  It is also possible to display the results in a grid format (i.e. HTML table format).  Grid formats are better in some circumstances.  I describe how to achieve that effect in this article.

Business Scenario

I have worked with a client on an enterprise-wide MOSS rollout.  We have designed their taxonomy such that projects are first class citizens in the hierarchy and have their own top level site.  Project managers maintain a singleton list of project summary information, such as title, budget, expected completion date, remaining budget and other summary type fields.  By "singleton" I mean a custom SharePoint list guaranteed to contain only one item.   Simplistically, it looks like this:

The CQWP uses an XSL transform to emit HTML for the browser to render.
I always envision the result before diving into the XSL because XSL is a nightmare.  Here’s my desired result:

HTML like this generates that result:
 
<html>
  <body>
    <center>
    <table border=1>
      
      <!-- Labels -->
      <tr bgcolor=blue>
        <td><font color=white><b>Project Name</b></font></td>
        <td align=right><font color=white><b>Complete Date</b></font></td>
        <td align=right><font color=white><b>Budget</b></font></td>
        <td align=right><font color=white><b>Actual Expense</b></font></td>
        <td><font color=white><b>Overall Status</b></font></td>
      </tr>
      
      <tr>
        <td>Re-wire computer room.</td>
        <td align=right>02/01/08</td>
        <td align=right>22,500.00</td>
        <td align=right>19,000.00</td>
        <td>In Progress</td>
      </tr>
        
      <tr>
        <td>Provision servers for SQL Upgrade</td>
        <td align=right>04/01/08</td>
        <td align=right>7,500.00</td>
        <td align=right>0.00</td>
        <td>Planned</td>
      </tr>
        
    </table>
    </center>
  </body>
</html>

Approach

Follow these steps to create the grid:
  1. Identify the components of the grid (rows/columns).
  2. Define and create necessary site columns.
  3. Create sub sites for the projects and singleton lists.
  4. Add the CQWP to a web page and configure it to search for your lists.
  5. Modify the CQWP’s XML to gather up the additional columns.
  6. Modify the XSL to generate a table.
I’m going to concentrate on number six.  Numbers one through four are straight-forward and something that any CQWP user has already done.  Number five has been well-documented by others including this exhaustive screen-shot laden article from MSDN here (http://msdn2.microsoft.com/en-us/library/bb897399.aspx

Nuts And Bolts

Begin and implement steps one through five as per the MSDN documentation and Heather Solomon’s article.
At this point, you’ve added your CQWP to the page and you have your <CommonViewFields> configured as necessary.
Following the usual steps, I get these intermediate results:
1. Create a content type, a templatized custom list for that content type and two sites.  Here is the content type:

Here is the site structure:

2. Add the CQWP after creating my project subsites and singleton project summary lists:

3. Add all the additional information I want via the <CommonViewFields>:
        <property name="CommonViewFields" type="string">Project_x0020_Name;Project_x0020_Expenses;Project_x0020_Status;Project_x0020_Start_x0020_Date;Project_x0020_End_x0020_Date;Project_x0020_Budget</property>
Note that I had to keep all the property fields on one line or it would not work (CQWP would tell me that the query returned no items).
4. At this point, we’re ready to move beyond the MSDN article and flip on over to Heather Solomon’s article.  Follow her steps starting near step #5 to create a customized / unghosted version of ItemStyle.xsl.  I follow Heather’s advice, up through step 11 and get these intermediate results:
4.1: Name my XSL template as follows:
<xsl:template name="Grid" match="Row[@Style='Grid']" mode="itemstyle">
I also slightly modify her suggested <xsl:for-each …> by adding a <br/> tag to provide a cleaner listing:
    <xsl:for-each select="@*">
      P:<xsl:value-of select="name()" /><br/>
    </xsl:for-each>
4.2: I modify the web part, go to appearance and select my "Grid" style:

Apply the change and here is the result:

We can see from the above that the fields we want (Project name, expense, status, etc) are available for us to use when we emit the HTML.  Not only that, but we see the names by which we must reference those columns in the XSL.  For example, we reference Project Status as "Project_x005F_x0020_Name".
At this point, we depart from Heather’s blog and from the shoulders of these giants, I add my own little bit.

ContentQueryMain.xsl

NOTE: When making changes to both ContentQueryMain.xsl as well as ItemStyle.xsl, you need to check those files back in before you see the effect of your changes.
For grid-making purposes, MOSS uses two different XSL files to produce the results we see from a CQWP.  To generate the previous bit of output, we modified ItemStyle.xsl.  MOSS actually uses another XSL file, ContentQueryMain.xsl to in conjunction with ItemStyle.xsl to generate its HTML.  As its name implies, ContentQueryMain.xsl is the "main" XSL that controls the overall flow of translation.  It iterates through all the found items and passes them one by one to templates in ItemStyle.xsl.  We’ll modify ItemStyle.xsl to generate the open <table> tag before emitting the first row of data and the closing <table> tag after emitting the last row.  To accomplish this, ContentQueryMain.xsl is modified to pass two parameters to our "grid" template in ItemStyle.xsl, "last row" and "current row".  ItemStyle.xsl uses these to conditionally emit the necessary tags.
Using Heather Solomon’s technique, we locate ContentQueryMain.xsl.  It is located in the same place as ItemStyle.xsl.  This screen shot should help:

We need to make the following changes:
  • Modify an xsl template, "CallItemTemplate" that actually invokes our Grid template in ItemStyle.xsl.  We will pass two parameters to the Grid template so that it will have the data it needs to conditionally generate opening and closing <table> tags.
  • Modify another bit of ContentQueryMain.xsl that calls the "CallItemTemplate" to pass it a "LastRow" parameter so that LastRow may be passed on to our Grid template.
Locate the template named "OuterTemplate.CallItemTemplate" identified by the string:
  <xsl:template name="OuterTemplate.CallItemTemplate">
Replace the whole template as follows:
 
  <xsl:template name="OuterTemplate.CallItemTemplate">
    <xsl:param name="CurPosition" />

    <!-- 
      Add the "LastRow" parameter. 
      We only use it when the item style pass in is "Grid".
    -->
    <xsl:param name="LastRow" />

    <xsl:choose>
      <xsl:when test="@Style='NewsRollUpItem'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="EditMode" select="$cbq_iseditmode" />
        </xsl:apply-templates>
      </xsl:when>
      <xsl:when test="@Style='NewsBigItem'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="CurPos" select="$CurPosition" />
        </xsl:apply-templates>
      </xsl:when>
      <xsl:when test="@Style='NewsCategoryItem'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="CurPos" select="$CurPosition" />
        </xsl:apply-templates>
      </xsl:when>

      <!-- 
              Pass current position and lastrow to the Grid itemstyle.xsl template.
              ItemStyle.xsl will use that to emit the open and closing <table> tags.
      -->
      <xsl:when test="@Style='Grid'">
        <xsl:apply-templates select="." mode="itemstyle">
          <xsl:with-param name="CurPos" select="$CurPosition" />
          <xsl:with-param name="Last" select="$LastRow" />
        </xsl:apply-templates>
      </xsl:when>

      <xsl:otherwise>
        <xsl:apply-templates select="." mode="itemstyle">
        </xsl:apply-templates>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
The comments describe the purpose of the changes.
Of course, the "OuterTemplate.CallItemTemplate" is itself called from another template.  Locate that template by searching for this text string:
<xsl:template name="OuterTemplate.Body">
Scroll through the instructions in OuterTemplate.Body and insert the LastRow parameter as follows (shown as a comment in italics):
<xsl:call-template name="OuterTemplate.CallItemTemplate">
  <xsl:with-param name="CurPosition" select="$CurPosition" />
  <!-- Insert the LastRow parameter. -->
  <xsl:with-param name="LastRow" select="$LastRow"/>
</xsl:call-template>
After all of this, we finally have things set up properly so that our ItemStyle.xsl can emit <table> tags at the right place.

ItemStyle.Xsl

NOTE: Again, check in ItemStyle.xsl after making any changes so that you see the effect of those changes.
We have two tasks here:
  • Replace the entire Grid template.  You can copy/paste from below.
  • Add some mumbo jumbo outside the template definition that enables "formatcurrency" template to work.  (You can tell that I have a tenuous handle on XSL).
First, near the top of ItemStyle.xsl, add this line:
  <!-- Some mumbo jumbo that enables us to display U.S. currency. -->
  <xsl:decimal-format name="staff" digit="D" />

  <xsl:template name="Default" match="*" mode="itemstyle">
Note that I added it directly before the <xsl:template name="Default" …> definition.
Next, go back to our Grid template.  Replace the entire Grid template with the code below.  It is thoroughly commented, but don’t hesitate to email me or leave comments on my blog if you have questions.
 
  <xsl:template name="Grid" match="Row[@Style='Grid']" mode="itemstyle">

    <!-- 
      ContentMain.xsl passes CurPos and Last.
      We use these to conditionally emit the open and closing <table> tags.
    -->
    <xsl:param name="CurPos" />
    <xsl:param name="Last" />

    <!-- The following variables are unmodified from the standard ItemStyle.xsl -->
    <xsl:variable name="SafeImageUrl">
      <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
        <xsl:with-param name="UrlColumnName" select="'ImageUrl'"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="SafeLinkUrl">
      <xsl:call-template name="OuterTemplate.GetSafeLink">
        <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="DisplayTitle">
      <xsl:call-template name="OuterTemplate.GetTitle">
        <xsl:with-param name="Title" select="@Title"/>
        <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="LinkTarget">
      <xsl:if test="@OpenInNewWindow = 'True'" >_blank</xsl:if>
    </xsl:variable>

    <!--
      Here we define a variable, "tableStart".  This contains the HTML
      that we use to define the opening of the table as well as the column
      labels.  Note that if CurPos = 1, it includes the HTML in a CDATA tag.
      Otherwise, it will be empty.
      
      The value of tableStart is emited every time ItemStyle is called via 
      ContentQueryMain.xsl.
    -->
    <xsl:variable name="tableStart">
      <xsl:if test="$CurPos = 1">
        <![CDATA[ 
        <table border=1>
          <tr bgcolor="blue">
            <td><font color="white"><b>Project Name</b></font></td>
            <td align="right"><font color="white"><b>Complete Date</b></font></td>
            <td align="right"><font color="white"><b>Budget</b></font></td>
            <td align="right"><font color="white"><b>Actual Expense</b></font></td>
            <td><font color="white"><b>Overall Status</b></font></td>
          </tr>   
        ]]>
      </xsl:if>
    </xsl:variable>

    <!-- 
      Another variable, tableEnd simply defines the closing table tag.
      
      As with tableStart, it's always emited.  This is why its value is 
      assigned conditionally based upon whether we've been passed the last
      row by ContentQueryMain.xsl.
    -->
    <xsl:variable name="tableEnd">
      <xsl:if test="$CurPos = $Last">
        <![CDATA[ </table> ]]>
      </xsl:if>
    </xsl:variable>

    <!-- 
      Always emit the contents of tableStart.  If this is not the first
      row passed to us by ContentQueryMain.xsl, then we know its value
      will be blank.
      
      Disable output escaping because when tableStart it not blank, it
      includes actual HTML that we want to be rendered by the browser.  If
      we don't tell the XSL parser to disable output escaping, it will generate
      stuff like "&lt;table&gt;" instead of "<table>".
    -->
    <xsl:value-of select="$tableStart" disable-output-escaping="yes"/>


    <tr>
      <!--
      P:Project_x005F_x0020_Name
      P:Project_x005F_x0020_End_x005F_x0020_Date
      P:Project_x005F_x0020_Budget
      P:Project_x005F_x0020_Expenses
      P:Project_x005F_x0020_Status
      -->
      <td>
        <xsl:value-of select="@Project_x005F_x0020_Name"/>
      </td>

      <td align="right">
        <xsl:value-of select="@Project_x005F_x0020_End_x005F_x0020_Date"/>
      </td>

      <td align="right">
        <xsl:call-template name="formatcurrency">
          <xsl:with-param name="value" 
               select="@Project_x005F_x0020_Budget"></xsl:with-param>
        </xsl:call-template>
      </td>

      <td align="right">
        <xsl:call-template name="formatcurrency">
          <xsl:with-param name="value" select="@Project_x005F_x0020_Expenses">
        </xsl:with-param>
        </xsl:call-template>
      </td>

      <td>
        <xsl:value-of select="@Project_x005F_x0020_Status"/>
      </td>

      <!-- 
        All of the following is commented out to clarify things.
        However, bring it back and stuff it into a <td> to see its 
        effect.
      -->
      <!--
        <div id="linkitem" class="item">
          <xsl:if test="string-length($SafeImageUrl) != 0">
            <div class="image-area-left">
              <a href="{$SafeLinkUrl}" target="{$LinkTarget}">
                <img class="image-fixed-width" src="{$SafeImageUrl}" 
                     alt="{@ImageUrlAltText}"/>
              </a>
            </div>
          </xsl:if>
          <div class="link-item">
            <xsl:call-template 
                 name="OuterTemplate.CallPresenceStatusIconTemplate"/>
            <a href="{$SafeLinkUrl}" 
                   target="{$LinkTarget}" title="{@LinkToolTip}">
              <xsl:value-of select="$DisplayTitle"/>
            </a>
            <div class="description">
              <xsl:value-of select="@Description" />
            </div>

          </div>

        </div>

-->
    </tr>

    <!-- 
      Emit the closing table tag.  If we are not on the last row,
      this will be blank.
    -->
    <xsl:value-of select="$tableEnd" disable-output-escaping="yes"/>

  </xsl:template>

  <xsl:template name="formatcurrency">
    <xsl:param name="value" select="0" />
    <xsl:value-of select='format-number($value, "$DDD,DDD,DDD.DD", "staff")' />

  </xsl:template>
 

Results

Putting all of that together, I get the following result:
 

Concluding Thoughts

Naturally, now that you have grid-making support in place, you can use other templates to display dates and currency as per your requirements.  You can also put in conditional formatting, such as displaying projects who have exceeded their budget in red. 
You should leverage existing MOSS CSS styles so that the results conform to your site’s branding.
It feels like a lot of work to do this, but it really is not.  First time through, expect to spend the better part of a day getting it perfect.  I find there’s a "zen" to the process and once you’ve gone through it a few times (as well as working through graphing and search results) it all starts to jell.
Keep in mind that ItemStyle.xsl and ContentQueryMain.xsl need to be checked in for you see the results of your changes. 
Don’t get hung up on the specific facts of the business scenario.  This approach does not depend upon singleton lists or anything like that.  Modify the approach to generate a table for any results provided by the content query web part.
<end/>

1 comment:

  1. This is copied content original content at
    http://www.mstechblogs.com/paul/display-content-query-web-part-results-in-a-grid-table

    ReplyDelete