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

1

6

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?

Valence answered 26/2, 2016 at 9:10 Comment(2)
Can you not check !String.IsNullOrEmpty(numberField) in your if block ?Dentition
@Dentition - I probably can this time, seeing as it's a String, but I'm more worried about the more complex data types that Sitecore supports and that I'm using .HasValue on elsewhere.Valence
I
7

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.

Isabelleisac answered 26/2, 2016 at 9:15 Comment(5)
@MarekMusielak : Is ContainsStandardValue property exposed by nullable type itself?Achromatize
@LolCoder아카쉬 this has nothing to do with nullable type. Field type is not nullable. It's Sitecore class and it has HasValue property.Isabelleisac
It appears calling ContainsStandardValues after calling HasValue has a different result compared to if we call ContainsStandardValues beforehand. Just a heads up, I had to watch the order of operations when testing against bothValence
Strange, because this should not happen. Although, in case it was happening in the past, it is not happening now. I am checking this with Sitecore 10.1.0 version and whether I call ContainsStandardValues before or after HasValue, there is no difference.Foremost
@Varun - good to know. If I recall correctly, this project was Sitecore 8.Valence

© 2022 - 2024 — McMap. All rights reserved.