How to implement dynamic content render when form submited (newbie ask) - ruby-on-rails

I am developing rails 3 application (I am newbie in Rails).
Currently, I have a form (use "form_for") for submit, there is a div area under the form. What I want is when user click the 'submit' button of the form, based on the user input data in the form, application will first go to the database to retrieve and organize some data, then the div area under the form will be rendered with the organized data.
That's the content of the div area is rendered dynamically based on user's input in the form, and the div render happens when user click "submit" form button .
The index.html.haml:
=form_for :myform do |form|
= ...
= ...
=form.submit "submit"
%div.result
/dynamic content to be rendered here, when user submit the form
=render :partial 'result'
I think my form submission should first go to run a controller method to organize the data from Database, and what's the next step I should do? As you noticed from the above code, I have a partial there under div, I would like to update the 'result' partial when user submit form, but how to implement this??

examples of how you may update your page in response to ajax polling
#some_controller.rb
def your_action
end
# javascript erb file. views/some_controller/your_action.js.erb
$('div.result').html('<%= escape_javascript(render :partial => 'your_action' -%>');
# _your_action.html.haml
= #dynamic_data

Rails scaffolding will give you a clue on how to do this. Just include the form as partial as well in your show template. Something like this:
index.html.haml (or new.htm.haml):
= render 'new'
show.html.haml:
= render 'new'
# display your #object

Related

How to pass object to partial using controller?

I've been trying to pass my Product object to my rendered partial but no matter what I try it doesn't work. The home page has a quick view button that pops a modal (the partial) and I want to pass the correct product to it.
Route
get 'shop-product-ajax-page', to: "pages#shop_product_ajax_page"
Home Page (shortened to only the link for brevity)
<% #products.each do |product| %>
<%= link_to "Quick View", shop_product_ajax_page_path, :data => {:lightbox => 'ajax'} %>
<% end %>
Controller Action
def shop_product_ajax_page
render :partial => 'pages/shop_product_ajax_page', :layout => false
end
Right now, the button works and displays the HTML in the modal. I want to be able to populate the correct product information for whatever Quick View product is selected.
The problem is that the link is making a completely separate AJAX request, it's hitting the server separately, so the Ruby context you expect (variables etc) isn't available in that new request.
Two choices:
Don't make an AJAX request but render the lightbox as part of the page. You could hide it using display: none or similar, then use Javascript to display it when the link is clicked.
Make the request the way you currently are, but pass in the same parameters that your current controller action is using to get #products and in shop_product_ajax_page do the same thing to hit the database and get the products.
The second choice might be easier without messing with JS. It would be something like:
def shop_product_ajax_page
#products = get_products_from_params(params)
render :partial => 'pages/shop_product_ajax_page', :layout => false
end
private
def get_products_from_params(params)
Product.find(params["product_ids"]) # or whatever you're currently doing
end

Render html.erb (not partial) in other html.erb

I'm quite new to Rails and trying to make app with Foundation framework. The problem is with modal window.
I have an index.html.erb file in views/users folder, generated by scaffold.
Also there is a new.html.erb file in the same folder.
I want to open ../users/new link in modal window on index page.
I used examples in Reveal (Foundation Documentation), put new.html.erb file content in:
<div id="myModal" class="reveal-modal">
.
.
</div>
Also, add to New User link "href" attribute.
<%= link_to 'New User', new_user_path, 'data-reveal-id' => 'myModal' %>
as was described here.
Now I need to render new.html.erb in index.html.erb, cause I need this code just before /body tag, as described in Foundation Docs.
I've tried to render it as partial, but it doesn't work.
Is there any way to do it, without double new.html.erb as _new.html.erb and inserting it as partial in index.html.erb?
I don't think, that RoR with all there's "Write less code!" stuff, doesn't have the way for do it without code duplicating.
Thanks!
You cannot use the new action as it is, though you can put your form in one partial, use across new and your action to generate form in modal.
On Page load you can use _form partial.
You can use ajax to generate the form for the model if you want on fly, this can be use for edit as well as new.
Step1 :link_to "your action path", remote: true, id: "abc"
Step2: your action path should return html of the form using render to string
Step3: now using jquery ajax success of $("#abc") replace your model inner content with the form.
And use the create action for both ajax and postback.
Code is DRY.
Let me know if you need the code.
Thanks

Add section to form by rendering a partial when link is clicked

