0

I can't seem to find any documentation on this. I have an item, that has a TreelistEx field:

enter image description here

I want to programatically add a new item to this field, preferably using glass mapper but vanilla sitecore will do if needs must.

Can anyone help me out here? How do I go about this?

You'll have to excuse the lack of details, I can't find a single thing to point me in the right direction here.

Liam
  • 27,717
  • 28
  • 128
  • 190

2 Answers2

1

The TreeList and TreeListEx work the same way as the multilist.

using (new Sitecore.SecurityModel.SecurityDisabler())
{

    Item newItem = Sitecore.Context.Item;

    newItem.Editing.BeginEdit();

    MultilistField mlf = newItem.Fields["FieldName"];

    // adding an item
    mlf.Add(ItemToAdd.ID.ToString());

    // removing an item
    mlf.Remove(ItemToRemove.ID.ToString());

    newItem.Editing.EndEdit();
}
Chris Auer
  • 1,405
  • 12
  • 23
  • Seems an improvement on my effort. Why does it accept a Guid that's been stringed(retorical)?! Stupid sitecore – Liam Mar 08 '16 at 16:56
  • Because in the underlying data, everything is a string. – jammykam Mar 08 '16 at 17:02
  • [Stringly typed](http://blog.codinghorror.com/new-programming-jargon/) *Used to describe an implementation that needlessly relies on strings when programmer & refactor friendly options are available....Excessively stringly typed code is usually a pain to understand and detonates at runtime with errors that the compiler would normally find.* :) – Liam Mar 08 '16 at 17:03
  • Welcome to Sitecore. Shouldn't have to say that since I know you are not new. – jammykam Mar 09 '16 at 13:26
0

It seems that sitecore stores these fields as a piped separated list. So you can edit the values as a string (this is very stringly typed). So can manipulate the values as a string (god this is crappy). So to add an item into the treelistEx that has a id of {652FD742-AAE3-468D-81BE-7EF18E06B796} you can:

Item item;
item.Editing.BeginEdit();
item.Fields["fieldname"].Value += "|{652FD742-AAE3-468D-81BE-7EF18E06B796}";
item.Editing.EndEdit();

It's pretty simple to split the string into an array, manipulate and turn it back to a string.

TBH this code is pretty crappy. I'd like to think (knowing sitecore I'm not holding my breath) that there is a better way to achieve this...

Liam
  • 27,717
  • 28
  • 128
  • 190