Feb
11
2008

How to use event handler to add web part to web part page

When you are designing a new page layout and want to have default web parts to be included when user creates a new page off this page layout. You can accomplish this by several ways.

1.       Easiest way probably is to put web parts inside the page layout. – But you cannot change the web part settings without modifying page layout.

2.       Use <AllUsersWebPart/> within element manifest file where you provisioning the page layout. – It is good way to do it only if it can work properly. I am having issues with this method. Having Default Web Parts in new Pages Based Off Page Layouts in MOSS 2007 Publishing Sites have great post about how to do this.

Or you can use event handler to add default web parts to the page when page gets created and added to page library.

First step, create a page layout with empty WebPartZone.

 


<!-- page layout .aspx -->


<WebPartPages:WebPartZone id="DefaultWebPartZone" runat="server" title="Feature Zone">


</WebPartPages:WebPartZone>

Second step, create a list event handler and register it with “Page document library”


<!-- Feature element manifest .xml-->


<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Receivers ListTemplateId="850">

    <Receiver>

      <Name>AddedEventHandler</Name>

      <Type>ItemAdded</Type>

      <SequenceNumber>10000</SequenceNumber>

      <Assembly>YourAssemblyNameHere, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789ABCDEF</Assembly>

      <Class>YourNamespaceHere.YourClassNameHere</Class>

      <Data></Data>

      <Filter></Filter>

    </Receiver>

  </Receivers>

</Elements>
 

Thrid step, write your code to insert the web part to page.


 /*EventHandler.cs*/
public class WebPartPageBuilder : SPItemEventReceiver
{
        public override void ItemAdded(SPItemEventProperties properties)
        {    
            //we check if event fired from page library and page was created base on correct page layout (with web part zone).
            if (properties.ListTitle.Equals("Pages") && properties.ListItem.ContentType.Name.Equals("Page Layout Name")) 
            {
                SPFile thisFile = properties.ListItem.File;
                SPLimitedWebPartManager webPartManager = thisFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
                ContentByQueryWebPart defaultCQWPWebPart = new ContentByQueryWebPart();
                /**web part settings ommited here**/ 
                webPartManager.AddWebPart(defaultCQWPWebPart, "DefaultWebPartZone", 1);
            }
            base.ItemAdded(properties);
        }
}

 Now, you have created a event handler that inserts web part to the page.

blog comments powered by Disqus