Rails turbolinks break submit remote form - ruby-on-rails

I'm having a rather weird problem using Rails 4, Turbolinks and a remote form. I have a form looking like:
<%= form_for [object], remote: true do |f| %>
<td><%= f.text_field :name, class: 'form-control' %></td>
<td><%= f.email_field :email, class: 'form-control' %></td>
<td><%= f.submit button_name, class: 'btn btn-sm btn-primary' %></td>
<% end %>
This form adds (creates) a new object. It does however not always work:
When I load the page directly using the URL or a refresh; it works
When I navigate from my app to this page; it fails
When disabling Turbolinks for this link, the page worked perfectly.
I have two questions:
Why doesn't this work? Is this because the remote handlers aren't attached to the button because of a JQuery/Turbolinks problem?
How can I work around this problem?
Thanks in advance.
Solution
Thanks to #rich-peck, the solution was to add a piece of javascript that manually submits the form upon clicking the button:
<%= javascript_tag do %>
var id = "#<%= dom_id(f.object) %>";
var inputs = $(id).parent().find('input');
console.log(inputs);
$(id).parent().find('button').on('click', function(e) {
e.preventDefault();
$(id).append(inputs.clone());
$(id).submit();
});
<% end %>
This code adds javascript to the form table row, getting the inputs, appending them to the ID and submitting the form. The preventDefault(); prevents the query from getting sent twice when the page is refreshed and the form actually works.

Turbolinks
As mentioned, the problem with Turbolinks is that it reloads the <body> part of the DOM with an ajax call - meaning JS is not reloaded, as it's in the head
The typical way around this issue is to delegate your JS from the document, like this:
$(document).on("click", "#your_element", function() {
//your code here
});
Because document is always going to be present, it will trigger the JS continuously
Remote
With your issue, it's slightly more tricky
The problem is you're relying on the JQuery UJS (unobtrusive JavaScript) engine of Rails, which is difficult to remedy on its own
We've never had this issue & we use Turbolinks all the time - so I suppose the problem could be with how you're constructing your form / handling the request. This GitHub seemed to recreate the issue, and it was to do with the table
Maybe you could try:
<%= form_for [object], remote: true do |f| %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.submit button_name, class: 'btn btn-sm btn-primary' %>
<% end %>

Turbolinks don't fully reload your page, but only part of it. This is what makes them so fast, however if you have JavaScript requiring a full page reload you will run into trouble. The reason it does work with a refresh is because now you force the page to fully reload.
Edit: This gem might be worth trying out: https://github.com/kossnocorp/jquery.turbolinks
For a little bit of extra information about the inner workings of turbolinks: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks
Or: https://github.com/rails/turbolinks
P.s. Also make sure the javascript_include_tag is within the head tag (and not in the body)

Related

form_for was put inside fields_for

