Developer forum

Forum » Development » Adding items to an itemRelationList through API

Adding items to an itemRelationList through API

Steen Nørgaard Perdersen
Steen Nørgaard Perdersen
Reply

Hi,

I am greating a piece of code to replace some itemlists of one type with a new type. The itemlists gets created allright, but i struggle to fill anything in them.

Heres my code:

                Paragraph paraNew = new Paragraph(paraOld.PageID);
                paraNew.Header = paraOld.Header + " copy: " + DateTime.Now.ToString("HH:mm");
                paraNew.Sort = paraOld.Sort;
                paraNew.ItemType = itemListTypeNew;
                paraService.SaveParagraph(paraNew);
                paraNew.Item.Save();
          
//"Copy" of paragraph ok - New is created next to old one, and through backend items can be added
 
                Item itemListitemNew = Dynamicweb.Content.Items.ItemManager.Storage.GetById(itemListTypeNew, paraNew.ItemId);                
                ItemList list = new ItemList(itemTypeNew);
                list.Save();
                itemListitemNew[itemListTypeListFieldNew] = list.ID;
                itemListitemNew.Save();          
 
//List should be ready to use now:
                var itemListNew = ItemList.GetItemListById(Convert.ToInt32(itemListitemNew[itemListTypeListFieldNew]));        
               var newentry = new Item(itemTypeNew);
                newentry.Add(new KeyValuePair<string, object>("Title", (object)"TestTitle"));
          newentry.Add(new KeyValuePair<string, object>("Link", (object)"/TESTLINK"));          
                newentry.Save();
 
//New Item of correct type created          
                itemListNew.Relations.Append(newentry);
 
//Printing what it looks like          
                <p>@JsonConvert.SerializeObject(itemListNew)</p>

 

But the relations are always empty:

{"ItemType":"CTAItem","SortBy":null,"SortOrder":null,"Relations":[],"Connection":null,"Transaction":null,"ID":1305,"IsNew":false}

Am i going about it the wrong way?

Best regards,

Steen

 

 


Replies

 
Vladimir Shushunov Dynamicweb Employee
Vladimir Shushunov
Reply
This post has been marked as an answer

Hi Steen!

The problem is in Append method

Note, This method does not modify the elements of the collection. Instead, it creates a copy of the collection with the new element.

So you need to:

itemListNew.Relations = itemListNew.Relations.Append(newentry);
itemListNew.Save();

Or use ItemList.AddRelation method:

     ItemList.AddRelation(Convert.ToInt32(itemListitemNew[itemListTypeListFieldNew]), newentry.Id, sort);

Best regards, Vladimir

 

 

Votes for this answer: 1
 
Steen Nørgaard Perdersen
Steen Nørgaard Perdersen
Reply

Perfect. Kind of knew the problem was a stupid oversight on my behalf.

Thanks for answering!

STeen

 

You must be logged in to post in the forum