Monday, April 6, 2009

AddFieldAsXml bug

Yes, there is a bug on this function allowing that the field created using this function to have after creation as InternalName the DisplayName.

This can cause problems when you ranslate your field name into other languages. In this case when you will try to access your field an error will occure.

This bug can be fixed with a small workaround. For this, into our function that create the field we have to get the InternalName , create the field and after that replace the InternalName of the new created field with the one that we saved before. This solution can be used together with a solution presented into a previous post.

private void SetTheProperGUID(SPList catList, SPField catField, SPList pageLibList) 
{
string fieldXml = catField.SchemaXml;
string strInternalName = catField.InternalName;
string strDisplayName = catField.Title;
Regex regex = new Regex(@"List=\""(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}\""");
if (regex.IsMatch(fieldXml))
{
fieldXml = regex.Replace(fieldXml, "
List=\"" + catList.ID.ToString("B").ToLower() + "\"");
}
// a SharePoint bug force us to make a workaround
// DisplayName must be the same as InternalName at creation
string oldValue = "DisplayName=\"" + strDisplayName + "\"";
string newValue = "DisplayName=\"" + strInternalName + "\"";
fieldXml = fieldXml.Replace(oldValue, newValue);
catField.Delete();
pageLibList.Fields.AddFieldAsXml(fieldXml);
// now the DisplayName must be set with the proper value
SPField fixedField = pageLibList.Fields[strInternalName];
fixedField.Title = strDisplayName;
fixedField.Update();
}

No comments:

Post a Comment