David Roth
David Roth

Reputation: 193

Rails form_with change submit text

I'm creating a new form using form_with helper and as you know is detecting if you are on a new record page or a edit page ([following the CRUD example from rails guide][1], i render the form as a partial to reuse the form) changing the text on the submit button depending where i call the form.

<%= form_with model: @article, local: true do |form| %>
   <p>
       <%= form.label :title %>
       <%= form.text_field :title %>
   </p>
   <p>
       <%= form.submit %>
   </p>
<% end %>

But i want to the text on the form submit helpers for translating purpose, but I don't know if is possible to preserve the Create/Update recognition functionality and if there are some helper or class where I can configure those labels.

Upvotes: 2

Views: 2746

Answers (2)

Sandip Mane
Sandip Mane

Reputation: 1633

I handle this with the @article object!

When the form is rendered from create method, @article doesn't have the ID in it otherwise from update method you'll have to pass an ID for it to be updated.

So it would be:

<% if @article.id.present? %>
  <%= form.submit "Update" %>
<% else %>
  <%= form.submit "Create" %>
<% end %>

Upvotes: 2

krishna raikar
krishna raikar

Reputation: 2675

Dont mess up your form with conditions.Put those conditions in helper classes

form.rb

.. <%= form.submit frm_action %> ..

And your helper method like this

helper.rb

def frm_action
  if @article.id.present?
    "Create"
  else
    "Update"
  end
end

Upvotes: 3

Related Questions