Monday, June 11, 2012

Simple jquery form in cfwheels

Quite often I find myself needing a simple contact form in my main layout. I want the form available on all pages, and I don't want a page refresh when the form is submitted. It needs some simple validation too. So here's how I accomplish that. First I build a form in the layout.
The important parts of the form are:
  • The form and all elements have id's
  • There are labels after form fields that need validation
Make sure you include jquery in the head of your layout

Okay, so now let's add some jquery. We have a lot going on here so I tried to put good notes in the script. The important thing to remember here is that on the ajax submission it's very important that you append ?format=json on the end of the url.

Now let's enable json in cfwheels.

Just go to your contacts controller, and in your init function, add the provides function that our cfwheels developers have provided for us.

Now we'll use the renderWith() function when we create our method.

So all that remains is to handle the form submission in a controller action.

The action should be self explanatory. We are taking the form fields and saving them to the database and sending out an email if the save is successful. If you want to use wheels to validate your email field, you could put validation in the model, and then send back the error message.

Couple of notes. Doing it this way, I don't get isJSON to equal true. If I stringify the form fields, then isJSON equals true but then I can't figure out how to pull out my individual form fields. Also, make sure you turn off debugging in ColdFusion to see the response. Otherwise, you won't see it.

So anyway, this works for me for now. Would appreciate any comments or suggestions to make it easier!

No comments: