Pages

Tuesday, May 9, 2017

Create a publishing page using custom page layout programmatically


Recently, I have got requirement to create a publishing page programmatically using JavaScript in SharePoint Online. Below are the steps details and example code snippet,

function createPage(){
$.getScript(_spPageContextInfo.webServerRelativeUrl + "/_layouts/15/" + "SP.Publishing.js", function(){
SP.UI.ModalDialog.showWaitScreenWithNoClose("Creating Page", "Please wait");    
   clientContext = new SP.ClientContext.get_current();  
   oSite = clientContext.get_site();
   oWeb = oSite.get_rootWeb();  

            //Get the client context,web and list object of Master Page Gallery
   var oList = oWeb.get_lists().getByTitle('Master Page Gallery');  

   //Get the page layout by ID using which we will create a publishing page       
   pageLayoutitem = oList.getItemById(pagelayoutid); 

   clientContext.load(oWeb); 
   clientContext.load(pageLayoutitem);  
   clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
    });
}
function QuerySuccess() {  
    //Create Publishing Page using PublishingPageInformation object   
    var curContext = new SP.ClientContext.get_current(); 
    var cWeb = curContext.get_web();
    var newPublishingPage = SP.Publishing.PublishingWeb.getPublishingWeb(curContext, cWeb);  
    var pageInfo = new SP.Publishing.PublishingPageInformation();  
    pageInfo.set_name("sample.aspx");  
   
    pageInfo.set_pageLayoutListItem(pageLayoutitem);  
    newPage = newPublishingPage.addPublishingPage(pageInfo);  
    //Load the new page object to the client context   
    clientContext.load(newPage);  
    clientContext.executeQueryAsync(SecondQuerySuccess, SecondQueryFailure);  
}  

function QueryFailure(sender, args) {  
    console.log('Request failed' + args.get_message());
    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
    alert("Something went wrong, refresh and try again");  
}  

function SecondQuerySuccess(sender, args) {  
    console.log("Publishing page created successfully.");
    var pageItem = newPage.get_listItem();
        pageItem.get_file().checkIn("", 0);
        clientContext.load(pageItem);
        clientContext.executeQueryAsync(function () {
            //Open publishing page which is created     
    window.open(pageItem.get_item('FileRef'), '_blank');
   }, SecondQueryFailure);
        }, Function.createDelegate(this, SecondQueryFailure));       
}  
function SecondQueryFailure(sender, args) {  
    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
     alert("Something went wrong, refresh and try again");
}

Make sure SP.Publishing.js file loaded before execute above script.

No comments:

Post a Comment