How to modify Content Type once it is deployed?

Once the Content Type is deployed it is very difficult to modify them via Feature deployment. Once the Content Type is being used by any of the object in SharePoint, it’s difficult to modify that Content Type without deleting the associate content.

For Example, There is a Page Layout (let’s name it as SamplePL) which is bind to the Content Type (let’s name is as SampleCT). User creates pages using SamplePL. Now, if there is a requirement to add new field to the SamplePL, we need to first add that field to the SampleCT and then add that field to the SamplePL. If the deployment is happening through feature deployment (automated deployment) then the SampleCT will never be refreshed on the server.

To overcome this problem there are two approaches (as far as I know):

1. Manual Changes:

a. Admin has to manually delete the content which is created using the SamplePL.

b. Admin has to manually add the column to the Content Type via the SharePoint UI Interface.

c. Add that newly added column to the SamplePL and then only the SamplePL will start showing that new field.

2. Via Object Model:

If the content is huge and if it’s practically impossible to delete that content to change the Content Type, the other way is to write a small utility which can do the job for you without even deleting the content. Here is the example, i am deleting a field from the SampleCT:

string contentTypeName = "SampleCT";

try

      {

      SPContentType contentType = site.RootWeb.ContentTypes[contentTypeName]; // site is the SPSite object

if (contentType == null)

            {

                  // display error message

return;

}

            else

            {

                  // Getting Fileds collection from the Site Columns Gallery

            SPFieldCollection fileds = site.RootWeb.Fields;

                  if (fileds.ContainsField("FieldName"))

{

                  // SPField field = fileds.GetField("FieldName"); // This method will get the object of the field

                        // Checking for the field in SampleCT

                        if (!contentType.Fields.ContainsField("FieldName"))

                        {

// In this example I am deleting a Field from the Content Type

                            contentType.FieldLinks.Delete("FieldName");

                            contentType.Update(); // Updating Content Type is very important otherwise changes will be reflected

}

                    }

}

}

You can put the entier code block inside the RunWithElevatedPrivileges statement if you are facing permission issues:

SPSecurity.RunWithElevatedPrivileges(delegate(){

});

Hope this blog helps all those who are wondering the behaviour of the Content Types.

Cheers!!!!

Comments