2010/01/11

一つのフォームに複数の submit ボタンを入れる

たまに一つのフォームに複数の submit ボタンをつけて、どれをクリックするかでロジックを分けたい場合がある。 application.js
function submitWithValueAndConfirm(formid, commitValue, text)
{
 if (window.confirm(text)) {
     var objForm = document.getElementById(formid);
  objForm.commit_value.value = commitValue;
  objForm.submit();
 } else {
  return false;
 }
}


view
<% form_for :req, @req, :url => {:action => :update}, :html => {:method => :put, :id => "action"} do |f| %>
    <input type="hidden" name="commit_value" />
    <%= f.submit "CONFIRM", :onClick => ("return submitWithValueAndConfirm('action','confirm', 'Will do. Okay?');") %>
<%= f.submit "KILL", :onClick => ("return submitWithValueAndConfirm('action','kill', 'Will delete. Okay?');") %>
    <%= f.submit I18n.t('btn_something'), :onClick => ("return submitWithValueAndConfirm('action','confirm', '" + I18n.t('something') + "');") %>
<% end %>
上で return confirm はポップアップメッセージ用。:onclick を使用すると、:confirm が使えないため。

controller
case params[:commit_value]
  when "confirm"
    ...
  when "kill"
    ...
  when "something"
    ...
end

因みに、リンクでフォームをサブミットする方法

<% form_for ([:user, @user], :url => {:action => :create}, :html => {:name => :login}) do |f| %>
   ...
   <a href='#' onclick="document.login.submit();" >Login</a>

<% end %>

0 件のコメント: