In our quest to handle some requirements to levelize the type of data users are adding to Sharepoint, we have come up with the idea that we need to add a choice field to all existing content types to categorize each item/document/discussion as to the level of data it contains at the item level. This should ensure that when a user creates a new custom list or new task etc this field will be required at first but could be turned off if needed. I was hoping that this could be done using a feature but a I am unable to determine what approach to take. Can the field be created programmatically and then somehow be added to all the content types or even the base content type. It seems that if you can add it to the 0x base content type it should work. Can this be done?
Why not create the field declaratively using a feature and then use the OM to add the field to your base content type? This is the approach I use often and it works fine.
Without having any code in front of me the general approach (this doesn't even rate as pseudo code!) would be:
- Create a feature to deploy the custom field
- On the feature activation you can run all your code to manipulate the base content type. I prefer not to manipulate system content types but that's just me and in your case I think you will need to.
- Get the base content type (0x) and custom field in question from the root SPWeb
- Add the field to the content type and update it. Remember to push the changes to all inheriting content types (everything in your case) by including the true flag when calling update.
The updated MSDN documentation on SPContentType has a good example of adding a field to a content type which is pretty similar to the code you will need. I think the code hasn't changed from 2007/WSS to 2010.
A couple of other questions...
- How many site collections will you need to do this to? You will need to activate this feature on every site collection that requires this functionality.
- You could consider building a feature stapler for your custom feature (assuming you use one) if you need to ensure all future sites will include this custom field/content type association.