Copied to clipboard

Flag this post as spam?

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


  • Patrick Shaun McNicholas 24 posts 206 karma points
    May 26, 2021 @ 20:13
    Patrick Shaun McNicholas
    0

    Is there a method to: Change IContentService node's template based on a property

    I'm retrieving data from a third party system using APIs and then creating nodes in Umbraco within a custom class, and I would like to be able to use the content service or template service to set the template used for the node based on one of the properties sent to the Class.

    I'm successfully doing everything up to the point that the node is created and published. However I cannot find the process for setting the final node's template to be used for rendering, and I can't ask the client to set the templates by hand in the back-office. That would be too much to manage manually.

    Since these nodes have identical properties and I only want to change the way the node itself is rendered within the site I would prefer they have a shared Document type but use a different template based on the property. I'm certain there is a way to do this as I see people asking and answering similar questions in the past in versions 7 and prior. I just don't see the methods for this in Umbraco version 8+

    I'm using a custom class for this

        public static string CreateNode(Guid UIDParent, string nodeName, string nodeProperty)
        {
            string statusMessage = "Node Created";
            IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;
            var newNodeItem = contentService.Create(nodeName, UIDParent, "nodeDocument", -1);
                newNodeItem.SetValue("nodeProperty", nodeProperty);
            contentService.SaveAndPublish(newNodeItem);
            // set template here based on nodeProperty
            return statusMessage;
        {
    
  • Huw Reddick 1929 posts 6717 karma points MVP 2x c-trib
    May 27, 2021 @ 18:14
    Huw Reddick
    100

    try something like this

    ITemplate template = Services.FileService.GetTemplate("TextTemplate");
    if(template != null){
        newNodeItem.TemplateId = template.Id
    }
    
  • Patrick Shaun McNicholas 24 posts 206 karma points
    May 28, 2021 @ 15:12
    Patrick Shaun McNicholas
    0

    Thank you yes that worked... I was able to add this logic in a couple of places to ensure the correct template is set on creation and is set when modified or displayed after checking that it's correct. I couldn't find anything about how to set templates anywhere in the documentation. Might be a good thing to add to the reference docs.

Please Sign in or register to post replies

Write your reply to:

Draft