Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore's Field.HasValue returning false, even when there is a Value?

I'm attempting to use Sitecore's Field.HasValue property in Razor syntax to test a particular field, but no matter what I try, the field always seems to be false.

  • I'm using Sitecore 8.
  • The Sitecore field, "Header Number" is a Single-Line Text field

Here's what I'm trying:

@{
    var phoneNumber = "";
    var numberField = Model.Item.Fields["Header Number"];
    if (numberField != null && numberField.HasValue)
    {
        phoneNumber = numberField.Value;
    }
}

As you can see in the screenshot below:

  • numberField is being correctly set to a Sitecore Field
  • numberField.HasValue is reporting false
  • However numberField.Value is (correctly) returning the value of the field
  • Because of the failure to fire the if block, phoneNumber is never set:

Screenshot of Breakpoint showing variable values

Is this a bug? Am I using HasValue incorrectly or is there another Sitecore method I should be using to safely test if fields have a value?

like image 659
Robotnik Avatar asked Feb 26 '16 09:02

Robotnik


1 Answers

Most probably value of this field comes from the Standard Values item (is inherited).

HasValue property only returns true when the value is set on the item itself.

Here is the implementation of HasValue property:

public bool HasValue
{
  get
  {
    return this.GetValue(false, false) != null;
  }
}

public string GetValue(bool allowStandardValue, bool allowDefaultValue)
{
  ...
}

You can check ContainsStandardValue property to check if the value comes from the Standard Values.

like image 137
Marek Musielak Avatar answered Oct 24 '22 13:10

Marek Musielak