August 13, 2010

Insert a field to content type in SharePoint 2007

Today I had a problem in adding a field to a content type. I searched on everything but couldn't find out any solution. When trying out many things, finally got the answer.

When you want to add a field to a content type, first we need to add that field to the web, then only we can add the field to the content type, and finally to the list which has the content type.

Here is the code that I used for this.

public static void CreateSpField(SPWeb web, string contentTypeName, string fieldName, string fieldType, string listName)
{
web.AllowUnsafeUpdates = true;

web.ParentWeb.Fields.Add(fieldName, SPFieldType.DateTime, false);

SPContentType contentType = web.ParentWeb.ContentTypes[contentTypeName];
SPFieldLink fieldLink = new SPFieldLink(web.ParentWeb.Fields[fieldName]);
contentType.FieldLinks.Add(fieldLink);

contentType.Update();
web.ParentWeb.Update();

SPList list = web.Lists[listName];
list.Fields.Add(web.ParentWeb.Fields[fieldName]);
list.Update();

web.AllowUnsafeUpdates = false;
}

No comments:

Post a Comment