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;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>