Tuesday, July 1, 2008

Custom Site Column in an existing OOTB List or ContentType

Today I will explain you on how to add a custom site column to an existing Out of the box (OOTB) List type or a content type. There will be instances during your project life cycle when you will want to provision a column to a particular List type or content type, for example you want to add a new column "Expert Comments" to a Wiki library. And you also want to provision this column to any new Wiki library created hereafter in the existing site.

Now for adding a new site column to custom list, you can add it directly when provisioning custom List Definition you can learn this here. But if you want to add a site column to already provisioned list you need to do it through object model.

Firstly you need to find the system content type for a List. Every list in in SharePoint uses a content type, either system content type or custom content type. You can view the content type hierarchy here. And you can find an associated content type for a system List using following lines of code in a console app:

using (SPSite site = new SPSite("http://devmoss/)"))

{

using (SPWeb web =
site.OpenWeb())

{

//List Content types in a web
foreach (SPContentType ct in web.ContentTypes)
{
Console.WriteLine(ct.Name);
}
Console.WriteLine("-------------------------");

//List Content types in a List
SPList list = web.Lists["Posts"];
foreach (SPContentType ctl in list.ContentTypes)
{
Console.WriteLine(ctl.Name);
}
Console.ReadLine();
}



Now once you know the content type of a List in which you wish to add a
custom column, you can use it add a new SPFieldLink to that SPContentType
object. Below is the sample code:




using (SPSite site = new SPSite("http://devmoss001/)"))
{
using (SPWeb web = site.OpenWeb())
{

try
{
string newColumn= "New Column";

//Construct required content type objects
SPContentType wikiContentType = web.ContentTypes["Wiki Page"];

//Check if the site column already exists
if (!web.Fields.ContainsField(newColumn))
{
//If the site column doesn't exist then create a new column and assign it to custom columns group
popularity = web.Fields.Add(newColumn, SPFieldType.Number, true);
SPFieldNumber fieldNum = (SPFieldNumber)web.Fields[newColumn];
fieldNum.Group = "Custom Columns";
fieldNum.Update(true);
}

if (!string.IsNullOrEmpty(newColumn))
{
//Get the field reference of new site column
SPFieldLink fieldLink = new SPFieldLink(web.Fields[newColumn]);

if (fieldLink != null)
{
try
{


//Add the site column to wiki content type
wikiContentType.FieldLinks.Add(fieldLink);
wikiContentType.Update(true);

}
catch (SPContentTypeSealedException ex)
{
}
catch (SPContentTypeReadOnlyException ctEx)
{
}
}

}

}

catch (SPException ex)
{
//Write to Logger
}


}
}


I hope that will be of some help to you. If you have any questions related to this concept then feel free to write to me.

No comments: