1
votes

For the sitecore item testItem how can I make sure that this item has the field "Title".

I am asking because I am creating some fields in an item's template programmatically. So a field should not be created again if it already exists.

Because with this code I can get if the field has some value or not.

testItem["Title"] 
testItem.Fields["Title"] 
3
Just check for null. It's simply a collection.Liam
What if the Field Title exists but it contains null?Kamran
Then it won't be null but it's .Value will beLiam
Do you want to consider inherited fields as belonging to the current template? For example if current template does not have "Title", but the parent template does, what would you like to happen?Konstantin

3 Answers

8
votes

Please check this code, you are checking if item, fields collection and field value is not null

if(testItem!= null && testItem.Fields != null && testItem.Fields["Value"] != null)
{
  string name = testItem.Fields["Title"].Value;
}
2
votes

Code below will return value, including Standard or Default value for the field:

        if (testItem.Fields["Title"] != null && testItem.Fields["Title"].HasValue)
        {
            string title = testItem["Title"].Value;
        }
0
votes

To save having to check the field against your testItem more than once you could cast to a field and then: check the field for null, that it has a value and then retrieve the value.

The advantage here is that if you need to access the field in several places you don't have to retrieve from testItem each time.

e.g.

Field titleField = testItem.Fields["Title"];

if (titleField != null && titleField.HasValue)
{
    //do something with value
    string fieldValue1 = titleField.Value;

    //or (see intellisense for params)
    string fieldValue2 = titleField.GetValue(true);
}