Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Proxicode 128 posts 324 karma points
    Dec 30, 2018 @ 20:28
    Proxicode
    0

    Assign Template to DocType Programmatically (in razor code)

    Not a question today, just wanted to share this with the community in case anyone else needs it. I inadvertently created 67 "partners" in my CMS without a default template and was faced with manually editing each one to set the template, so I set off to figure how to do this via the API.

    I found Andrew Knox very helpful comment here but it turns out that the IUmbracoCmsService and IUmbracoFileService he uses are either gone, undocumented or not available via razor. So after a good read of the API docs I found the FileService and ContentService

    The FileService is needed because when you assign a Template to a DocumentType it not assigned by name or by Id, but assigned as a file.

    My code is posted below, but a few things worth noting. The FileService has several different GetTemplate() methods to retrieve the template. I chose to use the string name, but you could optionally use Id or even GUID. Same is true for the contentService... there are MANY ways to retrieve contentNodes, my example is using GetChildren(parentId) but have a look at the ContentService docs to find what's best for your needs.

    Important! Be sure to remove this code after the first successful run or it will keep reassigning the template on every load ;-)

    // get a reference to the services
    var fileService = ApplicationContext.Current.Services.FileService;
    var contentService = ApplicationContext.Current.Services.ContentService;
    
    // find the template
    var template = fileService.GetTemplate("PartnersPage");
    
    // get all nodes that need to be updated
    IList<IContent> allPartners = contentService.GetChildren(1486).ToList();
    
    // assign tempalte file and Save
    foreach(var p in allPartners)
    {
        p.Template = template;
        contentService.SaveAndPublish(p);
    }
    

    Happy coding!

    -Roger

  • Proxicode 128 posts 324 karma points
    Dec 30, 2018 @ 22:24
    Proxicode
    0

    Incidently - I also updated a property on each node with nearly identical code

       // get a reference to the service
        var contentService = ApplicationContext.Current.Services.ContentService;
    
        // get all nodes that need to be updated
        IList<IContent> allPartners = contentService.GetChildren(1486).ToList();
    
        foreach(var p in allPartners)
        {
            p.SetValue("umbracoInternalRedirectId", 1486);
            contentService.SaveAndPublish(p);
        }
    
  • keilo 568 posts 1023 karma points
    Jan 08, 2019 @ 14:15
    keilo
    100

    thanks for sharing this

Please Sign in or register to post replies

Write your reply to:

Draft