Hierarchical forms with fleegix.form

2007-07-12 10:14:00

A common hack you see with both Ruby/Rails and PHP is the use of brackets in form element names (e.g., name="foo[bar]") to 'namespace' the form -- when values submitted from elements like this reach the server, they are converted into properties on an object.

Up to now, the toHash method in the fleegix.form module didn't do anything special form elements named using that hack.

This method converts form elements into a keyword/value JavaScript object. It does correctly stick the values for things like sets of checkboxes or a multi-select into an array, like you'd expect -- but it didn't do anything special with element names with brackets.

So, an element with name="zardoz[zed]" would end up in the converted object looking like convertedForm['zardoz[zed]']. Not really easy on the eyes, and probably not the intent when someone sets up those bracketed form-element names.

This past week Kevin Faulhaber was kind enough to pass along a toHash patch that converts those properly. So name="zardoz[consuela]" comes out correctly in the converted object as convertedForm['zardoz']['consuela'] -- or, since you don't have those gnarly brackets in the actual keyword, you can use normal dot-syntax -- convertedForm.zardoz.consuela.

Since toHash is the backbone of both the serialize and diff methods in the form module, it wasn't practical to make this the default behavior. So, to get this new behavior, just pass a second argument to the toHash method -- an options object, with the hierarchical property set to true:

var obj = fleegix.form.toHash(someForm, 
  { hierarchical: true });

Easy as pie.

I'm thinking now it would also be interesting to see if we could handle names with empty brackets (name="foo[]") like the PHP guys use to create arrays on the server.

This change is in the Fleegix.js trunk, and will be making it into the next release. For info on the other interesting stuff you can do with forms using Fleegix.js, check out the form module documentation.


This is the blog for Matthew Eernisse. I currently work at Yammer as a developer, working mostly with JavaScript. All opinions expressed here are my own, not my employer's.


Previous posts

All previous posts ยป

This blog is a GeddyJS application.