We can achieve this with the help of SharePoint Object Model. First we will find the number of documents for any specific content type in the document library and then in ItemUpdated event and ItemDeleted Events for the document library we can have the code to hide/display the Content Type:
To calculate the number of items related to a specific Content Type in a document library we can use following Code (cant put the code so putting it in sky drive):
private int FindNumberOfItems(SPList list)
{
SPQuery qry = new SPQuery();
qry.Query = "<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>ContentTypeName</Value></Eq></Where>";
return list.GetItems(qry).GetDataTable().rows.count;
}
Download the code from:
So lets say X is the Number of Docs associated to a particular content type returned by the above code and now we want to hide the content Type when this number reaches 5 then the code required to be used is:
Code in the ItemUpdated Event:
If (X>=5)
properties.List.ContentTypes["NameOfContentType"].Hidden = true;
//This will make the Content Type not visible under “New” button in the toolbar
properties.List.ContentTypes["NameOfContentType"].Update();
Now same way we can start displaying this content type once the number of docs reaches below the specified limit. We need to call the code in the ItemDeleted Event.
Code in the ItemDeleted Event:
If (X<5) properties.List.ContentTypes["NameOfContentType"].Hidden = false; //This will make the Content Type visible under “New” button in the toolbar
properties.List.ContentTypes["NameOfContentType"].Update();
You may be interested to see
Introduction to Content Types
1 comment:
Thanks for the post. I was wondering why my content type was still showing up. Turned out that I was hiding the site content type rather than the list content type.
Post a Comment