Basic tech stuff

Programming and Linux administration

Rails fix for nested forms

Posted by Daniel Brahneborg on 2007 May 26

In Rails there is a nice helper function button_to. It uses Javascript in the onclick event to create a new form which is immediately submitted. Perfect when a button is all you really need.

Or so I thought, until I installed the HTML Validator extension to Firefox. It has a super strict HTML parser that tells you when something is wrong with your code. This way there is a much greater chance that the pages will look the way you want in as many browsers as possible.

So what’s the problem? Well, I had a form surrounding a table. The form was really only for the last row in the table, but since a form must either be outside of the table tag or within a td, the only option was to let the form surround the table. On all rows but the one with the real form fields, I wanted that new button. When the new form was created, the HTML validator became a bit upset about the fact that a new form was created within an existing form. This isn’t allowed. (There are sure a lot of things that aren’t allowed in HTML.)

The solution was to patch actionpack/lib/action_view/helpers/url_helper.rb around line 367, changing

    "this.body.appendChild(f); f.method = 'POST'; f.action = this.href;"

into

    "document.body.appendChild(f); f.method = 'POST'; f.action = this.href;"

This makes the new form live as a child to the top level body tag instead. Now the validator was happy again.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: