Monthly Archives: October 2013

Traverse all fields for Sitecore item without loading all values

When working with clones in Sitecore you sometimes need to call ReadAll() to get hold of every field. This gives the penalty of loading all the items field values one by one.

Here is an extensionmethod to get all TemplateFields for the item.

    using Sitecore.Data.Items;
    using Sitecore.Data.Managers;
    using Sitecore.Data.Templates;

    public static class SitecoreItemExtensions
    {
        public static TemplateField[] GetTemplateFields(this Item item)
        {
            Template template = TemplateManager.GetTemplate(item);
            if (template == null)
            {
                return new TemplateField[] { };
            }

            return template.GetFields();
        }
    }

Then just loop through this collection and lazy load only the fields you want, like this:

    foreach (var field in Sitecore.Context.Item.GetTemplateFields())
    {
        // logic goes here
    }

Beware of using Field.HasValue in Sitecore

After calling Field.HasValue or Field.GetValue(false, x) the two properties ContainsStandardValue and InheritsValueFromOtherItem is unconditionally reset to false.

The problem is the first two rows in the public function Field.GetValue(…)

    public string GetValue(bool allowStandardValue, bool allowDefaultValue)
    {
        this.containsStandardValue = 0;
        this.inheritsValueFromOriginalItem = 0;
        // ...
    }

This generates problems when working with items that receives their values from the StandardValues or Clones of items.

The same problem has already been spotted in Sitecore 6.4 by Sean Kearney

http://seankearney.com/post/Field-ContainsStandardValue-in-Sitecore-is-Buggy.aspx

I just verified the problem still exist in Sitecore 7.0. I reported the problem with issue number #396060.

Simple workaround, avoid calling HasValue:

    // field.Value calls GetValue(true, false) internally which is safe
    var fieldValue = field.Value;
    var hasValue = fieldValue != null;