I have just discovered that it is critical that you keep the length of StaticName values for Fields to 32 or under… anything after this is cropped and the resultant value becomes the InternalName. This means that if you try and call methods like GetByInternalName or ContainsField passing in your expected name, it will fail.
To help explain this, see the following code, where I am adding fields :
Guid listId = new Guid(Request.QueryString["List"]);
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists[listId];
// LIST OF FIELD GUIDS TO ADD TO THE LIST SPECIFIED IN THE QUERY STRING
// THESE FIELDS ARE DECLARED IN A FEATURE AND HAVE STATIC NAMES LONGER
// THAN 32 CHARACTERS
string[] fieldGuids = new string[] {
"{36924573-D81E-493e-98E0-9DAF4420FF86}",
"{33380026-51E7-456e-A601-AEB23C3E98C1}",
"{63000972-DBBC-4db0-A757-135A32446FC8}",
"{55935C52-6969-45bb-9757-C71DC3F4BED7}",
"{7BA783C7-93B9-4b2a-A1E3-B768094B2DDE}",
"{636E52EE-5635-4f4e-A93C-9FC0D6F0B8BA}",
"{6D5AB29D-C646-4b61-8F5A-68F443E437CB}"};
web.AllowUnsafeUpdates = true;
foreach (string guid in fieldGuids)
{
Guid fieldGuid = new Guid(guid);
// HERE WE ARE GETTING THE FIELD WE WANT TO ADD FROM THE SITE COLUMNS
SPField field = web.AvailableFields[fieldGuid];
// THE STATIC NAME IS MORE THAN 32 CHARS BUT THIS METHOD SEARCHES THE DISPLAY NAME AND, IMPORTANTLY,
// THE INTERNAL NAME – WHICH IS CROPPED AT 32 LONG. RESULT = FIELD NOT FOUND, WHEN IN FACT IT DOES EXIST
if(!list.Fields.ContainsField(field.StaticName))
list.Fields.Add(field);
}
list.Update();
N.B. if you intend to use this code then always remember to put code like this in a try/catch/finally so you can reset the web.AllowUnsafeUpdates value back to false.
Posted
06-25-2008 3:05 PM
by
georgebonney