Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 804
Marat_Galiev Avatar asked Jan 25 '11 08:01

Marat_Galiev


3 Answers

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

like image 65
Jazz Avatar answered Nov 13 '22 04:11

Jazz


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

like image 45
polarblau Avatar answered Nov 13 '22 03:11

polarblau


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.

like image 13
Zequez Avatar answered Nov 13 '22 02:11

Zequez