Search This Blog

Monday, March 28, 2011

Deleting site columns with all references from a site collection : SharePoint 2010

Its a common scenario in many sharepoint projects wherein we need to delete a site column from a site collection which is no longer being used.

However, when we try to delete such site column programmatically,sharepoint gives us the error:

 "Site columns which are included in content types or on lists cannot be deleted. Please remove all instances of this site column prior to deleting it."

Therefore, we need to delete all references of this site column wherever they are being used in the site collection.

In order to achieve this, SharePoint 2010 provides a very useful method called 'ListsFieldUsedIn()' which can be called on a SPField object.This method provides us with a 'SPFieldTemplateUsage' collection in which we can find the 'WebID',as well as the 'listID' where this site column is being used.Once we have this collection, we can iterate through it and delete all the column references using the 'WebID' and 'ListID'.

Once all these references have been deleted , we can simply call the Delete() method on the 'SPField' object to delete the site column.

Here's the method which takes the field to be deleted and the root web of the site collection as input parameters and deletes the site column along with all the references:

private void DeleteColumn(SPField field, SPWeb web)
        {
            ICollection<SPFieldTemplateUsage> collection = field.ListsFieldUsedIn();
            foreach (SPFieldTemplateUsage usage in collection)
            {

                SPWeb webSite = web.Site.AllWebs[usage.WebID];
                SPList list = webSite.Lists[usage.ListID];

                if (list.ContentTypesEnabled)
                {
                    SPContentTypeCollection listContentTypes = list.ContentTypes;
                    foreach (SPContentType contentType in listContentTypes)
                    {
                        if (contentType.Fields.ContainsField(field.InternalName))
                        {
                            contentType.FieldLinks.Delete(field.InternalName);
                            contentType.Update();

                        }

                    }
                }

                if (list.Fields.ContainsField(field.InternalName))
                {
                    list.Fields.Delete(field.InternalName);
                }



                webSite.Dispose();
            }

            foreach (SPContentType contentType in web.ContentTypes)
            {

                if (contentType.Fields.ContainsField(field.InternalName))
                {
                    contentType.FieldLinks.Delete(field.InternalName);
                    contentType.Update(true);

                }

            }

          
            field.Delete();
          

        }





No comments:

Post a Comment