Monday, May 30, 2011

Setting default value to column in document library


One question I hear a lot from developers and system designers is “How can I set a default value to a column in a document library”?

The same goes for form libraries in SharePoint, Apparently SharePoint does not support default values for document libraries.

The first thing that comes to mind, as a solution for this predicament, is to build an event handler that will set a default value to the fields you need whenever a new item (document) is added to the library.

An experienced developer will tell you you should use the ItemAdding event, in order to set the default values to the field during the same update that the user initiated, and under his credentials.

To do that, you will have to use the properties.AfterProperties["FieldName"] = “Default Value”; to set your value.

But – you will be surprised that document libraries, although they do support the ItemAdding event, do not support properties.AfterProperties use. This collection is always empty and ignored in document libraries!

So, the only solution to set a default value to a field in a document library is by using the ItemAdded event.

During this event, the SPListItem was already created and is accessible through properties.ListItem property (unlike ItemAdding, that happens before the item was created).

So, setting the field should be rather easy: properties.ListItem[“FieldName”] = “Default value”;

But you will have to update the file manually yourself, since this happens after SharePoint has already processed the update of the item.

Naturally, you will not want to update the modified date/time, modified by user, and also you will not want to create a new version or emails alerts to be sent out.

So, instead of using the properties.ListItem.Update() method, use these lines of code:


Or the SharePoint 2010 code equivalent:

this.EventFiringEnabled = false;
this.EventFiringEnabled = true;

This will allow you to use custom code and programmatically set a default value to any SharePoint library column. Note that the same code should also work for SharePoint Lists, but this is supported through the UI or during the ItemAdding event.

For those of you who are not developers, or would rather a 3rd party solution, you can use KWizCom List Forms Extension solution version 2.1.60 or higher, where you can find a settings page that allows you to set advanced default values using this workaround.

Thanks, Shai.

No comments: