select and onChange in a Ruby on Rails form - forms

I browsed all SO questions and answers about this topic but I'm still unable to make my scenario work.
I want to trigger a click button action when a dropdown menu option is selected ; seems simple and should be very common with AJAX.
Here are the relevant excerpts of my code:
<%= form_for(#test, :html => {:id => "form_id", :name => "MyForm", :remote => "true"}) do |form| %>
<%= form.label "Menu1" %>
<%= form.select (:Menu1, [["Option1","value1"],["Option2","value2"]], :html_options=>{:onChange=>"javascript: this.form.apply_button_name.click();"}) %>
<!-- more select menus and text fields here -->
<div class="actions">
<%= form.submit "Apply", :name => "apply_button_name", :remote => "true" %>
</div>
<% end %>
I used ":remote => "true" both for the form and the button because that's the only way to get AJAX working. I also tried with and without explicit "html_options" and "javascript:", after I browsed some SO answers that suggested that but that did not help. I also tried onSelect, and onClick instead of onChange, but still no luck.
The generated HTML is the following:
Menu1
<select id="test_Menu1" name="test[Menu1]"><option value="value1">Option1</option>
<option value="value2" selected="selected">Option2</option></select>
As you can see, there's no onChange event handler in the HTML code ; WHY? Anyone is seeing what am I doing wrong?
Thanks for any help.

Modify your call to form.select, like this:
<%= form.select :Menu1, [["Option1","value1"],["Option2","value2"]], {},
:onChange=>"javascript: this.form.apply_button_name.click();" %>

If you examine the documentation for:
API Dock Ruby on Rails select
You will see that the select form helper takes the form:
select(object, method, choices, options = {}, html_options = {})
If you don't pass anything for the option hash (in your case this will be an empty hash), the form thinks that your html_options hash are your options hash, and gets confused.
A way to check this is to add something like {:onchange=> "alert('Hello');"} and either see if the event successfully triggers, or alternatively, in your actual web page, right click on the select element and inspect it. If no onchange option is present in the html, that means that your rails form helper is indeed confusing the html_options with the other options. So, what you should have:
<%= form.select (:Menu1, [["Option1","value1"],["Option2","value2"]], {}, {:onChange=>"handler();"} %>
MAKE SURE TO INCLUDE THE EMPTY HASH FOR THE OPTIONS BEFORE THE HTML OPTIONS AND YOU SHOULD BE FINE. I don't think you even need to have the html_options and javascript stuff you have.
Lastly, if onChange doesn't work, try to use onchange with no capital C.

Related

Displaying Rails Required Fields Form Errors All At Once

I'm using the Rails form and I'm also using Bootstrap tabs. I have 4 tabs that a user fills out and on the 4th tab is the submission button. I have a number of required: true fields in the form, and when I go to click on the submit button leaving any of these fields blank, the pop-up saying "Please fill out this field" appears.
Question: How can I just have a box appear with ALL the error messages, instead of each individual error message appearing one at a time?
I've read a number of posts, and have tried most suggestions (with exception to ones that include JS, as I'm hoping there is a strong solution not including JS). I put below some code below my submit button that I tried but it doesn't display anything as the individual box error message I think overrides it.
Any help is appreciated.
_Form:
<%= form_for(#property, html: { multipart: true }) do |p| %>
...
<%= p.file_field :picture, :multiple => true, name: "property_attachments[picture][]", size: 2 %>
<%= p.submit "Submit", class: 'btn btn-primary' %>
<% if #property.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#property.errors.count, "error") %>.
</div>
<ul>
<% #property.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% end %>
Figured it out and learning a lot about Rails Forms. I was using required: true for a number of fields and this created individual pop-ups on each error one by one. I removed all of the required: true fields and then added validations in the model (eg. validates: :price, presence: true) and then the error message I used above in my question displayed any missing fields.

Why Isn't The Partial File Automatically Created?

Getting through Michael Hartl's tutorial great; I've encountered a few snags along the way but nonetheless, it's working out better than I expected.
My question, is regarding the partial file. In the tutorial if I have read correctly, chapter 5- it advises to edit the 'application.html.erb' file with...
'<!DOCTYPE html>
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
<%= stylesheet_link_tag "application", media: "all",
"data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
<%= render 'layouts/shim' %>
</head>
<body>
<%= render 'layouts/header' %>
<div class="container">
<%= yield %>
</div>
</body>
</html>'
The tutorial then says if this line worked I should find a file called 'app/views/layouts/_shim.html.erb' and I cannot find it, thus, it was not automatically created, further not allowing me to pull up the referring static page in my browser (which may or may not be related).
Thanks in advance.
Of course, to get the partial to work, we have to fill it with some content; in the case of the shim partial, this is just the three lines of shim code from Listing 5.1; the result appears in Listing 5.10.
So yes. You have to create partial file by yourself and fill it with proper content. In case you code editor doesn't support partial extraction.
For example:
Using rails.vim plugin for VIM there is the possibility to extract selected lines into partial by using Rextract <partial_name> command. Which creates new file, moves selected lines into it and replace selected lines from source file with <%= render :partial => '<partial_name>' %>

Rails paperclip, Edit form file_field not assigned

I used paperclip to attach an avatar onto my user, in my Model:
has_attached_file :avatar,
:styles => {square_tiny: '50x50#', square_small: '100x100#', square: '200x200#'}
I have a form
<%= form_for(#user_profile,
:url => { :controller => :user_profiles, :action => :update_general_info, :id => #user_profile.id },
:html => { :multipart => true,
:class=> "form-horizontal" }) do |f| %>
<div class="control-group">
<%= f.label :avatar, :class => "control-label" %>
<div class="controls">
<%= f.file_field :avatar %>
</div>
</div>
....
<% end %>
The upload works perfect, but I come back and EDIT my user, the file field says 'no file chosen'. And since I am validating presence of that avatar, every time a user edit his details, he has to upload his avatar again...
How do I work around that?
I thought the :multipart => true would help but it didn't.
There is absolutely no good way for a page to set a value to a file field, and that's for security reasons.
If the browser allowed a page or a JS script to set a value to a file field that would allow a malicious page to preset the file field value with some system or passwords file. And that would be a massive security hole.
What I do in that case is I display the already saved file as a link that the user can click to download. You can then provide little AJAX links to delete (the file is deleted with an AJAX call and the link replaced with a new file input) and replace (the link is replaced with a file input).
Your last option would be to use AJAX to upload the file. If you use AJAX for a file upload you'll POST to a hidden frame so the file input will keep its selected value.
Either way keep in mind that any change to file field value has to be user initiated.

How exactly does Rails prefills forms?

I have a (simple) question for my own curiosity:
I'd like to find out how Rails prefill forms with posted values like... you know, when there's a validation error on some models' attributes then you do something like "render :edit" and the form is magically prefilled.
What exactly are the mechanisms that Rails use to do such a thing? I didn't manage to find any documentation on this subject and I'd like to understand the magic.
So if someone can give me some explanations on this subject, I'll be glad to read that!
Thanks!
[Edit] And a subsidiary question: when a model inherits from another (STI) do we have to do something in particular to prefill forms?
You are mostly using the form_for helper in this style:
<%= form_for #person do |f| %>
<!-- Some more stuff here -->
<%= f.text_field :first_name %><br />
<!-- Some more stuff here -->
<% end %>
What this essentiall does is, it generates a text field that is filled with the value of #person.first_name.to_s. When an error happens, #person.first_name is filled with the errornous value. If you create a person (#person = Person.new), then #person.first_name.to_s is "".
So rails just fills the text field with the value, the attribute has.
f by the way is a rails FormBuilder. It's methods are documented here, if you want to take a closer look at the source.

How do I change the text_area default size for a form in rails 3?

I'm going through Agile Web Development with Rails and I'm having some trouble with the form helper text_area. Specifically, I want to make the text area smaller (the form submits correctly and everything goes into the database correctly). According to the book this code should work:
<%= form_for(#request) do |f| %>
<div class="actions">
...
<div class="field">
<%= f.label :quote_details, "*Items required:" %>
<%= f.text_area :quote_details, :rows=>5, :cols=>40 %>
</div>
It seems that no matter what numbers I put for :rows or :cols, the box stays the same default size. Instead of :rows and :cols, I used :size=>"3x40" and size=>"5x8" etc.. but the box still always stays the same size.
As an experiment I tried
<%= f.text_field :quote_details, :size=>"300*39" %>
That changed the number of columns, but removing the :size and putting :rows or :cols has no effect (it goes back to a default size for a text_field).
I did see this:
Change default Rails text_area helper rows/cols
I tried answer 1, but the answer given didn't work for me. I don't really understand what the second and third answers mean. I might be doing something else wrong or maybe it's a different problem.
I'm just stumped. Any help or ideas on what's going on would be greatly appreciated. Thanks for any responses.
Oh, I'm using rails version 3.0.0 and ruby 1.9.2p0 on vista.
your first code segment has :cols => 40% instead of 40?
I would also consider using CSS to do it, as that can make changing the look of the webpage isolated to the CSS presentation layer.
try do it with form_with. For me it works.
<%=form_with, local: true do |form| %>
<%= form.label :comment %>
<%= form.text_area :body, :rows=>10, :cols=>60 %>
<% end %>