Friday, January 22, 2021

Sitecore 10 - Simple Item extension method to read value from Droplink, Droptree, and Grouped Droplink fields etc.

 Recently, I was working on a requirement to show the selected item field value into a view  (Assume an option to choose a custom icon for the view or a feature).


There are a few options available that get the field id and read the item and get the field value, but in this case, I preferred to create an item extension method that can be used for any similar type of fields, here is the sample for the reference.


public static string GetSampleReferenceFieldValue(this Item item, ID referenceFieldId, ID targetFieldId)

        {

            ReferenceField referenceField = item.Fields[referenceFieldId];

            return referenceField?.TargetItem == null ? string.Empty : referenceField.TargetItem[targetFieldId];

        }

and in the view, we can simply call this as an example below - 

item.GetSampleReferenceFieldValue(Templates.TemplateNameFields.FieldId, Templates.TemplateNameFields.FieldId);

Hope that will help to others.

 

No comments:

Post a Comment