Thursday, April 28, 2011

Impact of Content Type changes on existing Lists in SharePoint 2007

In real world, we come across of many business scenarios that force us to add/edit/remove some columns to our existing Lists. Sometimes these Lists are heavily populated with large amount of data and workflows running on them. As we all know we add columns to a SharePoint List using Content Types for reusability purpose. So changing the columns of a List means changing the Content Type associated with the List. In such a situation, several questions come to one's mind.

1. Can I simply add the new field references to my existing ContentType CAML and re-activate the feature ? Will the new fields be added to the existing Lists ? Will it impact the running workflows on the Lists ?

We all know for sure that the new fields will be part of a new List that we create after the change. But what about the existing Lists. Simply adding the new field references to the existing Content Type CAML will not reflect in the existing Lists. You need to add these field references programmatically inside a feature receiver by passing true to the Update() method of the Content Type. Here is the sample code snippet.


public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPWeb web = ((SPSite)properties.Feature.Parent).OpenWeb())
{
SPContentType pcType = web.ContentTypes[new SPContentTypeId("GUID of the existing Content Type")];
SPField newField = web.Fields[new Guid("GUID of Field")];
SPFieldLink newFieldLink = new SPFieldLink(newField);
pcType.FieldLinks.Add(newFieldLink);
pcType.Update(true);
}
}


Any change in the Content Type should not impact the running workflows on the Lists.

When we remove fields from an existing Content Type and re-deploy it, the same columns would not be removed from the Lists that use the Content Type. Safety of the List Data is utmost important for SharePoint.

At the end, Don't forget to remove these field references inside feature deactivating event.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
using (SPWeb web = ((SPSite)properties.Feature.Parent).OpenWeb())
{
SPContentType pcType = web.ContentTypes[new SPContentTypeId("GUID of the existing Content Type")];
SPField newField = web.Fields[new Guid("GUID of Field")];
if (pcType.Fields.ContainsField(newField .Title))
pcType.FieldLinks.Delete(new Guid(GUID of Field));
pcType.Update(true);
}
}


Some facts related to Content Type -
If you delete the content type associated to a List, then it won't delete the columns in the List. They would be still exist as local columns. if you want to remove them from your List, then you have to delete them manually or programmatically.

No comments:

Post a Comment