Hello all.
In our project, we had a situation in which we must set the available page templates to the given web. Since we already deployed the solution to a production environment and we will not create the site again, for an existing site we need to do it manually and for new sites that will be created we use the feature stapler.
So here we will discuss how to set available page layouts programmatically. (We did this using a custom feature receiver and associated our custom feature in the feature stapler.) Setting the available page layout programmatically is a bit more difficult than setting it in the site definition in Onet.xml file.
To set the available page layouts there is the method “SetAvailablePageLayouts()” of publishing the web. This method takes one parameter, an array of “PageLayout” class objects.
So to set the available page layouts programmatically:
- Get the PublishingWeb of the web where we need to set / update the available page layouts since SetAvailablePageLayouts() is a method of PublishingWeb as in the following:
- PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(currentWeb);
- Get all the available page layouts for the web (just in case we want all the existing set page layouts) and create an instance of ArrayList class objects to add the layouts.
- PageLayout[] layouts = pWeb.GetAvailablePageLayouts();
- ArrayList pageLayoutList = new ArrayList();
- pageLayoutList.AddRange(layouts)
- Now, since we require an instance of the “PageLayout” class, I get all the available page layouts for the site collection, loop through them and compare them with my new page layout that I need to add to the web and to be added to the 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))
- {
- pageLayoutList.Add(pl);
- }
- }
- Type cast the arraylist into an array of PageLayout class objects and call the SetAvailablePageLayouts() of PublishingWeb.
- PageLayout[] newPls = (PageLayout[])pageLayoutList.ToArray(typeof(PageLayout));
-
- pWeb.SetAvailablePageLayouts(newPls, false);
- pWeb.Update();
I hope this will be useful to you. In case if any queries, feel free to discuss questions.
Thanks.