Wednesday, 6 June 2012

Extending the Content Query Web Part (ContentByQueryWebPart)

I was assigned a task to allow filtering of CQWP results without requiring the user to edit the webpart.
I figured out the following simple way to extend the CQWP by having the filtering done with a drop down list on the webpart itself.
At first I wanted to use the consumer/provider method but decided this was easier...
Here's the code:
namespace ExtendCQWP.FilterWP
{
    [ToolboxItemAttribute(false)]
    public class FilterWP: Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart
    {
        protected override void OnLoad(EventArgs e)
        { 
            if (this.Page.Request.QueryString["FilterField1"]!=null && this.Page.Request.QueryString["FilterValue1"]!=null)
            {
                this.FilterField1 = this.Page.Request.QueryString["FilterField1"].ToString(); 
                this.FilterValue1 = this.Page.Request.QueryString["FilterValue1"].ToString();
            }
        }
        protected override void CreateChildControls()
        {             
            DropDownList ddl = new DropDownList();
            ddl.Items.Add(new ListItem("All", "All"));            
            ddl.Items.Add(new ListItem("HR", "HR"));
            ddl.Items.Add(new ListItem("Finance", "Finance"));
            ddl.Items.Add(new ListItem("IT", "IT"));

            ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
            ddl.AutoPostBack = true;
            ddl.EnableViewState = true;

            if (this.Page.Request.QueryString["FilterValue1"] != null)
            { 
                foreach(ListItem item in ddl.Items)
                    if(item.Text.Equals(this.Page.Request.QueryString["FilterValue1"].ToString()))
                    {
                        item.Selected = true;
                        break;
                    }
            }

            this.Controls.Add(ddl);            
            base.CreateChildControls();
        }

        void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList tmpddl = (DropDownList)sender;
            if(tmpddl.SelectedValue.Equals("All"))
                SPUtility.Redirect("http://mysite/SitePages/cq.aspx", SPRedirectFlags.Trusted, HttpContext.Current);
            else
                SPUtility.Redirect("http://mysite/SitePages/cq.aspx?FilterField1=Division&FilterValue1=" + tmpddl.SelectedValue, SPRedirectFlags.Trusted, HttpContext.Current);
        }
    }
}

Here's how the list and web part looks like.

No comments:

Post a Comment