I'm having a problem with form_for and fields_for.
So, my problem is:
I had a form_for, and inside this form_for, I use a fields_for. Inside this fields_for, I use a form_tag (i used ajax for this form_tag).
But when I view the generated HTML, it didn't display form_tag, it only display form_for. And I didn't understand why.
Please explain for me, why it didn't display form_tag.
Here is my form_for:
<div class="row">
<%= form_for #real_estate, url: admin_real_estate_update_path do |f| %>
<%= f.fields_for(:client) do |client| %>
<%= text_field :real_estate, :assessment_start_at, value: #real_estate.assessment_start_at %>
<%= render partial: "admin/real_estate/form/assessment", locals: {real_estate_id: #real_estate.id} %>
<% end %>
<%= f.submit "Submut", class: "btn btn-primary"%>
<% end %>
</div>
Here is my form_for which i put inside fields_for:
<%= form_tag admin_search_assessment_path(real_estate_id), method: :post, remote: true do %>
<%= text_field_tag :company_name, params[:company_name] %>
<%= submit_tag "Submit" %>
<% end %>
And i tried to add <form></form> follow as:
<div class="row">
<%= form_for #real_estate, url: admin_real_estate_update_path do |f| %>
<form></form>
<%= f.fields_for(:client) do |client| %>
<%= text_field :real_estate, :assessment_start_at, value: #real_estate.assessment_start_at %>
<%= render partial: "admin/real_estate/form/assessment", locals: {real_estate_id: #real_estate.id} %>
<% end %>
<%= f.submit "Submut", class: "btn btn-primary"%>
<% end %>
</div>
And form_tag was display, but form_for didn't display.
Update:
So, i used $("form_2").submit(function() {....}); to solve this problem.
Actually, i still want to use form-nested.
Inside this fields_for, I use a form_tag (i used ajax for this form_tag)
N'est pas possible, mon ami.
--
Here's how it works...
form_for and form_tag both generate pure HTML forms:
<form action="/action" method="POST">
</form>
Many people get confused about how Rails works - it's really quite simple. Rails employs "helper" methods to generate pure HTML which your browser can read.
Browsers only understand HTML/CSS at the moment. Thus, whenever you send a request to Rails - it has to return that data, otherwise a "web page" simply wouldn't be able to be processed.
Thus, when you ask whether you can nest forms, you have to abide by how the forms work in pure HTML (spec):
Note you are not allowed to nest FORM elements!
HTML fill-out forms can be used for questionaires, hotel reservations,
order forms, data entry and a wide variety of other applications. The
form is specified as part of an HTML document. The user fills in the
form and then submits it. The user agent then sends the form's
contents as designated by the FORM element. Typically, this is to an
HTTP server, but you can also email form contents for asynchronous
processing.
In short, it means that everything within a <form> tag is counted as a form by HTTP. This means that if you have another <form> tag, it's going to cause an error, preventing either from working.
You know this already (otherwise you wouldn't have mentioned ajax).
Your main problem is the use of <form></form> inside your current <form> object. This will confuse HTML profusely, and thus I would recommend replicating the submission of a form, without the <form> object itself:
#app/views/admin/real_estate/form/assessment.html.erb
<%= text_field_tag "[company_name]", params[:company_name], id: real_estate_id %>
<%= button_tag "Submit", type: "button" , data: { id: real_estate_id } %>
#app/assets/javascripts/application.js
$(document).on("click", "button", function(e){
e.preventDefault();
var real_estate_id = $(this).data("id");
$.ajax({
url: "path/to/real/estate/form/assessment/" + $(this).data("id")),
data: {company_name: $("input[type=text]#" + real_estate_id).val()}
success: function(data) {
//do something on success
},
error: function(data) {
//do something on error
}
});
});
This code will still output what you need.
The difference will be two-fold:
The user will experience the same functionality (the input will still be present)
The embedded form will be passed to the main "form" submit, but will not be passed through your strong params method (making it
invisible to your controller)
In effect, you're replicating the functionality of an HTML form through Ajax. Whilst I still wouldn't do it this way, it will give you the functionality you require.

How and when does rails load a gem library?

I have a gem installed : http://toopay.github.io/bootstrap-markdown/
This library is supposedd to turn a textarea element into a stylized mardown editor.
To do this I used the following code:
<div class="well col-md-10 col-md-offset-1">
<%= form_for(:post, :url => {:action => 'create'}) do |f| %>
<%= f.text_field(:title, class: 'form-control')%>
<%= f.text_field(:description, class: 'form-control')%>
<%= f.text_area(:content, rows: 15, "data-provide" => "markdown")%>
<%= f.button "Submit", type: 'submit', class: 'btn col-md-4 col-md-offset-4 btn-large btn-success'%>
<% end %>
</div>
Initially I put this code on my root page and it worked perfectly.
I then created a new controller and moved it to a different view. I was accessing that view by manually typing the url in the browser: localhost:3000/controller/view and the page loaded perfectly.
Result here:
However, when I access the page through a link on a different page, the form was not stylized.
Result:
The odd thing is that if I reload the page it applies all the changes.
I made a temporary ugly hack that reloads the page one on every access:
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
But there must be a decent explanation for what is going on.
I went through the library itself and added some console.log statements.
It seems that the library is loaded and initialisez on the home page but when I click the link it does not run anything anymore.
I am trying really hard to understand if this is a rails problem or a library one.
You have an issue with Turbolinks. First, remove data-provide attribute to initialize input yourself and add a class, like markdown-editor.
<%= f.text_area(:content, rows: 15, class: "markdown-editor")%>
Second, add a Javascript initializer:
$(document).on('ready page:load', function(){
$(".markdown-editor").markdown()
});
Then it will be initialized on each page load.

Submit a form after an event. Rails

Here is the part of code I am working on.
<td class= "block" id=<%= dom_id(Block.find(block.id)) %> colspan=2>
<%= form_for block do |f| %>
<%= f.text_area :content, :size => "5x4" %>
<%= f.hidden_field :id_case %>
<%= f.hidden_field :canvas_id %>
<%= f.submit "Submit", class: "save" %>
<% end %>
</td>
I would like to add another form under this one, still in the "td". And I would like this one to be submitted when I drag a special element in the (which is droppable)
I figured out that forms can have the data-remote attribut, but I didn't really get how we have to use it. Is this attribute made for execute javascript after we've submitted the form or is it a helper that submits the form after a special element ?
If this is the second case, it really fits with my idea but I really didn't understand how to use it.
Thanks for your help
I am not sure exactly what you want to know here, but a form with data-remote="true" means that it will be submitted by Ajax rather than a 'normal' submit. You can add remote: true to your form like this:
<%= form_for(#post, remote: true) do |f| %>
...
<% end %>
The resulting form will have a data-remote="true".
To submit a form by Ajax after you have dropped your element you can do the following using jQuery:
$("#your-droppable-element").droppable({
drop: function( event, ui ) {
$('#your-form').submit();
}
});
I hope that helped :)

nested_form displays a partial twice

I'm using the gem nested_form in a Rails 3.1 application. The problem is that when I click on the link generated by "link_to_add", it displays the partial twice, whereas it should display it just once. There you go some code:
Form:
<%= nested_form_for #product, :html => {:multipart => true} do |f| %>
<%= f.fields_for :safety_info_files %>
# adds a link for displaying the template
<%= f.link_to_add "Add file", :safety_info_files %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Template:
<div class="fields">
<%= f.link_to_remove "remove" %><br />
<%= f.label :doc, "File" %>
<%= f.file_field :doc %><br />
</div>
Did anybody else have the same problem?
EDIT:
Silly mistake, silly me. Sorry if I made some of you wasting time, the problem was that I was loading "nested_form.js" twice, so it called the function that appended the partial the same number of times.
Sorry again.
Silly mistake, silly me. Sorry if I made some of you wasting time, the problem was that I was loading "nested_form.js" twice, so it called the function that appended the partial the same number of times.
For those having this issue using rails 4 / turbolinks and not finding nested_form.js included twice, try removing turbolinks from application.js. Once I did this and bounced the server this issue was resolved.
Credit here: https://github.com/ryanb/nested_form/issues/307
I was facing same issue.
I had included nested_form.js in my application layout file.
And I haven't changed my app/assets/javascripts/application.js file, it is as it is, when it was created at time of creating rails application.
When I removed entry from my application layout, problem was solved.

Rails 3 submit form with link

How I can submit form with link on correct rails 3 format?
Thanks.
<%= form_for #post do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %>
<p><%= f.submit %></p>
<% end %>
My code sample.
For people who came here via Google, I have an improvement on Zequez's answer. Instead of the method that he gives, add this method to the application helper instead:
def link_to_submit(*args, &block)
link_to_function (block_given? ? capture(&block) : args[0]), "$(this).closest('form').submit()", args.extract_options!
end
Then, as Zequez stated, for simple links you can just do this in your view:
<%= link_to_submit 'Submit Form' %>
...and for more complicated buttons you can pass HTML options and a block to be used inside the link. If you use Twitter Bootstrap, for example, this lets you add CSS classes, formatting and icons:
<%= link_to_submit( class: 'btn btn-primary' ) do %>
<strong>Submit</strong> the Form <i class="icon-arrow-right"></i>
<% end %>
The JQuery code will work as long as the link is a child of the form (that is, as long as link_to_submit is called from somewhere within the form_for block).
"Correct" is a tricky word in this context ;) . One could ask why you're not just taking a button element and make it look like a link?
Anyways — you can't achieve this with plain HTML (at least not to my knowledge). With a Javascript framework like e.g. jQuery you could simply do something like this:
$('a').click(function(){
$('form').submit();
return false;
});
Rails 2.3.x had a link_to_remote helper which let's you specify a :submit parameter (= DOM element's ID, default is the parent form). So you were be able to write:
link_to_remote 'submit', :url => {…}, :submit => "my_form"
But with Rails 3's push to UJS, this helper is gone.
You can add the following to the application helper:
def link_to_submit(text)
link_to_function text, "$(this).closest('form').submit()"
end
Then inside your view files you can just call
link_to_submit 'Submit Form'
And the link must be child of the form.
With jquery, this one-liner will work fine for a simple form.
<%= link_to t("translate.submit"), "#", class: "make it beautiful", :onclick=>"$('form').submit()" %>
Of course you don't really have to use jquery, just finding the dom element for your form will work fine as well.
<%= link_to t("translate.submit"), "#", class: "make it beautiful", :onclick=>"document.getElementById('your_form_id').submit()" %>
This way you don't use any ajax, just plain form submit.
In Rails 3, the link_to_remote helper is gone, but it's replaced with
link_to 'submit me', url_for(#post), {:remote => true, :class => 'submit_me'}
In your case, you likely want your form to do the AJAX, like so:
<%= form_for #post, :remote => true do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %>
<p><%= f.submit %></p>
<% end %>
With a companion link:
link_to 'submit me', '#', :class => 'submit_me'
Then, in an .js file included in the page body:
$('.submit_me').click(function() {
$('form').submit();
return false;
});
The idea is that anything more complicated than turning a link or form into an ajax request should be done with the jQuery callbacks, as listed here:
https://github.com/rails/jquery-ujs/wiki/ajax
And if you want to really get into interactive AJAX requests, go here for a great 2-part article on it.

Resources