Today we are going to talk about the how we can use content type in object model. We will see classes and how to bind any content types with the list or document library.
We all know about the content type is that it can be treated as reusable component that can be used in list and library or any other way. Content type will always inherit from parent content type.
We can have item based content type attached to the list and document based content type attached with the document library. We cannot attach the vice versa.
First to get all the content type in our site level we will call AvailableContentTypes method which will give us SPContentTypeCollection object. Each individual object in SPContentTypeCollection is SPContentType. One more method we will use which takes the content type ID that we know and will directly give us that SPContentType.
Before that please make a note of a difference between the AvailableContentTypes and ContentTypes property of SPWeb class.
ContentTypes will return all content types only with reference to the current web but AvailableContentTypes will return you all content types of current web as well as all parent webs as well.
Ok, coming back to the point, here is a way we can proceed working with content type through the object model.
SPContentType objContentType = objWeb.AvailableContentTypes[“contenetypeID”];
objList.ContentTypes.Add(objContentType);
objList.Update();
Remember if your conenet type is about fields, then when the content type is added to the list, fields gets added to the field collection but won’t show those fields. So you need to take out the SPView class object and add the ViewFields for those new created fields through the ContentType.
Same, if we want to remove any content type, then follow the below approach.
Foreach(SPContentType objContentType in objList.ContentTypes)
{
If(objContentType.Name.toUpper() == “contenetypeID”)
{
objContentType.Delete();
break;
}
}
No comments:
Post a Comment