Friday 14 December 2007

Creating Custom Field Controls

Steps involved in creating a SharePoint Custom Field Control


1. Create your field definition in FLDTYPES_xxx.XML file, and add FieldEditorUserControl property to your custom field definition. Define fields for all custom properties of your custom field definition in PropertySchema section. Set Hidden attribute of all Field elements in PropertySchema section to True. Otherwise, fields will be rendered in user interface.

Example, a custom property definition looks like:

MyCustomField
My Custom Field
Text
MyFields.MyCustomField, MyFields, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f3bf8ec1b42660c3
TRUE
TRUE
/_controltemplates/MyCustomFieldControl.ascx





...




2. Create .ascx control file in TEMPLATE\CONTROLTEMPLATES directory. In my sample it’s MyCustomFieldControl.ascx and is very simple:














This control has only one drop-down control. The idea is, that user can select some value from drop-down, and it’ll be stored in custom property of our custom field.

3. Create .NET classes for your custom field type and user control. For custom field type:

As you can see, we’ve created string attribute and property, for my field type’s CustomProperty. In Init method, we populate it with stored custom property value. Finally, we overridden Update method, to save modified custom property values to the field.


The code for my user control:
public class SelectMyCustomProperty : UserControl, IFieldEditor
{
/* ... */
public void OnSaveChange(SPField field, bool isNew)
{
string value = this.ctlMyCustomProperty.SelectedValue;
MyCustomField myField = field as MyCustomField;
if(isNew)
myField.UpdateMyCustomProperty(value);
else
myField.MyCustomProperty = value;
}
/* ... */
}
As described in SDK user control class should implement IFieldEditor interface. It has 2 methods and 1 property:
InitializeWithField – is called, when control is initialized;
OnSaveChanged – called, when user clicks OK button in field properties window;
DisplayAsNewSection – true if control should be displayed as new section in field properties form.
In CreateChildControls we just populate our drop-down list with some values.

The crucial point here is, not to try setting values directly to custom properties in OnSaveChange (like, myField.SetCustomProperty(“MyCustomProperty”, value)). Even if you call myField.Update() afterwards, the value won’t be saved! More precisely, it will be saved, but then it will be overwritten by current custom property value. Looks like SharePoint calls OnSaveChange in our control, then continues to update values of custom properties from other sources (and our Hidden field in PropertySchema section is one of them), and finally calls field’s Update method. That’s why we need to override Update method in our custom field class and set custom property values there – at that point SharePoint has done his job, and won’t change any property values.