Copied to clipboard

Flag this post as spam?

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


  • suzyb 474 posts 932 karma points
    Oct 26, 2017 @ 23:06
    suzyb
    2

    Creating Nested Content Programatically

    I'm trying to programmatically set a nested content property but am having a bit of trouble getting it working fully. The following code creates the nested content item on the document however none of the properties (title & bodyText) are set.

    Content doc = (Content)sender;
    
    IContentService contentService = ApplicationContext.Current.Services.ContentService;
    
    List<IContent> items = new List<IContent>();
    
    IContent newDesc = contentService.CreateContent("Description", doc.Id, "nestTextContent");
    newDesc.SetValue("title", "test");
    newDesc.SetValue("bodyText", cleanedDescription);
    
    items.Add(newDesc);
    
    doc.SetValue("pageContent", JsonConvert.SerializeObject(items));
    contentService.Save(doc);
    

    Looking at some older threads the answers say the value should be a "JSON serialized Dictionary<string, object> string" but I don't see what the contents of the dictionary should be.

    Am I barking up the wrong tree trying to serialise a list of IContents? If not how do I get the actual nested content item's properties set.

    These are the threads I've been referencing. https://our.umbraco.org/projects/backoffice-extensions/nested-content/nested-content-feedback/72977-can-i-write-collection-of-ipublishedcontent-back-to-model-property https://our.umbraco.org/projects/backoffice-extensions/nested-content/nested-content-feedback/76444-create-nestedcontent-items-in-surfacecontroller

  • David Parr 48 posts 206 karma points
    Oct 27, 2017 @ 07:34
    David Parr
    108

    Hi Suzy

    You can get this working, I hope the following code helps you out. You were close before, it is not a list of IContent you need though but a list of dictionary.

    Content doc = (Content)sender;
    
    IContentService contentService = ApplicationContext.Current.Services.ContentService;
    
    // Same as in your above example, title and body text values
    var items = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(doc.GetValue<string>("nestTextContent"));
    
    items.Add(new Dictionary<string, object>() {
      {
        "title",
        "test"
      },
      {
        "bodyText",
        cleanedDescription
      }
    });
    
    doc.SetValue("pageContent", JsonConvert.SerializeObject(items));
    contentService.Save(doc);
    

    This is just a basic working example for 7.3+ that I have tested.

  • Umbraco_Learner 2 posts 72 karma points
    Jul 12, 2019 @ 08:15
    Umbraco_Learner
    0

    hello

    I am trying to Set value and save a Nested Content programatically. Pretty much following the above steps.

    I get an error while Save - Object Reference not Set to an instance of an object.

    ApplicationContext.Current.Services.ContentService.Save(myContent);

    I am not sure why I get this.

  • suzyb 474 posts 932 karma points
    Oct 27, 2017 @ 09:19
    suzyb
    0

    Thanks so much David. I've got it working now.

    Obvious when it's pointed out but I just couldn't figure it out last night.

  • Cedric 15 posts 86 karma points
    Jun 05, 2018 @ 18:48
    Cedric
    0

    Hello I have a similar problem can you help me? I can not initialize items it tells me that the value is null and item.add logically I must put an object but I do not know which object thank you

    var mycontentService =  Services.ContentService;
            var itemregulatory = mycontentService.CreateContent(name, parentId, "regulatory",0);
            itemregulatory.SetValue("countryname", countryname);
            itemregulatory.SetValue("referTo", referTo);
            itemregulatory.SetValue("authorityName",authorityName);
            itemregulatory.SetValue("webSiteLink", webSiteLink);
            itemregulatory.SetValue("localTesting",localTesting);
            itemregulatory.SetValue("testsRequired", testsRequired);
            itemregulatory.SetValue("countryOwner",countryOwner);
            itemregulatory.SetValue("systemAproval", systemAproval);
            //itemregulatory.SetValue("antennaDependant",antennaDependant);
            itemregulatory.SetValue("sampleNeeded", sampleNeeded);
            itemregulatory.SetValue("countryInfoMarkingRequirements",countryInfoMarkingRequirements);
            itemregulatory.SetValue("agent", agent);
            itemregulatory.SetValue("certificationCost",certificationCost);
            //itemregulatory.SetValue("technology", "");
    
    
            //var items = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(itemregulatory.GetValue<string>("technology"));
            var items = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(itemregulatory.GetValue<string>("technology"));
    
            items.Add(new Dictionary<string, object>() {
              {
                "technologyUse1",
                "3G"
              },
              {
                "bandNumber",
                "002"
              }
            });
    
            itemregulatory.SetValue("technology", JsonConvert.SerializeObject(items));
            mycontentService.SaveAndPublishWithStatus(itemregulatory);
    
  • Sérgio 30 posts 171 karma points
    Aug 03, 2018 @ 16:44
    Sérgio
    0

    This line is probably return a null value as you don't have anything in the property yet:

    var items = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(itemregulatory.GetValue<string>("technology"));
    

    You need to check if items is null and, if so, initialize it accordingly:

    if (items == null) {
        items = new List<Dictionary<string, object>>();
    }
    
  • Stephen 767 posts 2273 karma points c-trib
    Apr 26, 2019 @ 07:27
    Stephen
    0

    Note: the serialized format of Nested Content property values has quite probably changed in v8. Here is what I have in database for a Nested Content property with only 1 TextBox:

    [
      {"key":"04a6dba8-813c-4144-8aca-86a3f24ebf08","name":"Item 1","ncContentTypeAlias":"nested","text":"woot"},
      {"key":"d8e214d8-c5a5-4b45-9b51-4050dd47f5fa","name":"Item 2","ncContentTypeAlias":"nested","text":"zoot"}
    ]
    

    So this will probably need to be amended for v8

  • ChristophC 21 posts 60 karma points
    Oct 14, 2019 @ 14:34
    ChristophC
    5

    My solution in Umbraco 8.1.4:

    var liste = new List<Dictionary<string, string>>();
    
    Guid guid1 = Guid.NewGuid();
    
    liste.Add(new Dictionary<string, string>(){
        {"key","@guid1"},
        {"name","Some name"},
        {"ncContentTypeAlias","Your NestedContent Element-Type Alias"},
        {"Property in NestedContent","Some Text"},
    });
    
    node.SetValue("Your NestedContent Property Alias", JsonConvert.SerializeObject(liste));
    
  • Rihab 104 posts 388 karma points
    Dec 18, 2019 @ 12:16
    Rihab
    0

    you saved my life maaaan :)

  • Ben 6 posts 96 karma points
    Feb 15, 2020 @ 13:35
    Ben
    0

    Hi,

    I'm trying this is Umbraco version 8.5.1 but having zero luck.

    It's just not adding the content to the nested property. Do you know if anything has changed with nested content since you posted this?

  • Perry Cope 31 posts 195 karma points
    Feb 28, 2020 @ 11:42
    Perry Cope
    0

    I am using 8.5.3 and something similar to this works for me.

    I have found a "key" is required to have a new guid.

    And "ncContentTypeAlias" is required (This is the Alias of the Document type you are using for the nested content!)

    Name is not required.

                var nestedContent = new Dictionary<string, object>();
                nestedContent.Add("ncContentTypeAlias", "DocTypeAlias");
                nestedContent.Add("key", Guid.NewGuid());
                nestedContent.Add("PropertyAlias", "PROPERTYVALUE");
                _contentService.SetValue("propertyName", JsonConvert.SerializeObject(nestedContent));
    
  • Owain Williams 480 posts 1412 karma points MVP 6x c-trib
    Mar 10, 2020 @ 18:34
    Owain Williams
    0

    I'm just trying to do something similiar to this. Ideally when I create a new page, which has a nested content field on it, I want to add an element to that nested content.

    All these code snips are usefully but where do you implement these? Do you need to use DI to hook in to the save function or something else?

    Sorry if I'm missing something that's been explained above. If anyone has more info that would be great. Thanks!

    I'm using Umbraco 8.

  • Perry Cope 31 posts 195 karma points
    Mar 11, 2020 @ 09:13
    Perry Cope
    0

    If your wanting to do it during Save i believe in v8 Composer and components are the way to do it.

    This https://our.umbraco.com/documentation/implementation/composing/

    And this article in particular helped me https://www.zpqrtbnk.net/posts/composing-umbraco-v8-components/

  • Anders Brohus 194 posts 475 karma points
    Jul 07, 2020 @ 08:05
    Anders Brohus
    0

    It works great :)

  • BJ Patel 80 posts 206 karma points
    Aug 03, 2021 @ 09:18
    BJ Patel
    0

    I have almost the same code,

    But the issue is every time it overwrites the Old Value with the new one. As I need to append/add new Items to nested content!

    so How can it be done?

    Thanks

  • Stefan Besteman 6 posts 26 karma points
    Oct 30, 2020 @ 14:10
    Stefan Besteman
    0

    I have the nested content variant working. Does anyone have a example of how to do this with a blocklist editor

    I see this in the database {"layout":{"Umbraco.BlockList":[{"contentUdi":"umb://element/0aa543991746424fb5d709793a14b8e3"},{"contentUdi":"umb://element/34c4794b69404535bce54bb6e1570b79"}]},"contentData":[{"contentTypeKey":"7af0ad93-b236-4b5c-9664-3c408dee7f85","udi":"umb://element/0aa543991746424fb5d709793a14b8e3","description":"test","value":"test2"},{"contentTypeKey":"7af0ad93-b236-4b5c-9664-3c408dee7f85","udi":"umb://element/34c4794b69404535bce54bb6e1570b79","description":"test3","value":"test4"}],"settingsData":[]}

  • Ben McKean 272 posts 549 karma points
    Nov 13, 2020 @ 14:41
    Ben McKean
    0

    Did you find a solution to this Stefan?

  • Marc Goodson 2141 posts 14344 karma points MVP 8x c-trib
    Nov 14, 2020 @ 20:19
  • Kiran 17 posts 109 karma points
    Feb 02, 2021 @ 11:33
    Kiran
    0

    Hi all I have a similar problem can you please help me? I worked above code but it won't work currently i'm using umbraco 8.8. Can you please give me working sample code.

    Thanks in advance

  • Stefan Besteman 6 posts 26 karma points
    Feb 02, 2021 @ 13:00
    Stefan Besteman
    0

    Hi Kiran,

    Here a working example in umbraco 8.7. Nested content has 3 fields description, value1 and value2

    Nested content is available is a doctype named slab

    public class ContentDataThreeColumnItem : IContentDataItem { #region Properties

        [JsonProperty("contentTypeKey")]
        public Guid ContentTypeKey { get; set; }
    
        [JsonProperty("description")]
        public string Description { get; set; }
    
        [JsonProperty("udi")]
        public GuidUdi Udi { get; set; }
    
        [JsonProperty("value1")]
        public string Value1 { get; set; }
    
        [JsonProperty("value2")]
        public string Value2 { get; set; }
    
        #endregion
    }
    

    public class BlockListItem { #region Properties

        public string Description { get; set; }
        public string Value1 { get; set; }
        public string Value2 { get; set; }
    
        #endregion
    }
    

    private readonly IContentService _contentService;

    public ExcelService(IContentService contentService, IContentTypeService contentTypeService, ISqlContext sqlContext, IMediaService mediaService, IMediaTypeService mediaTypeService) { _contentService = contentService; _contentTypeService = contentTypeService; _sqlContext = sqlContext; _mediaService = mediaService; _mediaTypeService = mediaTypeService; }

    var slabNode = _contentService.GetPagedChildren(slabCollectionNode.Id, 0, 100, out totalRecords, filter).FirstOrDefault();

    var slabNodeBlockListItemList = new List

    slabNodeBlockListItemList.Add(new BlockListItem { Description = cpsExcelModel.Value1, Value1 = cpsExcelModel.Value2, Value2 = cpsExcelModel.Value3 });

    var blockListItemContentType = ThreeColumnRow.GetModelContentType().Alias

    foreach (var blockListItem in slabNodeBlockListItemList) { var contentUdi = new Content(null, slabNode, blockListItemContentType).GetUdi(); blockList.Layout.UmbracoBlockList.Add(new ContentUdiItem { ContentUdi = contentUdi });

                            blockList.ContentDataList.Add(new ContentDataThreeColumnItem
                            {
                                ContentTypeKey = blockListItemContentType.Key,
                                Udi = contentUdi,
                                Description = blockListItem.Description,
                                Value1 = blockListItem.Value1,
                                Value2 = blockListItem.Value2
                            });
                    }
    

    var serializedBlockList = JsonConvert.SerializeObject(blockList); slabNode.SetValue(Slab.GetModelPropertyType(a => a.ReferenceTable).Alias, serializedBlockList, currentVariantLanguage);

    _contentService.SaveAndPublish(slabNode, currentVariantLanguage, 0, false);

    Hope this gives you a direction

  • Jane King 4 posts 84 karma points
    Feb 25, 2021 @ 16:16
    Jane King
    0

    Useful. Informative. Thanks to all of you

Please Sign in or register to post replies

Write your reply to:

Draft