Monday, 12 December 2011

Setting / Updating available page layouts programatically

Hello All,

In our project, we had situation like we need set available page templates to the given web. Since we already deployed the solution on production environment and we are not going to create site again, for existing site we need to do manually and for new sites which will be created we used feature stapler.

So here we will discuss how to set available page layouts programmatically (We did this using custom feature receiver and associated our custom feature in feature stapler). 

Setting the available page layout programmatically is little difficult than setting in site definition in Onet.xml file.

To set the available page layouts there is a method “SetAvailablePageLayouts()” of publishing web. This method takes one parameter which is array of “PageLayout” class.

So to set the available page layouts programmatically:
  1. Get the PublishingWeb of the web where we need to set / update the available page layouts since SetAvailablePageLayouts() is method of PublishingWeb as
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(currentWeb);

  1. Get all the available page layouts for the web (Just in case if we want all the existing set page layouts) and created instance of ArrayList class to add the layouts.
PageLayout[] layouts = pWeb.GetAvailablePageLayouts();
     ArrayList pageLayoutList = new ArrayList();

  1. Now, since the we will required instance of “PageLayout” class, I get the all available page layouts for the site collection, loop through them and compare with my new page layout which I need to add to the web and added in array list as follows:
SPSite site = pWeb.Web.Site;
       if (site != null)
           PublishingSite publishingSite = new PublishingSite(site);
       if (publishingSite != null)
PageLayoutCollection pageLayoutsCollection = publishingSite.GetPageLayouts(true);

foreach (PageLayout pl in pageLayoutsCollection)
if (pl.Name.Equals(mynewpagelayoutnamewhcihneedtobemadeavailablefortheweb, StringComparison.InvariantCultureIgnoreCase))

  1. Type cast the arraylist into array of PageLayout class and call the SetAvailablePageLayouts() of PublishingWeb
PageLayout[] newPls = (PageLayout[])pageLayoutList.ToArray(typeof(PageLayout));

pWeb.SetAvailablePageLayouts(newPls, false);

I hope this will be useful to you. In case if any queries, questions feel free to discuss.

Thanks J.


Deepesh Sharma said...

This was really helpful. Thanks a lot.


Prasham Sabadra said...

Thanks Deepesh !

James said...

Awesome, thanks Prasham, helped me out a lot!

PS don't forget to call pWeb.Update() at the end to make sure the page layout change gets saved :)

Ravindra Nikam said...


I have custom page layout so how can we deploy on page layout gallery pro grammatically. If you know can you share it.