Saturday, May 1, 2010

How to add Custom FIELDS/Columns to Contenttype/LIST programmatically , SHAREPOINT MOSS 2007

I know there are many people who are trying to find a way to add "Custom columns" to contenttypes/lists programmatically ...I spent reasonable time to figure it out so I would like to share it so it may be useful for others...

Ok, I had 2 cups of coffee and then sat in front of system to start my sharepoint deployment package. Everything is going cool until I try to add my custom column with custom fieldtype to my contenttype and attach that contenttype to list. My contenttype is not attached to list...it says "object reference not set to instance of the object".....bang........some thing wrong...!!

I spent some time then finally found solution !! solution is simple "Don't add custom fields to contenttype. use only that are supported by Sharepoint..." I know what you are thinking now....but hold on a second and let me explain it you clearly

1. First, Add the column to contenttype with the base Fieldtype of your custom fieldtype [every custom fieldtype must derive from sharepoint base fieldtype]
2. Attach contenttype, created in step 1, to your list [or multiple lists].  Here you won't see any error and all contenttypes are attached to Sharepoint Lists successfully. So far so good.
3. Now, change the base field type to your custom Field type and update it........then it updates all lists/contenttypes !!!!

I am providing sample code......for STEP 3 [I am assuming you did step 1 and step2]

private void UpdateFieldToCustomFieldType(Guid siteCollectionID, string customFieldType, string fieldName, bool hideField)

{
using (SPSite site = new SPSite(siteCollectionID))
{
using (SPWeb web = site.OpenWeb())
{
if (web.Fields.ContainsField(fieldName))
{
try
{
SPField customField = web.Fields.GetFieldByInternalName(fieldName);
customField.SchemaXml = customField.SchemaXml.Replace("Text", customFieldType);  //"Text" is basefieldtype of my customfieldtype which I used in step 1 to add to contenttype
customField.Group = "Custom Columns";
customField.Hidden = hideField;
customField.Update(true);   //this is important to propagate changes to all contenttypes/lists
web.Fields[customField.Id].Update();
}
catch (System.Exception ex)
{
throw (ex);
}
}

}}}



ENjoy...................

No comments:

Post a Comment