Sunday, March 23, 2008

Sending forms the "old way" with Ext JS

The normal non-AJAX life-cycle of sending a form in Rails is the following:

  1. The user submits the form
  2. The browser is going to the form's action url
  3. The Rails action calls some model methods and sends a redirect to the users browser to a overview page or the created record for example
Here are some code snippets to solve this life-cycle with Ext JS and Rails:

// ext js form

var submit_button = new Ext.Button({
text: "Submit",
handler: function () {
form = this.ownerCt.getForm();
form_as_dom = form.getEl().dom;
form_as_dom.action = form.url;
form_as_dom.submit();
}
})

new Ext.form.FormPanel({
url: "<%= confirm_order_path(@order)%>",
standardSubmit: true, // doesn't do anything in ext js version 2.0.2
items: submit_button
})

# rails controller action

def confirm
order = Order.find params[:id]
order.confirm!
order.save # no error handling in this example

redirect_to order_path(order)
end


The special thing here is, that Ext JS doesn't really support the old-way of sending form data to the browser. But it's actually on their roadmap for the 2.1 release in this spring, which should be out very soon. The above code shows the current "work around" by using the actually DOM object of the form.

For completion and comparison, here the code for doing a form submit via AJAX.

// ext js form

var submit_button = new Ext.Button({
text: "Confirm",
handler: function () {
form = this.ownerCt.getForm()
form.submit({
success: function () {
this.setText("Unconfirm");
form.url = "<%= unconfirm_order_path(@order) %>";
},
scope: this
});
}
})

new Ext.form.FormPanel({
url: "<%= confirm_order_path(@order)%>",
standardSubmit: false, // false by default,
// but doesn't do anything in ext js version 2.0.2
items: submit_button
})

# rails controller action

def confirm
order = Order.find params[:id]
order.confirm!
order.save # no error handling in this example

render :text => "{ success: true }" # ext js converts
# responses to json by default, that means no need
# to send an explicit json header
end

4 comments:

Steffen Hiller said...

Sorry for the missing syntax highlighting! I'll be working on that. Any tipps for quick and easy syntax hightlighing on blogger blogs are welcome! Thanks.

Steffen Hiller said...

Done! Syntax Highlighting added via this cool javascript and css library: http://code.google.com/p/syntaxhighlighter/

colin said...
This comment has been removed by the author.
colin said...

Interesting. Don't know if you are familiar with the 'buttons' properties of formPanels. For more beauty, add the buttons there instead of in the form components:

http://paste2.org/p/297364

points of change:
1. Add buttons to like
{
xtype: 'form',
buttons: [super_button]
}

2. Reference the form from within the button as
handler: function (but, e) {
form = but.ownerCt.ownerCt.getForm();
}