Creating a page through code in Umbraco 7

Often we are required to create pages through code in a CMS. In this post we will look at how this can be done in Umbraco 7.

Creating a page through code is pretty straightforward and can be done with a few lines of code. Take a look at the example below.

public bool PublishPage()
{
    //Get the ContentService object
    var contentService = ApplicationContext.Services.ContentService;

    //Get the IContnet object which will be the parent of the page that we are publishing
    var parentPage = contentService.GetRootContent().First();

    //create the child page using the ContentService
    var childPage = contentService.CreateContent("New Text Page", parentPage, "textPage");

    //Set the property values of the child page
    childPage.SetValue("title", "This is the Title");
    childPage.SetValue("content", "This is the content");

    //Save and publish the page 
    var publishAttempt = contentService.SaveAndPublishWithStatus(childPage);

    //Return the success value
    return publishAttempt.Success;
}

Let’s review the code :

  • Line no 4 : Get the instance of the ContentService object which will be used to retrieve and create content. In the above example, I have used the ApplicationContext.Services property to do so.
  • Line no 8 : Retrieve the page that will be the parent of the new page. In the above example, I have retrieved the Home page.
  • Line no 11 : Create the child page using the ContentService.CreateContent method, providing the name, parent page IContent object and the document type alias.
  • Lines 14-15 : Set the property values of the newly created page using their property alias.
  • Line no 18 : Save and publish the page.

By default the CreateContent method uses 0 as the User Id when creating the content. The SaveAndPublishWithStatus method returns an Attempt<PublishStatus> object which has a boolean property named Success which indicates whether the page has been published or not.

In the image below, you can see the newly created page has been added to the tree structure along with the updated properties.

One thing to note here is that when creating pages from code, pages can be added to parent nodes which do not have permission to add the specific document type under it. In the above example we were able to create the page of document type textPage under the Home Page even though we have not specified any permission for it on the Home Page.

Conclusion

Creating pages through code is quiet a common task when working with any CMS. In Umbraco this can be done with relative ease using the service api’s provided.

Adam Brown
Please follow and like us:

Leave a Comment