Michael Anhari

Using i18n to customize submit button text in Rails

A globe of Earth sitting on a desk

Rails provides a robust solution to internationalization (i18n) 1, but it can be leveraged for a lot use cases even when your application only needs to support a single language.

One such example, is customing the default behavior of the submit form helper. This helper tries to convert the name of your model into some helpful text for a form's submission button.

For example, if we have the following form where @article is an instance of our Article model:

<%= form_for @article do |f| %>
  <%= f.submit %>
<% end %>

our button will read "Create article" if @article hasn't been persisted, and "Update article" if it has.

But what if you want to change it to read as Create blog post and Update blog post?

You could try passing a string to the submit function, but that wouldn't change the text when the form is used with new/existing objects.

<!-- not ideal -->
<%= form_for @article do |f| %>
  <%= f.submit "Create article" %>
<% end %>

i18n to the rescue

Rails's internationalization system allows us to define what this model should be referred to as when it's name is being used for human-readable use cases like our button.

In config/locales/en.yml you can set the following:

activerecord:
     models:
       article: Blog Post

submit will now use "Blog Post" instead of "Article" when used without an argument:

<!-- all good now! -->
<%= form_for @article do |f| %>
  <%= f.submit %>
<% end %>

Footnotes

1.

i18n comes from the fact that there are 18 letters between the i and the n in "internationalization"

↩ī¸Ž

Newsletter

I'm working on sending out a weekly newsletter. I'll make it as easy as possible to unsubscribe at any time.