1
votes

How to set a multi-reference field value programmatically if I have collection of items/ids?

E.g. Build following raw value "{guid1}|{guid2}|{guid3}..."


In my specific case I need to import a tree of items and on one level a parent was using children as repository and it also had a multi reference list to a subset of the children based on some criteria. I wanted to build a flexible list based on ordering or filtering and then set value of parent without making code specific to a list type - parent field can be any list.

E.g. Custom list with rule "where [is odd] orderby child desc" build for each Parent and set to field "Odd"

  • Parent1 -> Parent1["Odd"] = 5
    • 2
    • 5
  • Parent2 -> Parent2["Odd"] = 3,1
    • 1
    • 2
    • 3
2
"... Yes! Stack Exchange has always explicitly encouraged users to answer their own questions ... " stackoverflow.com/help/self-answerpgk
@ZacharyKniebel Both my question and answer are MUCH more generic (better) than the possible duplicate that you have referencedpgk
Yup, Jeff Attwood even blogged about it: blog.stackoverflow.com/2011/07/… Don't like the question/answer? Then downvote it.jammykam
Fair enough - I will correct it.Zachary Kniebel

2 Answers

4
votes

Use class Sitecore.Text.ListString to build the value

Example:

// Incomplete code snippet assumes variable Item item with list field "References" 
// and IEnumerable<ID> references

Sitecore.Text.ListString referencesValue = new Sitecore.Text.ListString();

foreach(ID id in references)
{
   string idString = id.ToString();
   if (!referencesValue.Contains(idString))
   {
       referencesValue.Add(idString);
   }
}    

item.Editing.BeginEdit();
item["References"] = referencesValue.ToString();
item.Editing.EndEdit();
2
votes

According to the cookbook link provided by Zachary, this seems to be the correct way to access such a field:

    Sitecore.Data.Fields.MultilistField multiselectField = item.Fields["multiselect"]

The individual members of the list returned by Sitecore.Data.Fields.MultilistField.GetItems() method are never Null. If a user has deleted an item without updating the references to that item, the GetItems() method excludes that item from its results. [...] You can add items to a supported field type using the Sitecore.Data.Fields.MulitlistField.Add() method, and remove items using the Sitecore.Data.Fields.MulitlistField.Remove() method.