blog.scoreman.net

Changing page layout and content type of a publishing page

Yesterday i wrote to extension methods that helps changing page layout and content type of a publishing page. The first method finds the layout by name, sets the content type on the list item and changes the layout. The second method (EnsureContentTypeOnPagesList) ensures that the new content type will be added to the Pages library if not already present (Content types will be added to the Pages library first when you add a page using that content type).

public static void ChangePageLayout(this PublishingPage page, string layoutName)
{
    PageLayout[] pageLayouts = page.PublishingWeb.GetAvailablePageLayouts();
    PageLayout newLayout = pageLayouts.SingleOrDefault(p => p.Name == layoutName);
    if (newLayout != null)
    {
        page.PublishingWeb.EnsureContentTypeOnPagesList(newLayout.AssociatedContentType);
        page.ListItem[SPBuiltInFieldId.ContentTypeId] = newLayout.AssociatedContentType.Id;
        page.Layout = newLayout;
        page.ListItem.SystemUpdate();
    }
}
public static void EnsureContentTypeOnPagesList(this PublishingWeb publishingWeb, SPContentType contentType)
{
    SPContentType listContentType = publishingWeb.PagesList.ContentTypes.Cast<SPContentType>()
        .SingleOrDefault(ct => ct.Id.ToString().StartsWith(contentType.Id.ToString()));
    if (listContentType == null)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (var elevatedSite = new SPSite(publishingWeb.Web.Site.ID))
            {
                using (var elevatedWeb = elevatedSite.OpenWeb(publishingWeb.Web.ID))
                {
                    elevatedWeb.AllowUnsafeUpdates = true;
                    Guid listId = PublishingWeb.GetPagesListId(elevatedWeb);
                    elevatedWeb.Lists[listId].ContentTypes.Add(contentType);
                    elevatedWeb.AllowUnsafeUpdates = false;
                }
            }
        });
    }
}

Tags: ,

Leave a Reply