开发者

How can I create this dynamic form?

Imagine a dropdown with 3 options:A,B,C and a div with the id of myform. When the user selects an option from the list, the div's content should be replaced by the form corresponding to the option. The thing is, the forms have nothing in common.

I was thinking of tackling this in the following way:

  • create a new controller FormCreator
  • create a new action build_form , which will take a type as a parameter (A/B/C)
  • create A.html.erb, B.html.erb and C.html.erb
  • depending on the type, I will render either A/B/C, with layout rendering disabled
  • use ajax to replace the content of the div with what the controller produced

Is there a better way of 开发者_Python百科doing this?


Here's guideline how I would do it: When some option is selected, for example A, with AJAX GET AController#new as JSON and return form rendered by erb. Than $('#myForm').html(withResponse). Main idea is that on select.change event you hit correct resource controller new action and replace div content with it's response.

Not complete answer but I hope it will give you an idea


Why not just hide the forms and reveal/hide them upon select list selection? It doesn't matter which controller or action you render the forms/select list from but they should probably post to their own controller and render only the previously posted form on validation failure.


Use a javascript select to call your AJAX controller with :onchange => remote_function(...)

In your controller =>

def FormCreator
  if params[:form] == 1
    render :update do |page|
      page.replace_html 'form_div', :partial => 'form_1'
      #make a file with just the form called _form_1.erb, this is called a partial 
      #because the file name starts with '_'
      #form_div is the id of the div that holds all 3 forms.
    end
  end
  #repeat for all forms
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