When I search for documentation about creating contenttypes using code (C#) I always find examples using a SPFieldLink to link to an existing field of the site and adding this via
contentType.FieldLinks.Add()
But there is also a method to add fields directly. Is there a good reason why I should not simply add fields using
contentType.Fields.Add(SpField())
?!?
thanks in advance
It might help to look at the XML for a list.
Here is the XML for the Announcement Content Type:
<FieldRefs>
<FieldRef ID="{7662cd2c-f069-4dba-9e35-082cf976e170}" Name="Body" />
<FieldRef ID="{6a09e75b-8d17-4698-94a8-371eda1af1ac}" Name="Expires" />
</FieldRefs>
Here is the XML for the Announcement List:
<Fields>
<Field ID="{7662cd2c-f069-4dba-9e35-082cf976e170}" Type="Note" RichText="TRUE" RichTextMode="FullHtml" IsolateStyles="TRUE" NumLines="15" Name="Body" DisplayName="$Resources:core,camlid2;" Sortable="FALSE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Body">
</Field>
<Field ID="{6a09e75b-8d17-4698-94a8-371eda1af1ac}" Type="DateTime" Name="Expires" DisplayName="$Resources:core,camlid3;" Format="DateOnly" FromBaseType="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Expires">
</Field>
</Fields>
Lists have Fields. Content Types have FieldRefs.
I'm not sure if this is exactly right, but I always describe it as the difference between classes and interfaces or abstract classes. A Content Type is the definition for a list, but, like an interface, it does not contain any data or functionality. Since Fields contain data and functionality, Content Types (disassociated from a list) do not have Fields, they have FieldRefs. YMMV - but that always helps me keep them straight.
There seems to be a simple reason like I found out by now: It just does not work on ContentTypes. When trying to add a Field directly SP2010 sends me an exception:
This functionality is unavailable for field collections not associated with a list.
I absolutely did not expect this (nor the spanish inquisition), but it just does not seem to be possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With