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
- Parent2 -> Parent2["Odd"] = 3,1
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();
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.