I am looking to add translation to my select2 dropdowns, I have the following:
View
<%= f.collection_select(:guest_id, User.all, :id, :full_name, {}, class: "selectpicker", placeholder: true, multiple: true) %>
<SCRIPT> $(document).ready(function () {
$('#invitation_guest_id').select2({
language: $('html').attr('lang'),
placeholder: I18n.t('js.posts.select2.contact_name_dist'),
minimumInputLength: 3
});
});
</SCRIPT>
I have a file Translation.js
with the key contact_name_dist translated in many languages. For some reason, Rails only returns the english translation. Good thing, is it means it can read my file. But probably not picking up the language instruction.
Any argument missing ?
Found :
placeholder: I18n.t('js.posts.select2.guest_id') Should be the write instruction
Related
I'm having a really weird issue with i18n on a current rails project. I get translation missing messages whenever I attempt to use the key notifications. For example:
#en-US.yml
en-US:
notifications:
index:
title: 'notification page'
#/notifications/index.html.erb
<%= content_for :title, t('.title') -%>
This will fail and tell me the translation is missing
#en-US.yml
en-US:
notifications:
index:
title: 'notification page'
#/notifications/index.html.erb
<%= content_for :title, t('notifications.index.title') -%>
This will also fail.
#en-US.yml
en-US:
notification:
index:
title: 'notification page'
#/notifications/index.html.erb
<%= content_for :title, t('notification.index.title') -%>
This oddly, will work, removing the s will allow it to find the translation.
#en-US.yml
en-US:
notifications1:
index:
title: 'notification page'
#/notifications/index.html.erb
<%= content_for :title, t('notifications1.index.title') -%>
This also will work, adding a 1 to the end of notifications works.
It appears that rails does not like the word notifications. This is a problem because I don't want to have to rename the entire model for this, and also I want to use the i18n.t view shortcuts for consistency. Is notifications a reserved word? Is there any reason why it is failing to find it?
I'm not sure why it's failing in your case but I just had a go myself and it's not a reserved word, my locale file:
en:
notifications:
foo: bar
The result:
1.8.7 :001 > I18n.t('notifications.foo')
=> "bar"
This test was done with Rails 3.1.5 and Ruby 1.8.7.
In your case you got the following?
1.8.7 :001 > I18n.t('notifications')
=> "translation missing: en.notifications"
Although not an exact answer, I have found that there are a few words in I18n that cannot be used as keys. I am assuming the I18n code uses them elsewhere.
Others include "no", "yes", "on", etc.
Just using a synonym or do something like "notifications_" to make it different.
I've installed Twitter Bootstrap into my project and found unknown syntax for me:
<%=t '.title', :default => model_class.model_name.human.pluralize %>
<%= link_to t('.new', :default => t("helpers.links.new")),
new_article_path,
:class => 'btn btn-primary' %>
I can't understand the meaning of '.title', '.new' and 'helpers.links.new'. How do these constructions interact with the locale dictionary?
Also I've never met the construction :default => in t method, where I can read about it?
t is a helper method supplied by I18n internationalization mechanism of rails, and is a shortcut for I18n.translate method.
The locale file which I18n reads from is set by default to Rails.root/config/locales/en.yml assuming en is your default locale.
The first argument is the key which I18n will look for in your locale file.
The statement t('.new', :default => t("helpers.links.new")) means that I18n will look for the construct
en:
new: "new string"
in your locale file.
:default is the string which will be returned in case the first key was not found.
:default => t("helpers.links.new") just means that I18n will look for the following construct in en.yml:
en:
helpers:
links:
new: "new string"
and return it in case the first one was absent.
You can find here the full documentation of I18n translate method.
I'm using Rails 3.1 with Paperclip and trying to implement Uploadify for multiple file uploads on a single page. I tried following various samples, including: Rails3-Paperclip-Uploadify
Currently I have a Upload model which has a one to many relationship with my UploadImage model - This is what I had setup so far for my view:
UploadImages/new.html.erb
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" %>
<%= javascript_include_tag "swfobject.js", "jquery.uploadify.v2.1.0.js" %>
<script type="text/javascript" charset="utf-8">
<%- session_key = Rails.application.config.session_options[:key] -%>
$(document).ready(function()
{
// Create an empty object to store our custom script data
var uploadify_script_data = {};
// Fetch the CSRF meta tag data
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
// Now associate the data in the config, encoding the data safely
uploadify_script_data[csrf_token] = encodeURI(encodeURI(csrf_param));
$('.uploadify').uploadify
({
uploader : '/uploadify/uploadify.swf',
cancelImg : '/uploadify/cancel.png',
multi : true,
auto : false,
onComplete : function(event, queueID, fileObj, response, data)
{
var dat = eval('(' + response + ')');
$.getScript(dat.upload);
},
scriptData : {
'_http_accept': 'application/javascript',
'format' : 'json',
'_method': 'post',
'<%= session_key %>' : encodeURIComponent('<%= u cookies[session_key] %>'),
'authenticity_token': encodeURIComponent('<%= u form_authenticity_token %>'),
'upload_id' : '<%= #upload.id %>'
}
});
});
</script>
<%= form_for #upload.upload_images.build, :html => { :class => "upload", :multipart => true } do |f| %>
<%= f.file_field :image, :class => "uploadify" %>
<%= submit_tag "Submit Upload", :disable_with => "Uploading", :class => "submit"%>
<% end %>
I see the uploadify flash button, I select a few files and submit but this is all I see in my params:
{"utf8"=>"✓",
"authenticity_token"=>"K1bSH/FO0Hjdum0aiNU45mHJXezXTiCgh9XVmk1jrZM=",
"commit"=>"Submit Upload", "action"=>"create",
"controller"=>"upload_images"}
As you can see there is no file data being sent and even the scriptData that I specify doesn't get sent, I noticed that other people's code uses the script parameter for the uploadify function. In PHP frameworks they point it to the .php file which handles the saving. I'm using Paperclip so I wasn't sure how to implement this... perhaps this is my problem? Let me know if you need any additional details.
I found the answer by looking at this question: uploadify rails 3 nothing happens after the file is chosen
I had to attach some events to my submit button and add the script parameter to the uploadify function as I surmised.
So for starters in my config/routes.rb I needed to add:
post "upload_images/create"
And in my view I added:
$('#submit').click(function(event){
event.preventDefault();
});
$('#submit').click(function(event){
event.preventDefault();
$('.uploadify').uploadifyUpload();
});
and finally I added the script param to my initial uploadify function call:
script : '/upload_images/create'
After many hours of beating my head against it's finally working and making sense! Hope this helps somebody else.
Is it possible to create a select tag from the models validation without having problems with I18N?
For example if i had a model like this:
Model:
class Coffee < ActiveRecord::Base
SIZES = [ "small", "medium", "big" ]
validates :size, :inclusion => { :in => SIZES,
:message => "%{value} is not a valid size" }
end
Form:
<%= f.label :size %><br />
<%= select(:coffee, :size, Coffee::SIZES.collect {|d| [d, d]}) %>
How can I make this language independent?
The best way to handle that is to have locale-independent values in DB and localized labels on UI. You can achieve that by changing options for your select like that:
<%= select(:coffee, :size, Coffee::SIZES.collect {|d| [I18n.t(d), d]}) %>
and having that in you locale file:
some-language:
small: "small-translation"
medium: "medium-translation"
big: "big-translation"
That will generate html like that:
<select name="coffee[size]">
<option value="small">small-translation</option>
<option value="medium">medium-translation</option>
<option value="big">big-translation</option>
</select>
User will see localized options in select, but in request parameters locale-independent values will be posted, so your validation will work as it should.
If you're trying to make the validation message i18n independent, you don't actually need to mention which size is invalid, just that it is. You're passing an HTML select form, if they chose another size it's more likely they're messing with something so an exact error message is unnecessary.
For the select text itself, you could just pass it to the i18n system and handle it in that. By building the array with Coffee::SIZE.collect {|d| [t(".#{d}"), d]} you could add small, medium, big to your i18n file for that view to get localized values based off your validation options.
I have my Ajax working, builtin Rails javascript, with the submit button. However, I would like it to submit when I change the value of the dropdown box and eliminate the button. In my research I found what looks like the correct solution but I get no request to the server. Here is my dropdown form code, note it still has the submit button that worked before I added :onchange:
<% form_tag('switch_car', :method => :put, :remote => true) do %>
<div class="field">
<label>Car Name:</label>
<%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"),
:onchange => ("$('switch_car').submit()"))%><%= submit_tag "Switch Car" %>
</div>
<% end %>
Here is the HTML generated:
<form accept-charset="UTF-8" action="switch_car" data-remote="true" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="_method" type="hidden" value="put" />
<input name="authenticity_token" type="hidden" value="PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=" />
</div>
<div class="field">
<label>Car Name:</label>
<select id="id" name="id" onchange="$('switch_car').submit()">
<option value="9">Truck</option>
<option value="10">Car</option>
</select>
<input name="commit" type="submit" value="Switch Car" />
</div>
Thanks in advance for any help.
Replace your onchange with this,
onchange: "this.form.submit();"
this.form.submit() will not work if form is remote: true and rails-ujs is in use. In that case, a regular submit will occur instead of XHR.
Instead you should:
onchange: 'Rails.fire(this.form, "submit")'
You can read here for more details.
This is what I was able to do to get it to work. I named the form switch_car by using :name => "switch_car" and used the following javascript.
:onchange => ("javascript: document.switch_car.submit();")
I am still looking for a better answer so I will updated if I find something. This doesn't use submit .js for some reason. It processes it as HTML unlike the submit button which uses AJAX to update only the changing page elements. But this is the best I have been able to find so far.
Depending on the js library you are using:
Prototype: :onchange => ("$('switch_car').submit()")
Jquery: :onchange => ("$('#switch_car').submit()")
If you are using the defaults and your rails version is below 3.1, then prototype is the default library.
This is an old question, but none of the above answers work for me. They all result in a text/html request.
The following works, e.g. (the hide class sets css display: none):
<%= form.radio_button :tier_id, tier.id, onchange: "$('#submit-button-id').click();" %>
together with:
<%= form.submit "Save changes", id: 'submit-button-id', class: 'hide' %>
A more general solution using jQuery (I don't need to know the name of the form) is:
onchange: "$(this).parent('form').submit();"
This seems to have been around for a while but, I'll post my findings anyway since I haven't found this explanation anywhere yet.
I came across this article which describes quite well what's the problem when triggering a ajax request via the submit() method (with or without jQuery or Handler). The author then recommends to form your own AJAX request. That is not required and shouldn't be done to make use of the logic within rails.js (jquery-jus gem).
Problems with triggering submit() manually occur since rails.js binds and listens to an event that is namespaced submit.rails. To manually trigger a submission use
onchange: 'javascript: $( this ).trigger("submit.rails")'
on the element or the form.
For a select_tag, just add:
{:onchange => "myHandler();" }
where your handler will be:
this.form.submit();
Also, if onchange doesn't work you might want to try onChage with a capital C.
Finally, make sure NOT TO CONFUSE a select_tag with a form select.
See my answer to a similar question, only regarding a form select
Adding An Onchange Event To A Form Select
Time at 2021, with Rails 6
make a hidden submit then use js click() function:
<%= form_with(modle: #user, local: false) do |f| %>
<%= f.select :menu1, ["option1","option2"], {}, onchange: "javascript:this.form.commit.click();" %>
<%= f.submit 'save', class: "hidden" %>
<% end>
reference: https://stackoverflow.com/a/8690633/15461540
If you want to learn rails way ajax submit on fields change here is the code.
<%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"),
data: { remote: true, url: your_ajax_route_path }%><%= submit_tag "Switch Car" %>
data: { remote: true, url: your_ajax_route_path }
will automatically submit your input to your_ajax_route_path. If you are using a form builder then you should use with input_html
input_html: { data: { remote: true, url: your_ajax_route_path } }
like this. I hope it'll be useful for you
None of the solutions was working for me so I used the given below solution.
$("#q_dimension_id_eq").on("change", function (e) {
$(this).closest("form").submit();
});
I'm using rails 4.2.1 with jquery_ujs and it works for me:
onchange: 'jQuery(this).parent().trigger("submit")'
OBS.: It assumes the element is immediately child from form. You must adjust parent() according your DOM tree.