4

I'm using Alloy's Complex Form Example found here. The example he provides is a two level hierarchy and I'm trying to expand it to four.

He has javascript functions for adding nested items. How to expand for four nested layers?

'.add_nested_item': function(e){
   el = Event.findElement(e);
   template = eval(el.href.replace(/.*#/, ''))
   $(el.rel).insert({    
     bottom: replace_ids(template)
   });
 },
 '.add_nested_item_lvl2': function(e){
   el = Event.findElement(e);
   elements = el.rel.match(/(\w+)/g)
   parent = '.'+elements[0]
   child = '.'+elements[1]

   child_container = el.up(parent).down(child)    
   parent_object_id = el.up(parent).down('input').name.match(/.*\[(\d+)\]/)[1]

   template = eval(el.href.replace(/.*#/, ''))

   template = template.replace(/(attributes[_\]\[]+)\d+/g, "$1"+parent_object_id)

   // console.log(template)
    child_container.insert({     
     bottom: replace_ids(template)
    });
 }

3 Answers 3

1

I think it's a bit overloaded form if you need to handle three-level hierarchy. rethink your UI first.

Other than that - i don't think you need to build your associated objects in controller since example app builds them (if necessary) in views (app/views/projects/_form.erb):

<% @project.build_author unless @project.author %> <% project_form.fields_for :author do |author_form| %>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing out the app builds the objects. I updated my question.
1

Unfortunately this isn't really my area of expertise either…

Let me just state that I wouldn't use the example that's used in the complex-form-examples for so much nesting. Rather I'd build the required form inputs completely in JS with the regular DOM API. That should give you a much cleaner and leaner implementation and also better testable.

Cheers, Eloy

Comments

0

Ryan Bates has made this solution easy. Works with Rails 3 with helmerj's comment :)

http://railscasts.com/episodes/197-nested-model-form-part-2

helmerj's comment:

For the latest Rails3.rc ONe has to modify a single line:

in "module ApplicationHelper"

link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")

which removes the not needed h() function. Otherwise works like charm.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.