Tuesday, April 29, 2008

How to add a keymap to an existing FormPanel in ExtJS

Recently I needed to add a key map to an existing FormPanel in our ExtJS project. This sounded like a simple thing to do and in the end the code was simple, but it wasn't obvious how to do it. So I thought I would try to save you the pain I went through to figure it out.

In the JavaScript, you might have something like the following.

this.myForm = new Ext.form.FormPanel({ ...your parameters....});
this.myWindow = new Ext.Window({ ...your parameters....
items: this.myForm,
buttons: [{
text: 'Save',
handler: this.onSave.createDelegate(this)
},{
text: 'Cancel',
handler: this.onCancel.createDelegate(this)
}]
});

Now how do you go back and add a KeyMap after the fact.

The panel has to be rendered before you can add the KeyMap to it. To do that simple call the following.

this.myWindow.show();
this.myWindow.doLayout();

Now you can create the KeyMap.
new Ext.KeyMap(this.myForm.body, [{
key: Ext.EventObject.ESC,
fn: this.onCancel.createDelegate(this),
scope: this
},{
key: Ext.EventObject.ENTER,
fn: this.onSave.createDelegate(this),
scope: this
}]);

Now, the user can either click the cancel button or hit 'esc' to cancel what he was doing and to save what he was doing he can either press the save button or press the 'enter' key on the keyboard. I hope you find this helpful.

No comments: