Tuesday, July 24, 2012

SharePoint 2010 Modifying deployed/existing content types

Scenario: You have created a custom content type with required site columns declaratively (XML) and deployed it to production environment. Later business requirement has been changed and you have been asked to modify existing content type by adding a new site column. And push down the new site column to all the lists that are referencing this content type

Solution: The best approach is when you are creating site columns, content types initially, it is recommended to create them declaratively. Later if you have to add/modify existing site columns or content types it is recommended to do it programmatically.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
            SPWeb curWeb = ((SPSite) properties.Feature.Parent).RootWeb;
            //Create Custom Site Column
            curWeb.AllowUnsafeUpdates = true;
            string fieldNamev2 = curWeb.Fields.Add("SriSCV2", SPFieldType.Text, false);
            SPFieldText v2Field = (SPFieldText)curWeb.Fields.GetFieldByInternalName(fieldNamev2);           
            SPContentType ct = curWeb.ContentTypes["SriniTestCTSC"];
                            if(ct != null)
                                SPFieldLink FieldRef = new SPFieldLink(v2Field);                               
                            curWeb.AllowUnsafeUpdates = false;