Creating Multilist Fields

Creating Multilist Fields

The Sitecore.Configuration.Factory class encapsulates the general information available in the web.config file and contains methods that provide access to this information and the means to override it.

This snippet uses a fields collection to reference the field

  • Returns null if the field does not exist or the field value is null
  • Does not generate inline editing controls for the Page Editor
  • Useful for field types other than simple field types

This snippet also applies to a Checklist, Treelist, or TreelistEx field.

  1. Create an object for the database where the item is located - replace SitecoreDB with the name of the Sitecore database where you want to perform the update, typically “master”
  2. Create an object for the item in the database that will serve as the multilist - replace itempath with the absolute path to the item in the Content Tree, such as “/sitecore/content/home/about” - Sitecore does compare case when evaluating item paths
  3. Create an object of type multilistfield for the multilist field
  4. Build the multilist


C# Web Control Code

<>Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase("SitecoreDB");

Sitecore.Data.Items.Item item = db.GetItem("itempath");

Sitecore.Data.Fields.MultilistField multilist = item.Fields["fieldname"];

multilist.Add(item.ID.ToString());

 

if (!multilistfield.Contains(item.Parent.ID.ToString()))

{

      multilistfield.Add(item.Parent.ID.ToString());

}


if (multilistfield.Contains(item.ID.ToString()))

{

      multilistfield.Remove(item.ID.ToString());

}