Writing custom value handlers - Demonstration

In the following example, the ZipCodeValueHandler is created. The handler is created for the ZipCodeControl. This control accepts a zip code of the following format (two digits)-(three digits). There are separate textboxes for two digits and for three digits. The dash between the digits is added automatically.

 
Address
Street
100
House Number
10
Flat Number
10
Post Code -
Post
50
City
50
XML output

        
Writing custom value handlers - Description

MForm is not limited to using standard value handlers. Any webcontrol that provides any textual input can be used, if it has an appropriate value handler written.

Writing custom value handlers is pretty straightforward. It needs writing a little bit of server-side and a little bit of client-side code.

Implementing value handler on the server side

Any value handler must inherit from the ControlValueHandler<TControl>, where TControl must inherit from the Control.

There are several more specific overrides of the ControlValueHandler that are available to the developer:

  • UserControlValueHandler<TUserControl> where TUserControl must inherit from UserControl
  • StandardWebControlValueHandler<TWebControl> where TWebControl must inherit from WebControl
  • ListControlValueHandler<TListControl> where TListControl must inherit from ListControl

Each of these handlers provides a Control property, that is of the generic type.

Each implementation of the value handler on the server side, must implement agetter and setter of the Value property. This implementation usually looks like this:

public override string Value
{
    get
    {
        return Control.Value;
    }

    set
    {
        Control.Value = value;
    }
}

and it depends on the Control's characteristics (remember that the Control type is generic).

Implementing value handler on the client side

The value handler's client side class must also inherit from the BM.ValueHandler javascript class. This can be done with the following code:

(SomeCustomValueHandler).registerClass("(SomeCustomValueHandler)", BM.ValueHandler);

Besides that, the value handler must register itself for the value handler's factory (the key in this registration is the control's type name):

BM.ValueHandler['(server control type name)'] = (SomeCustomValueHandler);

With the above done, implementing two methods is left:

  • setControlValue method, which sets the control value in javascript
  • getControlValue method, which gets the value text from the control

The HTML DOM element that is correspondent to the server-side LeafItem is avaliable in the value handler class as the this.getLeafNode().

The implementation of the client side should look like this:

	(SomeCustomValueHandler) = function(leafItem) {
		(SomeCustomValueHandler).initializeBase(this, [leafItem]);
	}

	(SomeCustomValueHandler).prototype = {
		getControlValue: function() {
			...
		},

		setControlValue: function(value) {
			...
		}
	}