I currently have a couple of forms that I'm trying to change the button that submits it based if I'm on the edit or new action. I had two forms created but this smelt bad, and am now just using a single form partial.
At the end of my partial, I have something like this at the end of my forms:
<p>
<% if controller.action_name == 'new' %>
<%= f.submit "Create", :class => "pink_button"%> or
<% elsif controller.action_name == 'edit' %>
<%= f.submit "Update", :class => "pink_button"%> or
<% end %>
<%= link_to "cancel", :back %>
</p>
That way, if I'm creating some new, the button reads "Create", and if it's an update that a user is trying to complete, the button reads "Update". This works great, until the form is submitted and validation fails.
In my controller, I'm catching things that do fail like so:
def update
@list = current_user.lists.find(params[:id])
if @list.update_attributes(params[:list])
redirect_to list_path(@list), :notice => "List '#{@list.name}' updated."
else
render :action => 'edit'
end
end
So the form is simply re-rendered. The problem is, I'm no longer on the edit path. This means, my form button does not show up any longer.
Is there a convention to what I'm trying to do?
Thanks
Yes, this is handled in Rails with i18n by default. The translations are in ActionView, and look like this:
en:
helpers:
select:
# Default value for :prompt => true in FormOptionsHelper
prompt: "Please select"
# Default translation keys for submit FormHelper
submit:
create: 'Create %{model}'
update: 'Update %{model}'
submit: 'Save %{model}'
All you need to do is f.submit
(without passing "Create" or "Edit", etc) and the translations will do the rest. You can overwrite these by dropping the above yaml into your local locales.
If you need to set the class you can pass nil, e.g. f.submit nil, :class => 'whatev'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With