Saturday, October 8, 2011

SharePoint 2010 - Set the default Page Layout programmatically.

Goal - To set "CustomDefaultPageLayout.aspx" as the default page layout, so the next time when some one creates a "New Page" our custom page layout is applied to the page and not system's.


Follow the below given steps to achieve the goal.

  • First of all make sure that the site we have to apply the page layout is a "Publishing Site."
  • Create a Visual Studio Empty Project.
  • Add a Feature Receiver
  • Add new reference of "Microsoft.SharePoint.Publishing".
  • Apply this on the top of the class.
    using Microsoft.SharePoint.Publishing;
    using System.Linq;
  • On feature activation use the below given code.
    private void SetDefaultPageLayout(SPWeb _web)
    {
        PublishingWeb _pubWeb = PublishingWeb.GetPublishingWeb(_web);
        if (_pubWeb != null)
        {
            PageLayout _pageLayout = (from _pl in _pubWeb.GetAvailablePageLayouts()
                                        where _pl.Name == "CustomDefaultPageLayout.aspx"
                                        select _pl).FirstOrDefault();
            _pubWeb.SetDefaultPageLayout(_pageLayout, true);
            _pubWeb.Update();
        }
    }
  • Call the function "SetDefaultPageLayout" from the Feature Activation event.

4 comments:

  1. Thanks for the transferring knowledge , but how can I apply custom page layout to default page of sharepoint publishing site ?

    ReplyDelete
  2. @Dipti - The above given example finds out the CustomDefaultPageLayout.aspx from the list of page layouts. If it exists we are setting the CustomDefaultPageLayout.aspx as a Default page layout, so when the user tries to create a new page he/she can see our CustomDefaultPageLayout.aspx settings.

    ReplyDelete
  3. Hi..

    Thanks for the post could u explain step by step..
    Thanks

    ReplyDelete
    Replies
    1. @Anonymous, I think the post itself is step by step.

      Delete