Programmatically Set Available Page Layout in SharePoint

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:

  1. 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:
    1. PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(currentWeb);  
  2. 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.
    1. PageLayout[] layouts = pWeb.GetAvailablePageLayouts();  
    2. ArrayList pageLayoutList = new ArrayList();  
    3. pageLayoutList.AddRange(layouts)  
  3. 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:
    1. SPSite site = pWeb.Web.Site;  
    2. if (site != null)  
    3. {  
    4.     PublishingSite publishingSite = new PublishingSite(site);  
    5. }  
    6. if (publishingSite != null)  
    7. {  
    8.    PageLayoutCollection pageLayoutsCollection = publishingSite.GetPageLayouts(true);  
    9. }  
    10.   
    11. foreach (PageLayout pl in pageLayoutsCollection)  
    12. {  
    13.     if (pl.Name.Equals(mynewpagelayoutnamewhcihneedtobemadeavailablefortheweb, 
          StringComparison.InvariantCultureIgnoreCase))  
    14.     {  
    15.         pageLayoutList.Add(pl);  
    16.     }  
    17. }  
  4. Type cast the arraylist into an array of PageLayout class objects and call the SetAvailablePageLayouts() of PublishingWeb.
    1. PageLayout[] newPls = (PageLayout[])pageLayoutList.ToArray(typeof(PageLayout));  
    2.   
    3. pWeb.SetAvailablePageLayouts(newPls, false);  
    4. pWeb.Update();  
I hope this will be useful to you. In case if any queries, feel free to discuss questions.
 
Thanks.