SharePoint Client Object Model Error: This functionality is unavailable for field collections not associated with a list.

I got this error while trying to create a SharePoint ContentType using the Client Object Model. The problem occurred when I tried to add an existing field to the new Content Type using the contentType.Fields.Add method.

However, we can only add existing Fields only to a List in this manner. For a ContentType, we have to use the contentType.FieldLinks.Add method. The below commented line was throwing the error. I then replaced the Field with FieldLinks and then, my custom ContentType (Piyush_ContentType)was created with all the SiteColumns of the Parent Content Type (Task) plus one custom SiteColumn, Birthday (Date and Time).

Remember, to mention the contentType.Update(true/false) at the end to map your changes to the server.

Necessary namespace
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
string siteUrl = "http://servername:12345/";
SP.ClientContext ctx = new SP.ClientContext(siteUrl);
this.ctx.Load(this.ctx.Web);
SP.Web web = this.ctx.Web;
SP.FieldCollection fieldCollection = web.AvailableFields;
SP.ContentTypeCollection conCollectionList = web.ContentTypes;
ctx.Load(fieldCollection);
ctx.Load(conCollectionList);
ctx.Load(conCollectionList, l => l.Include(t => t.Parent.Id, t => t.Fields.Include(p => p.InternalName)));
ctx.ExecuteQuery();

//Setting Task as the Parent Content Type
SP.ContentType cTypeParent = conCollectionList.FirstOrDefault(t => t.InternalName == "Task");

SP.ContentTypeCreationInformation ctTYpeCreationInfo = new SP.ContentTypeCreationInformation();

ctTYpeCreationInfo.ParentContentType = cTypeParent;
ctTYpeCreationInfo.Name = "Piyush_ContentType";
ctTYpeCreationInfo.Group = "Piyush";
ctTYpeCreationInfo.Description = "Custom Content Type for testing";

SP.ContentType contentType = conCollectionList.Add(ctTYpeCreationInfo);

SP.Field field = ctx.Web.Fields.GetByInternalNameOrTitle("Birthday");

//Faulty code
//contentType.Fields.Add(field);

SP.FieldLinkCreationInformation fieldLink = new FieldLinkCreationInformation();
fieldLink.Field = field;
contentType.FieldLinks.Add(fieldLink);
contentType.Update(true);
           
ctx.ExecuteQuery();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.