Wednesday, February 02, 2011

Unable to add a lookup field using AddFieldAsXml –Solved!


I recently had a problem when trying to add a new lookup field programmatically. It turns out that Field ID was actually the culprit. You can't use a fixed field ID when using web.Fields.AddFieldAsXml(sColumnDefinitionXml) which is what the XML for a field is supposed to have when it is used as an element file in a feature, but not when you are adding the field using code.
Then:
Wrong XML definition for sColumnDefinitionXml


 

<Field Type=\"Lookup\" DisplayName=\"Chat Waiting Time\" Required=\"FALSE\" List=\"4c00bad4-e57d-417e-ad6e-d29fcad06c3f\" ShowField=\"AdvisorResultText\" Group=\"ChildLine Site Columns\" ID=\"{D4654C7B-7DDD-4c79-9CB1-7130B567C3BC}\" StaticName=\"ChatWaitingTimeLookUp\" Name=\"ChatWaitingTimeLookUp\" xmlns=\"http://schemas.microsoft.com/sharepoint/\" />"        

 

Right XML definition for sColumnDefinitionXml


 

<Field Type=\"Lookup\" DisplayName=\"Chat Waiting Time\" Required=\"FALSE\" List=\"4c00bad4-e57d-417e-ad6e-d29fcad06c3f\" ShowField=\"AdvisorResultText\" Group=\"ChildLine Site Columns\" StaticName=\"ChatWaitingTimeLookUp\" Name=\"ChatWaitingTimeLookUp\" xmlns=\"http://schemas.microsoft.com/sharepoint/\" />"        


Took it off and it worked like a charm. Now all lookup fields can be safely added by my feature receiver J.

1 comment:

Unknown said...

This isn't correct. I have been adding fields with an ID field with no problem. Do you have any references or is this only from your own experience?

I have a feeling that you couldn't do it because the field was already added and cached somewhere on the system. I had this issue when deleting my content hub and then recreating it and trying to activate my feature