Saturday, July 18, 2009

Ways to check field type in code

As a “safe check” code operation in Sitecore, you frequently check for expected field type before working with a field.
While there is an easy way to do it via “Type” property of a field returning string, it may not look really nice and considered hard-coding:
if (Sitecore.Context.Item.Fields["featured"].Type == "Droplink")
Plus backwards compatibility of such code is questionable.
I suggest you use the Sitecore.Data.Fields.FieldTypeManager class that has “GetField” method where you can pass the instance of your field and use “IS” keyword to check if it is safe to cast:
if (FieldTypeManager.GetField(Sitecore.Context.Item.Fields["title"]) is TextField)
if (FieldTypeManager.GetField(Sitecore.Context.Item.Fields["text"]) is HtmlField)
if (FieldTypeManager.GetField(Sitecore.Context.Item.Fields["featured"]) is LookupField)
if (FieldTypeManager.GetField(Sitecore.Context.Item.Fields["metakeywords"]) is MultilistField)

Just make sure to replace the field name strings with a reference to a GUID class and you will be all set!


Kamsar said...

Thanks Alex, I did a bit of refactoring in one of my libraries that we use to create a set of strongly typed template classes. In my case I had a TemplateFieldItem so I used FieldTypeManager.GetFieldType(templateFieldItem.Type) to look it up.

Kamsar said...

Because of the way the default FieldTypes.config is set up, this method is unable to resolve useful type information for Number, Integer, Multi-line Text, Password, and Name Value List field types. These field types do not have a mapping onto a representational class, so I had to resort to the hardcoded method in those cases.

Kamran A said...

You say to use a GUID reference; is this better than using names or is it a trade-off? A name could change, but I could also remove and re-add a field which would force it to use a new GUID.