Monday, February 22, 2010

Making the content query web part deployable

My biggest issue with the CQWP? its not deployable when connected to a specific list in a specific site.
If you configure a CQWP web part to connect to a list in a site, the web part saves the ID (GUID) of the list - and if you want to deploy the web part as part of a feature or onet.xml so that the web part gets added every time a user creates a site, it will fail - because the ID of the list changes every time you create a new site.

My solution? override the web part and implement the following 2 functions:

public class MyBetterQueryWebPart: ContentByQueryWebPart
{
public void SetListGuid()
        {
            if (!string.IsNullOrEmpty(this.WebUrl) && 
!string.IsNullOrEmpty(this.ListName))
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb(this.WebUrl, true))
                {
                    SPList list = web.Lists[this.ListName];
                    this.ListGuid = list.ID.ToString();
 
                }
            }
 
        }
        protected override void OnLoad(EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.WebUrl) && 
!string.IsNullOrEmpty(this.ListName) && 
string.IsNullOrEmpty(this.ListGuid))
            {
                SetListGuid();
            }
            base.OnLoad(e);
        }
}

This code checks if the web part is in list mode (has a list name and a web url) and is "corrupt" - doesnt have a list ID. if it finds that is the case, it dynamically loads the list ID based on the site url and the list name.

No comments: