Translate simple_form error messages - ruby-on-rails

I have this code displaying localized texts:
<%= f.input :full_name, :label => _('registration.form.label.name') + ':', :required => false -%>
<%= f.input :company, :label => _('registration.form.label.company') + ':', :required => false -%>
As you can see, the labels are being translated using the keys and an external system. The label part is working properly. However the error messages ("can't be blank" etc.) are not translated. The easiest way would be to customize the error messages by wrapping them in the _() tag, but I can't seem to find where to do it.
What would be the easiest way to translate the error messages? Preferably using the current translation system.

You could simply add the error messages to the activerecord yaml
en:
activerecord:
models:
mymodel:
attributes:
name:
too_short: "%{attribute} is too short."
This way you can also reference the attribute name within your yaml.
Of course, ideally you would place both the label and the validation in the simple_form i18n yaml, but I was not able to figure this out. Any suggestions for this are welcome.

The solution is to create custom error messages. (Example here: Customize error message with simple_form)
validates_length_of :name, :minimum => 5, :message => "blah blah blah"
And use them like this:
<%= f.input :name, :error_html => { :id => "name_error"} %>

Related

Select option not preselected after validation using collection in formtastic field

I'm 90% sure I'm doing something obviously wrong here, but when I'm using a select with a collection:
<%= f.input :description,
:label => "Which best describes who you are?",
:prompt => "Select an option...",
:collection => [[ "I am working for a company", "working"],["I am a freelancer", "freelancer"],["I am studying", "studying"],["I have recently graduated", "graduated"],["I teach", "teach"],["None of these things","none"]]
%>
and the form fails validation, the previously selected value is not selected, even though it is saved and is being passed to the params[:user][:description] as expected. Any ideas where I'm going wrong?
It's described there https://github.com/justinfrench/formtastic/wiki/Deprecation-of-%3Aselected-option#what-to-do-instead, so following should work
f.select :description,
options_for_select([[ "I am working for a company", "working"],["I am a freelancer", "freelancer"],["I am studying", "studying"],["I have recently graduated", "graduated"],["I teach", "teach"],["None of these things","none"]], f.object.description)
:label => "Which best describes who you are?",
:prompt => "Select an option...",
Also I would suggest moving collection to a separate helper method

Rails Validations neat errors in form

So i made a Validation that will check gender if an accurate ID number is inputted, if the data is incorrect then an error will appear beneath the select within the form.
.col
%h4 Participant
= f.field(:full_name, :label => "Full name *")
= f.field(:id_number)
= f.field(:gender, :field_type => :select, :choices => GENDER_SELECT, :label => 'Gender *')
%br #note i added this as the 'hacky' fix
= f.field(:race, :field_type => :select, :choices => RACE_SELECT, :label => 'Race *')
without the %br i have the form return the error like this
Is there a less hacky way so that when the error is displayed that it renders it something like this. so that the errors don't overflow onto other form elements
%br
= participant.errors[:gender]
%br
.field-error
= participant.errors[:gender]
Then use css to style the field-error class.
You should use CSS styles to control the errors layout/visual appearance instead of additional HTML tags.

Rails formtastic is asking for a country plug-in.. I don't want it. Anyone know how to tell it I don't want it?

I'm using formtastic and I've got a field country.. I'm getting this error when I attempt to display the screen.
To use the :country input, please install a country_select plugin,
like this one: https://github.com/jamesds/country-select
Now. I don't want to use any plugin.. It's free text, and I want to keep it that way.
Anyone know how to remove this requirement? Should be easy as... but I'm buggered if I can see how.
= semantic_form_for #store, {:html => { :class => "form-horizontal" }} do |f|
= f.input :default_country
Add
, :as => :string
to the end of the line that's causing the error
= semantic_form_for #store, {:html => { :class => "form-horizontal" }} do |f|
= f.input :default_country, :as => :string
In Rails 4, formtastic with country select input field:
Add 'country-select' to your Gemfile:
gem 'country-select'
If I use semantic form select, it doesn't shows previously saved value. So, the following is not working properly:
=f.input :country, as: :select, collection: country_options_for_select
So have to use standard form elements to get working:
=f.select :country, collection: country_options_for_select
I found that this plugin works out of the box (note the underscore instead of the dash):
https://github.com/chrislerum/country_select

Passing a variable to the i18n translations in simple_form

I need to pass in a variable to generate the label of a field with simple form. With normal translations you go about this in the following way: http://guides.rubyonrails.org/i18n.html#passing-variables-to-translations but for the life of me I am unable to get it to work with simple form.
I am attempting to pass it in using:
= f.input :name, :contact_type => f.object.contact_type.to_s
And in the simple_form.en.yml file:
en:
simple_form:
labels:
contacts:
name: "Name %{contact_type}"
This is outputting:
Name %{contact_type}"
Ignoring the variable all together. Is there a way to accomplish this?
Thanks,
Ryan Lundie
You need to explicitly add the label to the form input like this :
= f.input :name,
:contact_type => f.object.contact_type.to_s,
:label => t(:'simple_form.labels.contacts.name', :contact_type => "Whatever contact type")

Customize error message with simple_form

I'm using the simple_form gem. I want to customize the error message displayed when a user fails validations. How can I accomplish this?
You can declare the content of the
error message in your model:
validates_length_of :name, :minimum => 5, :message => "blah blah blah"
You can set id or class for your
error tag:
<%= f.input :name, :error_html => { :id => "name_error"} %>
Then you can use CSS for the styling.
And you can use
<%= f.error :name, :id => "name_error" %>
and you'll get
<span class="error" id="name_error">is too short (minimum is 5 characters)</span>
I dont know if it is any different for simple_form gem.
For content of error messages to be changed, you can use the :message attribute in the model.
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
end
Now the validation message will be Email is not filled up. If you want the field name also to be changed(Email to E-mail address something like that ), the approach now is to define it in locales.rb file like this
# config/locales/en.yml
en:
activerecord:
attributes:
user:
email: "E-mail address"
See link for details on locales. Another approach is to define in the model, humanized attributes like this:
class User < ActiveRecord::Base
validates :email, {:presence => true, :message => "is not filled up."}
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address",
...(other fields and their humanized names)
...
}
def self.human_attribute_name(attr, options={})
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
For customizing style of validation message we will have to edit the style for
#errorExplanation and .fieldWithErrors,in the scaffold.css stylesheet.
You can easily change the default error message comes in the translation file, which is found in config/locales/simple_form.en.yml.
In the specific initializer, config/initializers/simple_form.rb you can overrule the default options how the html is generated.
Hope this helps.
For completeness, I would like to add that formtastic is an easier choice to start with, because it has a default layout. I like simple_form a lot, but it does not offer any formatting out of the box, but that is their intention. With Formtastic it is very hard (impossible) to change the generated html, and with simple_form can you can completely mold the generated html to your liking. This is especially useful if you have a designer, and the forms you generate have to generate the same html. So if you are getting started, formtastic will give you nicer-looking results quicker. Also note that it is quite easy to switch, because the syntax is almost identical.
There is another solution explained here that wasn't mentioned in the answers. You can directly override the error messages from the views, in the form itself. For example:
<%= f.input :last_name,
placeholder: 'last_name',
error: 'This is a custom error message',
required: true,
class: 'form-field',
autofocus: true,
input_html: { autocomplete: "last_name" } %>
It is however not advised as it is not DRY, you would need to override it in every field.

Resources