Thursday, June 3, 2010

Progressive Enhancement with extjs

Been working with extjs recently trying to implement progressive enhancement of forms and such like. Unlike some libraries, extjs assumes that you will build the entire page programmatically in JavaScript (just like using Google Web Toolkit). A bit like the old Swing and MFC way of doing things - but a lot simpler.

However it is also possible with extjs to enhance an existing HTML element with JavaScript enabled goodness.

First it is necessary to enhance the form itself. If the form id is "dataForm" then this is the required code:

var form = new Ext.form.BasicForm("dataForm", {
standardSubmit: true
});

You can't apply a FormPanel in this way, but a BasicForm is fine. By default extjs expects an AJAX based form submission, so the standardSubmit property enables a normal form submission.

Next we must enhance and add the fields to the form. For example, to take a form input field and restrict it to numeric only input looks like this:
  <input id="percent" name="percentage">

// widgit configuration properties
var config= {
applyTo: "percent",
invalidText: "A value between 0 and 100 is expected",
allowBlank: false,
blankText: "A percentage is required",
minValue: 0,
maxValue: 100
};

var widget = new Ext.form.NumberField(config);
form.add(widget);
Finally it is necessary to prevent the form being submitted if the content is invalid. We do this by overriding the submit method of the form.
  var f = form.dom;   // The actual HTML form element
f.onsubmit = function() {
return form.isValid();
}