Access Droplink, Droptree, and Grouped Droplink fields

Version: 10.4

You can access field types allowing the user to select a single item, including Droplink, Droptree, and Grouped Droplink fields by using the Sitecore.Data.Fields.ReferenceField class.

The Sitecore.Data.Fields.ReferenceField.TargetItem property contains the Sitecore.Data.Items.Item specified by the field, or Null. For example, to access the item specified by the Droptree field named ReferenceField in the /Sitecore/Content/Home item in the Master database:

RequestResponse
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

Sitecore.Data.Fields.ReferenceField referenceField = item.Fields["referencefield"];

if (referenceField==null)
{
    // Field does not exist
}
else if (referenceField.TargetItem==null)
{
    // No item selected
}
else
{
    Sitecore.Data.Items.Item referencedItem = referenceField.TargetItem;
    // Process referenced item
}

You can set the Sitecore.Data.Fields.ReferenceField.Value property to the ID of an item to update a field of one of the supported types. For example, to ensure the Droptree field named ReferenceField in the /Sitecore/Content/Home item in the Master database specifies the /Sitecore/Content/Home/Sample item:

RequestResponse
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

Sitecore.Data.Fields.ReferenceField referenceField = home.Fields["referencefield"];

if (referenceField==null)
{
    // Field does not exist
}
else
{
    Sitecore.Data.Items.Item sample = master.GetItem("/sitecore/content/home/sample");

    if (sample==null)
    {
        // Sample does not exist 
    }
    else if (sample.ID.ToString()!=referenceField.Value)
    {

        home.Editing.BeginEdit();
        referenceField.Value = sample.ID.ToString();
        home.Editing.EndEdit();

    }
}

Do you have some feedback for us?

If you have suggestions for improving this article,