Displaying error messages in Extjs is not a terribly difficult task once you get the hang of the syntax and standardize all of your try / catch backend code. This post will present various ways to handle errors that may happen in your application so that you may provide users with a more meaningful message, and in turn help save some time when debugging. This is in fact an enhanced version of the Ext form example, and dives into areas where the example leaves off, the actual form is posted below so go ahead have a try, and look at the code if you would like before reading the explanation below. Once you download Ext you should have a folder called /examples/ in that folder you should have another folder called /form/ and finally in that folder open the file contact-form.js (here’s the link in case you have not downloaded the extjs library yet).
These examples are great but they all leave out one thing, data interaction between the form and the ‘back end’ of your web application. The block of code between lines 82 – 90 spell it out, and this will be the block that we modify to present us with a dummy response from the server.
handler: function() {
if (this.up('form').getForm().isValid()) {
// In a real application, this would submit the form to the configured url
// this.up('form').getForm().submit();
this.up('form').getForm().reset();
this.up('window').hide();
Ext.MessageBox.alert('Thank you!', 'Your inquiry has been sent. We will respond as soon as possible.');
}
}
Since the code is written in extjs4 some of the syntax is new, for example, this.up(‘form’).getForm().isValid() looks a little different than the familiar Ext.getCmp(‘id’).getForm().isValid(), and you are free to use either one, the up abstract component walks up the ownerCt axis and returns the ancestor container with the parameter as the simple selector, in this instance the ‘form’ selector returns the form container. If we had specified an id in the form we could have used the following code to achieve the same result, Ext.getCmp(‘the_form’).getForm().isValid(). It pays to take a look at the abstract components and understand where and when you can use them, a full list can be found here in the Sencha documentation: http://docs.sencha.com/ext-js/4-0/#/api/Ext.AbstractComponent.
Error handling takes place in two areas in a web application, first, at the client side, which is the local browser, and finally, at the server side, which means that the data has been passed to the server and you are validating it then passing the results of the validation back to the client side browser. As a general rule you will want to do as much validation as possible at the client side before you send the code over to the server, this will save you in processing time and will speed up your applications, as well as prevent potential security threats to enter your server via your web forms.
The Client Side
In extjs 4 Sencha has made it easier to add on custom alert boxes when the client side validation fails. I know the underlined form elements clad in wavy red squiggles should be an indication that you have left something out or done something wrong, however, in the real world where your application is bound to wind up there are users who overlook this subtle hint. A modal dialog box clearly stating the obvious can be achieved using the code below.
Before:
We wrapped the form submit with the following if statement, preventing submission if the client side validation failed.
if (this.up('form').getForm().isValid()) {
…
// Our form submit stuff
}
Now, we have the built in failureType property for the form action we can omit the if … then statement above and just insert the following code in out failure function of the form handler.
After:
if (action.failureType === Ext.form.action.Action.CLIENT_INVALID) {
Ext.Msg.show({
title:'Error',
msg: 'Please complete the fields that are outlined in red.,
icon: Ext.Msg.ERROR,
buttons: Ext.Msg.OK
});
}
This will abort the form submission, and give the user a nice visual warning in the form a of an error message that they will have to click on before correcting their form data.
The Server Side – Timeouts and other server side errors (non-application driven)
A great improvement over earlier versions of extjs is the fact that there is now a built in way to handle timeouts and server side errors so that your code is not left in a suspended state. Just as the client side example above, we will insert a if .. then block in the failure function of the handler, this time concentrating on the failureType Ext.form.action.Action.CONNECT_FAILURE.
if (action.failureType === Ext.form.action.Action.CONNECT_FAILURE) {
Ext.Msg.alert('Error', 'Status:'+action.response.status+': '+ action.response.statusText);
}
The result is below where 404 is the server side status and Not Found is the response text, this could be 503 Out of Resources, 500 Server Error, and the list goes on. (http://www.html-faq.com/serverbasics/?http )
Server Side validation
Ok there will be times when you absolutely have to validate data on the server side, be it a lookup against another table, an elaborate cross reference, whatever the reason, you will have to do it. The JSON below will indicate that there has been a server side failure.
{success: false}
You could stop with the simple statement above and give the user a generic error message, but since you are taking the time to read this far you are probably not that type of programmer and you want to give the user a little more information. In the example code we have the following fields, firstName, middleInitial, lastName, emailAddress, subjectField, and messageField. We can assume that any of these fields could hold invalid data, and there could be an infinite number of reasons why, now the task is to get the fields to the front end or client side and give the user a reason why the data was not acceptable. The JSON that you will have to return from the server to accomplish this consists of two parts, first, success must equal false, and second you should follow that with an object where the field name or id is followed by the error message that you would like to display, an example for the lastName field in our example form is below.
{ success: false, errors: { lastName: "Client not found" }}
The final piece is to put the code in place in the failure function of the action handler that will show the user the fields and messages you passed back with the JSON above. The code to do this is below.
if (action.failureType === Ext.form.action.Action.SERVER_INVALID){
// server responded with success = false
form.markInvalid(action.result.errors);
}
You should see something like this.
I have attached the source code to the modified example that you find in its entirety here … The only things you have to remember is that if you would like to turn off the client side validation you must do so by setting the clientValidation property to false, and that you can get pretty specific with the client side validation by using the vtype property (http://docs.sencha.com/ext-js/4-0/#/api/Ext.form.field.VTypes ).



