Assign Content Types to SharePoint Library depending of some conditions

If you need manipulate the content types of a SharePoint Library, it is not possible by using the browser user interface, then you should implement this by code. For example adds specific content types to folders in a document library when those folders are created with specific names.

See this example for understand this assign:
Suppose that a document library need load 4 file types for the Staffing company department:

  • Assign a Content Type for documents created in folder named “Resumes”
  • Assign a Content Type for documents created in folder named “References”
  • Assign a Content Type for documents created in folder named “Technical Exams”
  • Assign a Content Type for documents created in folder named “Medical Exams”
  • Before you should have created the Content Types in the SharePoint site, because the example assigns the existing Content Types. The following code shows how to achieve content type manipulation for this requirement:

    public override void ItemAdded(SPItemEventProperties properties)
    {
    base.ItemAdded(properties);
    SPListItem added = properties.ListItem;
    SPContentType ct_folder = added.ParentList.ContentTypes["Folder"];
    SPContentType ct_resumes = added.ParentList.ContentTypes["Resumes"];
    SPContentType ct_references = added.ParentList.ContentTypes["References"];
    SPContentType ct_technicalExams = added.ParentList.ContentTypes["Technical Exams"];
    SPContentType ct_medicalExams = added.ParentList.ContentTypes["Medical Exams"];

    if (added.ContentType.Id == ct_folder.Id)
    {
    SPFolder addedFolder = added.Folder;
    IList currentContentTypes = addedFolder.ContentTypeOrder;
    List contentTypes = new List();
    if (added.Title == "Resumes")
    {
    contentTypes.Add(ct_resumes);
    addedFolder.UniqueContentTypeOrder = contentTypes;
    addedFolder.Update();
    }
    if (added.Title == "References")
    {
    contentTypes.Add(ct_references);
    addedFolder.UniqueContentTypeOrder = contentTypes;
    addedFolder.Update();
    }
    if (added.Title == "Technical Exams")
    {
    contentTypes.Add(ct_technicalExams);
    addedFolder.UniqueContentTypeOrder = contentTypes;
    addedFolder.Update();
    }
    if (added.Title == "Medical Exams")
    {
    contentTypes.Add(ct_medicalExams);
    addedFolder.UniqueContentTypeOrder = contentTypes;
    addedFolder.Update();
    }
    }
    }

    You can include this code in a Event Receiver class for the document library, overriding the ItemAdded method.
    Now, when you select New Document over a Folder, the library uses the corresponding Content Type 🙂

    Leave a comment