Passing a variable to the i18n translations in simple_form - ruby-on-rails

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")

Related

Translate simple_form error messages

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"} %>

Simple_form always sets pattern for email input element

I use simple_form to display an email field:
= f.simple_fields_for :user do |f|
= f.input :email, wrapper: :append, pattern: false do
= f.input_field :email, type: "email"
Somehow it always set's the pattern for the input field but I want to use the HTML5 validation of the email input field instead.
Is there a way to prevent simpleform from setting the pattern?
You can monkey-patch SimpleForm:
module SimpleForm
module Components
module Pattern
def pattern
# Deactivated for good:
#input_html_options[:pattern] ||= pattern_source
nil
end
end
end
end
Now, pattern will no longer be generated from validations. You need to add pattern manually to each input that requires a pattern. Example:
= f.input :name, pattern: "[a-zA-Z]+"
Had the same problem ... found a workaround but its kind of hacky
add
:pattern => ".*"
to your field like this
<%= f.input_field :email, :autofocus => true, :pattern => ".*", :class => "span12", :placeholder => t('placeholder.email') %>
I would rather make a string_input.rb file in the app directory some where ... may be in a folder named 'inputs' then have this code
class StringInput < SimpleForm::Inputs::StringInput
def input
input_html_options[:class] = "input-xlarge #{input_html_options[:class]}"
unless string?
input_html_classes.unshift("string")
input_html_options[:type] ||= input_type if html5?
end
input_html_options[:pattern] = nil
add_size!
#builder.text_field(attribute_name, input_html_options)
end
end
This will have effect on all the pattern attributes so no need to put it in explicitly. of course you can also add a condition if the input type is email or not if you want to specify.
Happy coding :)

How to escape colon : in rails i18n?

Here is a line in the view:
<%= f.input :comm_date, :label => "Hello:", :as => :string %>
The regular i18n file has the format as:
Hello : 'Aloha'
In i18n yml file, we want to translate the "Hello:" as, for example, "Aloha:". Can we escape the colon : by doing below?
'Hello:' : 'Aloha:'
Or what's the right way to escape a colon?
The gem you are using, simple_form, as well as other similar ones such as formtastic, allow for using translation files (e.g. en.yml) for defining your label text.
You can see the translation file expectations from the simple_form documentation. Using your example, you'd need two translations, something like this, assuming your model is called Communication:
en.yml
en:
simple_form:
labels:
communication:
comm_date: "Hello:"
olelo.yml
olelo:
simple_form:
labels:
communication:
comm_date: "Aloha:"
And your view would simply be
<%= f.input :comm_date, :as => :string %>
No need to provide a value for the :label option.
Here is what we did:
'Hello:' : 'Aloah'
Just use single quote and it worked.

Customizing model name in ActiveAdmin filter

How can I customise model name in ActiveAdmin filter here?
This way doesn't work:
activerecord:
models:
category:
one: "категория"
other: 'категории'
filter :title, :label => "Change me"
filter :description, :label => "Change Me"
filter :user, :label => "Change Me"
You could also use I18n.t if you wanted to
filter :title, :label => (I18n.t "some.key.here")
ActiveAdmin uses metasearh ,so next rule works for me. (destination - parent model, rateplan - nested model)
Example:
en:
activerecord:
attributes:
destination:
rateplan: "RATEPLAN LOCALIZED NAME"
more info: https://github.com/ernie/meta_search#localization
UPD.
One more soulution is using fortastic rules for internalizaton
en:
formtastic:
labels:
rateplan: "RATEPLAN LOCAIZED"
more info: https://github.com/justinfrench/formtastic#internationalization-i18n
Active Admin uses formtastic to render filter as like the form fields. So you can customize you filters as you like as the formtastic'c customization options are really handy. For example. to change filters label: just use label: 'YOUR CUSTOM LABEL' option in filter method. You can use translations there as well

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