Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use fieldLinks when adding fields to a contenttype?

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

like image 284
Ole Albers Avatar asked Jan 26 '12 13:01

Ole Albers


2 Answers

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.

like image 85
Rich Bennema Avatar answered Nov 15 '22 17:11

Rich Bennema


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.

like image 26
Ole Albers Avatar answered Nov 15 '22 17:11

Ole Albers