2

How can I change the page layout of a page.

i have tried this code but the page layout doesn't change.

      using (SPWeb web = newSiteCollection.OpenWeb())
        {
            string masterUrl = SPUrlUtility.CombineUrl(newSiteCollection.ServerRelativeUrl, "_catalogs/masterpage/MyCustomMstr.master");
            try
            {


                web.MasterUrl = masterUrl;
                web.CustomMasterUrl = masterUrl; 


                PageLayout layout = (from p1 in _web.GetAvailablePageLayouts()
                                      where p1.Name == "MyCustomPLayout.aspx"
                                      select p1).FirstOrDefault();
                SPFile file = web.GetFile("Sidor/default.aspx");
                var pu = PublishingPage.GetPublishingPage( file.GetListItem());
                pu.Layout = layout;

                file.Properties["vti_title"] = String.Empty;
                file.Properties["PublishingPageContent"] = String.Empty;

                web.AllowUnsafeUpdates = true;
                web.Update();
            }
1

4 Answers 4

1
void SetDefaultPageLayout(string layoutName, SPWeb web)
{
    var pubWeb = PublishingWeb.GetPublishingWeb(web);
    if (pubWeb != null)
    {
        var pageLayout = pubWeb.GetAvailablePageLayouts()
            .Single(pl => pl.Name == "MyCustomPLayout.aspx");
        pubWeb.SetDefaultPageLayout(pageLayout, true);
        pubWeb.Update();
    }
}
1

Try this:

using (SPSite site = new SPSite("http://aissp2013"))
{
    SPWeb rootWeb = site.RootWeb;
    PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(rootWeb);
    PageLayout[] layouts = pubWeb.GetAvailablePageLayouts();
    PageLayout layout = null;
    var matches = from l in layouts
                  where l.Name.Equals("ArticleLeft.aspx", StringComparison.OrdinalIgnoreCase)
                  select l;
    if (matches.Count<PageLayout>() > 0)
    {
        layout = matches.First<PageLayout>();
    }                     
    if (null != layout)
    {
        SPFile file = rootWeb.GetFile("/Pages/MyClients.aspx");
        if (PublishingPage.IsPublishingPage(file.Item))
        {
            PublishingPage page = PublishingPage.GetPublishingPage(file.Item);
            if (page.Layout != layout)
            {
                file.CheckOut();
                page.Layout = layout;
                page.Update();
                file.CheckIn("Changed layout");
                file.Publish("Initial Publish");                           
            }
        }
    }
}

Source: http://www.sharepointnadeem.com/2014/11/sharepoint-change-page-layout-through.html

0

Please add the lines to check out and then check in the file. Also update the list item for which you are changing the page layout.

0

Page layouts of a page can also be changed via PowerShell script. Here is a CSOM PowerShell function which will change the page layout.

Since its CSOM you need not run this on server, i.e. this can be executed from remote machine provide you have installed SharePoint Client SDK.

Try{
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll'
    Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Taxonomy.dll'
}

catch {
    Throw "Unable to load SharePoint Client runtime"
}

function ChangePageLayout()
{
    param(
        [Parameter(Mandatory=$true)][string]$siteurl,
        [Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials,
        [Parameter(Mandatory=$false)][string]$PageName,
        [Parameter(Mandatory=$false)][string]$PageLayoutName,
        [Parameter(Mandatory=$false)][string]$PageLayoutDisplayName,
        [Parameter(Mandatory=$false)][string]$Title,
        [Parameter(Mandatory=$false)][bool]$isCustomPageLayout
    )
    try
    {

        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteurl)
        $ctx.Credentials = $credentials

        if($isCustomPageLayout -eq $false)
        {
            $PageLayoutName = "/_catalogs/masterpage/" + $PageLayoutName + "," + $PageLayoutDisplayName
        }
        else
        {
            #Here I have assumed that if its custom page layout, then it's placed inside some folder which is child to masterpage
            #If that's not the case with you then you can use below line of code
            #$PageLayoutName = "/_catalogs/masterpage/" + $PageLayoutName + ", " + $PageLayoutDisplayName
            #
            $PageLayoutName = "/_catalogs/masterpage/Custom Page Layouts/" + $PageLayoutName + ", " + $PageLayoutDisplayName
        }

        $Pages = $ctx.Web.Lists.GetByTitle('Pages')
        $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
        $camlQuery.ViewXml = '<View><Query><Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">'+ $PageName +'</Value></Eq></Where></Query></View>'
        $Page = $Pages.GetItems($camlQuery)
        $ctx.Load($Page)
        $ctx.ExecuteQuery()

        $file = $Page.File

        $ctx.Load($file)
        $ctx.ExecuteQuery()

        if ($file.CheckOutType  -ne [Microsoft.SharePoint.Client.CheckOutType]::None) {
            $file.UndoCheckOut()
            $ctx.Load($file)
            $ctx.ExecuteQuery() 
        }

        $file.CheckOut()
        $ctx.Load($file)
        $ctx.ExecuteQuery()

        $Page.Set_Item("PublishingPageLayout", $PageLayoutName)
        $Page.Set_Item("Title", $Title)
        $Page.Update()
        $Page.File.CheckIn("", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
        $Page.File.Publish("")

        #check for approval
        $ctx.Load($Pages)
        $ctx.ExecuteQuery()

        if ($Pages.EnableModeration -eq $true) {
            $Page.File.Approve("")
        }

        $ctx.Load($Page)
        $ctx.ExecuteQuery()
        Write-Host "Update Page Layout Complete"
        Write-Host ""

    }
    catch
    {
        Write-Host ("Error while changing page layout. Error -->> " + $_.Exception.Message) -ForegroundColor Red
    }
}

Usage:

$credentials = Get-Credential
ChangePageLayout "http:yoursite.com" $credentials "default.aspx" "YourCustomLayout.aspx" "Your Custom Page Layout" "Some Title" $true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.