Sunday, April 24, 2011

Show only required layouts in available layout gallery - PublishingWeb.SetAvailablePageLayouts method

SharePoint have few out of the box layouts available with publishing site template. When we create a new publishing layout, that layout need to be added into the available layout gallery in order to make it available to user for creating the publishing page. This can be done through mannual steps as well as through code. SharePoint object model have PublishingWeb.SetAvailablePageLayouts() method which can be use to set available layouts. Here is how-

using(SPSite site=new SPSite(url))
{
PublishingSite pubSite=new PublishingSite(site);
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(site.OpenWeb());
SPContentType associatedCType = pubSite.ContentTypes["My ContentType"];
if (associatedCType != null)
{
PageLayoutCollection allLayouts = pubSite.GetPageLayouts(associatedCType, true);
pubWeb.SetAvailablePageLayouts(allLayouts.ToArray(), true);
}
pubWeb.Update();
}

Thats it. The above piece of code will add all the layouts inheriting from content type associatedCType and remove all other layouts from the available layout gallery. Only added layouts will be available for creating pages

No comments:

Post a Comment