Gotcha in SPFieldType

So I was playing with some examples of exporting some site columns, wrapping them into features and then installing them on a new box. All straightforward except when it came to publishing webs.

The SPFieldType enum has a number of options, none of which look particularly like "Publishing Image" or "Publishing HTML". When iterating through the available fields in my root web:

foreach (SPField spField in rootWeb.Fields)
{
   string fieldType = spField.Type.ToString("f");
}

I was surprised to find that these fields were returning "Invalid" as their field type.

Only by chance, some time later, did I stumble upon the alternative:

foreach (SPField spField in rootWeb.Fields)
{
   string fieldType = spField.TypeAsString;
}

which gave "Image" and "HTML" as the field types.

Confused? I was.

EDIT: A bit of reflection shed some light on this. Not a lot, but a bit. The field "Type" has the following code:

public SPFieldType Type
{
   get
   {
      return SPField.GetFieldType(this.TypeAsString);
   }
   set
   { … }
}

GetFieldType attempts to set the string passed  to it to the enum, and returns SPFieldType.Invalid if it can't – e.g. when its a field type which is only exposed by MOSS.

Leave a Reply


Gotcha in SPFieldType

So I was playing with some examples of exporting some site columns, wrapping them into features and then installing them on a new box. All straightforward except when it came to publishing webs.

The SPFieldType enum has a number of options, none of which look particularly like "Publishing Image" or "Publishing HTML". When iterating through the available fields in my root web:

foreach (SPField spField in rootWeb.Fields)
{
   string fieldType = spField.Type.ToString("f");
}

I was surprised to find that these fields were returning "Invalid" as their field type.

Only by chance, some time later, did I stumble upon the alternative:

foreach (SPField spField in rootWeb.Fields)
{
   string fieldType = spField.TypeAsString;
}

which gave "Image" and "HTML" as the field types.

Confused? I was.

EDIT: A bit of reflection shed some light on this. Not a lot, but a bit. The field "Type" has the following code:

public SPFieldType Type
{
   get
   {
      return SPField.GetFieldType(this.TypeAsString);
   }
   set
   { … }
}

GetFieldType attempts to set the string passed  to it to the enum, and returns SPFieldType.Invalid if it can't – e.g. when its a field type which is only exposed by MOSS.

Leave a Reply