Friday, February 26, 2010

Adding a "submit on enter" in ExtJS formpanels.

I had to retrospectively setup "submit on enter" to some existing ExtJS forms.
Googling only turned up some fairly unappetizing solutions.
Here's a way using defaults. Just change the getCmp or parametize it if you want, I've left it as a constant for illustration purposes.
Add this to your FormPanel constructor and all your fields will get "submit-on-enter".
If you only want 1 field to have it then just add everything inside the defaults to that 1 field.

defaults:{
  enableKeyEvents:true,
  listeners:{
    specialKey: function(field, el)
    {
      if(el.getKey() == Ext.EventObject.ENTER)
      {
        Ext.getCmp('address-search-button').fireEvent('click');
      }
    }
  }
}

5 comments:

macint0sh said...

This solution don't work for me.
But i find something like this:
Ext.getCmp('submit').handler.call(Ext.getCmp('submit').scope);
And this working like a charm :)

macint0sh said...

Forgot!
Change this code:
Ext.getCmp('address-search-button').fireEvent('click');
for this:
Ext.getCmp('submit').handler.call(Ext.getCmp('submit').scope);

akm said...

Do you have a submit button in your form?

If you don't have a button then obviously you need to do something different as you found out.

But, then you probably wouldn't need to use the brute-force of using defaults on a form either, which I had to do because there were already a ton of forms that needed this type of thing added.

frrogoy said...

I couldn't get either way to work as written, but added the following to the form. I'm on Extjs 3.2.
keys: [{
key: [Ext.EventObject.ENTER], handler: function() {
Ext.getCmp('btnLogin').handler.call(Ext.getCmp('btnLogin').scope);
}
}]

James said...

Another hint is to call el.stopEvent() in the if block where the enter key is pressed. This prevents IE from sounding the default error sound when submitting the form with the Enter key.