UPDATE 3:
For anyone who reads this, this is why it wasn't working as expected in update 2 below: Passing a local variable to a partial that is rendered after the view has already loaded
If anyone knows how to solve that issue, let me know please.
UPDATE 2:
I updated the javascript with the quotation marks and it partially works...in the sense that the javascript is now functional and it will cause a string of text to appear on the page when I click the link as long as I have the partial only contain a string of text. However, when the partial includes the form fields code, something goes wrong.
If I just paste the following render code directly into the form in the new.html.erb view, it produces a new form section properly.
<%= render "add_round", f: f %>
However, when I try to include similar code in comps_helper.rb and then reference it from the link_to, it does not work:
In comps_helper.rb:
def addRound(f)
render "add_round", f: f
end
In new.html.erb:
<%= link_to "render it!", addRoundLink_path, remote: true %>
<div id="some_id"></div>
And I changed addRoundLink.js.erb to:
$("#some_id").html("<%=j addRound(f) %>"); #Is this the correct change to have made here?
Clicking the link_to link does nothing in that case.
Any thoughts?
UPDATED CODE:
Thanks for the reply. I've made the following changes and it still does not appear to be working. The link appears at the bottom of the form but when clicked does not change anything. What am I missing?
routes.rb:
resources :comps
match '/new_competition', :to => "comps#new"
get "/addRoundLink" => "comps#addRoundLink", :as => :addRoundLink
Note: I included the other 2 lines related to "comps" just in case those would cause an issue.
comps_controller.rb:
def addRoundLink
respond_to do |format|
format.js
end
end
comps_helper.rb:
def addRound
render "add_round"
end
addRoundLink.js.erb:
$("#some_id").html(<%=j addRound %>);
comps/new.html.erb:
<%= link_to "render it!", addRoundLink_path, remote: true %>
<div id="some_id"></div>
Thanks.
ORIGINAL QUESTION
First off, I'm new to rails. I've read and tried many solutions to similar questions but nothing has worked so far.
I created a form with rails form_for and fields_for. The form creates a new competition (comp). The competition has many rounds. The top half of the form (the form_for section) accepts the details about the competition as inputs and the bottom half of the form accepts details about each round (the fields_for section). The form works perfectly in this basic format.
I took all the code that is in the fields_for section and put it into a partial. My plan was to then create a "add new round" link to the bottom of the form that would simply display the partial above the link each time the link is pressed. This would add a new section to the form for a new round and allow the user to input as many rounds as they'd like. This is the part that I am struggling to make work.
I added this code to my comps_helper:
def addNewRound
render "add_round"
end
This renders the file /views/comps/_add_round.html.erb.
My question is: how do I get this to render in the form when a link is clicked. As far as I can get with the research I have done is:
<%= link_to "Add new round", { }, :remote => true %>
I don't exactly know what is supposed to go in the {} that will execute the addNewRound method. And I don't know what, if anything, I need to add to my comps_controller file.
Thanks so much for the help.
You have to create an action in your controller
app/controllers/some_controller.rb
def hello
respond_to do |format|
format.js
end
end
and define a route to this action.
routes.rb
get "/hello" => "some#hello", :as => :hello
then create a link to this action like that:
<%= link_to "render it!", hello_path, remote: true %>
<div id="some_id"></div>
When you click this link it will find its way to your action and respond with js(javascript) because we told action to respond with only js.
At the end render the partial to anywhere you want in your view(*in this example to the some_id div*)
app/views/some/hello.js.erb
$("#some_id").html("<%=j addNewRound %>");
WARNING: Creating dynamic forms is a pain. You will face a lot of problems (like setting different ids for new form elements etc...). I highly recommend you to use ryan bates nested_form gem

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 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

Posting a form through popup in Rails

I have a model called Details, and two controller methods new and create. New method displays a form to create Details (in new.html.erb), which gets posted to the Create method that saves it. (when it succesffully saves, it it renders the new.html.erb file with the details.) This works as expected.
Now i want a separate page with a link to fill in these details. I want the click to do the intended work through a popup, example redbox. When you click on that link, a popup should show the form, whose submit should post the form, and if it is successfully done, then refresh the original page. If the post is unsaved, then the same form should show the errors. What do i need to do to make it work in Ror? I guess i need some stuff to go in new.js.rjs and maybe create.js.rjs, but i can't really figure out what to put in those files.
Redbox updates the page's dom to add a div at the end of it. So your form is a part of the main page.
So if you add a form tag in this redbox, all your page will be reloaded as there's only one.
So you add anywhere in your page (preferably at the end) :
<div id="redbox" style="display: none;">
<%= form_for #details do %>
# Whatever form fields you want here
<% end -%>
</div>
You do a link that'll open the redbox :
<%= link_to_redbox 'Open The Details Form', 'redbox' %>
This will display your redbox with your form.
And as it is the same page, not a new windows, when you'll validate your form, it'll reload the all of it.
I used a link_to_remote_redbox for this, which on clicking, fetches the form rendered by the new method call in a popup widnow. it submits to the create function and it is now working. actually i had previously made it work without ajax and i was having difficulty in making it work with ajax. the problem was solved once i made separate partials for ajax calls, and doing:
respond_to do |format|
format.js { render :template => 'detail/ajax_template'}
...
end
I provided different templates for both create and new method calls, used the :html => {:id => 'some-id'} in form and the :update => {:some-id} to replace the form with the message that it worked correctly.
So I didnt know that i needed separate templates for the different styles of forms, and that i needed to use the :update option to replace the form when i asked the above question.

Resources