I’ve already done that. Everybody already done that. What nested forms are? It’s something which adds a new entry row, or removes one from a form, by clicking on + or - buttons (sometimes add or remove, YMMV). This all awesome, but with some tricks, it’s very easy to reproduce.
I’ll write every user-faced webpage in SproutCore sooner or later, it’s inevitable. However, old habits die hard, I still want to use Formtastic, and stuff Slim gives to me.
The first common denominator is the template usage. All righty then, let’s start somehow.
Interestingly, building your own handlebars.js is the hardest part (and if you’re already used to it, you can imagine the rest). First off, you need node.js and npm installed:
1 2 | |
I really hope you already use homebrew.
1 2 3 4 5 6 7 | |
Now wipe the sweat off of our forehead, and grab the newly created handlebars.js and handlebars.vm.js files, and copy them to our project’s lib/assets/javascripts directory (some of you might want to put them to vendor/assets/javascripts rightfully, I’m just lazy).
I’m not about to go into the details how to implement nested forms. That part hasn’t changed after all. You can get a very good insight on what it is and how to implement it watching Ryan Bates’ always amazing RailsCasts episode #196, and the following RailsCasts episode #197.
OK, 3rd party stuff is in place, let’s wire it into our app:
1 2 3 4 5 | |
Now handlebars.js is picked up. Let’s create a view:
1 2 3 4 5 6 7 8 9 10 11 | |
UPDATE: It looks like I forgot to show you my fragment. Here you are:
1 2 3 4 5 | |
As you can see, we put a rendered fields_for + render 'fragment' into a script field, but with a child index which can be replaced by handlebars. Remove links are not handled here, that part hasn’t changed. I suppose we might want to place more fragments into a page, and in that case we can hook to more DOM events:
1 2 3 4 5 6 7 8 9 10 11 12 | |
In this point if you look at the source it generates, you’ll see {{new_id}} gets replaced with __new_id__ at a couple of places. It’s because Formtastic naming settings replace everything which is not a letter, number, and some punctuation marks like dash, colon, or period. Let’s fix it:
1 2 3 4 5 6 | |
You can also fix in ActionView:
1 2 3 4 5 6 7 | |
You can always smooth off wrinkles, like hiding the add link if you don’t catch it:
1 2 | |
You use Modernizr, don’t you?
That’s it, enjoy your new templates put into a <script> tag, instead of a long onclick event with full of escaping.