Rails text_field_tag id attribute - ruby-on-rails

I'm going through Michael Hartl's Rails tutorial. One of the exercises for chapter 8 is to rewrite the code using form_tag instead of form_for. After viewing the source that form_for was giving me and looking up each tag in the Rails documentation, I was able to successfully put it together.
My question is: How does Rails know what id attribute to give the <input> tag created by text_field_tag, so that it matches the id of the <label> tag created by the label_tag that precedes it?
Here's the code for the form:
<%= form_tag(sessions_path) do %>
<%= label_tag "session_email", "Email" %>
<%= text_field_tag "session[email]" %>
<%= label_tag "session_password", "Password" %>
<%= password_field_tag "session[password]" %>
<%= button_tag("Sign in", name: "commit", type: "submit") %>
<% end %>
Here's the resulting html:
<form accept-charset="UTF-8" action="/sessions" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="c9a5KJveRSOQyDo/ckUtpmQAbjw2f1alnB6Dn1lu3XU=" /></div>
<label for="session_email">Email</label>
<input id="session_email" name="session[email]" type="text" value="{:id=>"session_email"}" />
<label for="session_password">Password</label>
<input id="session_password" name="session[password]" type="password" value="{:id=>"session_password"}" />
<button name="commit" type="submit">Sign in</button>

Note that since Rails 5.1, the recommended form helper to use is form_with.
And form_with no longer automatically generates id's and class's for DOM elements any more like form_for and form_tag used to.
This has implications for adding markup like labels which used to link up to their corresponding input fields automatically. Now, for a label to properly pair up to an input field (with the for attribute) you need to explicitly add the id attribute to the input.
Example
ERB:
<%= form_with model: User.new do |f| %>
<%= f.label :name %>
<%= f.text_field :name, id: :user_name %>
<% end %>
which generates HTML:
<form action="/users" method="post">
<label for="user_name">Name</label>
<input id="user_name" type="text" name="user[name]">
</form>
See also
https://medium.com/#tinchorb/form-with-building-html-forms-in-rails-5-1-f30bd60ef52d, specifically the heading "No more auto-generated ids and classes".

Related

Rails generate wrong method for "form_tag". How to fix that?

On on page, I have 2 forms like this:
<%= form_tag(create_car_service_settings_index_path, remote: true, method: :post) do %>
<%= hidden_field_tag "service_type", 1 %>
<%= text_field_tag "service_name", "", id: "service_name_car" %>
<%= submit_tag "Add Service" %>
<% end %>
... some HTML ...
<%= form_tag(create_car_service_settings_index_path, remote: true, method: :post) do %>
<%= hidden_field_tag "service_type", 0 %>
<%= text_field_tag "service_name", "", id: "service_name_car" %>
<%= submit_tag "Add Service" %>
<% end %>
The first form is rendered as POST, but the second one as GET; in routes.rb is following:
resources :settings do
collection do
...
post 'create_car_service'
post 'edit_car_service'
end
end
Why the second form is rendered as GET instead of POST? Stuck on this for a while.
Thanks.
EDIT:
First form:
<form action="/settings/create_car_service" accept-charset="UTF-8" data-remote="true" method="post">
...
Second form:
<form action="/settings/create_car_service" accept-charset="UTF-8" data-remote="true" method="get">
When you do bin/rails routes you should get something like this
Prefix Verb URI Pattern Controller#Action
create_car_service_settings POST /settings/create_car_service(.:format) settings#create_car_service
edit_car_service_settings POST /settings/edit_car_service(.:format) settings#edit_car_service
So that post route should be create_car_service_settings_path not create_car_service_settings_index_path that points to settings#create_car_service
But it is a strange if you get for one method GET and other POST. Can you paste the output from these forms (html)
EDIT
So using the path that you provided generated an error for me. When I use this
<%= form_tag(create_car_service_settings_path, remote: true, method: :post) do %>
I will get this for first
<form action="/settings/create_car_service" accept-charset="UTF-8" data-remote="true" method="post">
for second
<form action="/settings/create_car_service" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="service_type" id="service_type" value="0" />
<input type="text" name="service_name" id="service_name_car" value="" />
<input type="submit" name="commit" value="Add Service" data-disable-with="Add Service" />
</form>

Simple_form class form-horizontal with bootstrap 3 not working in rails 4

I have two rails apps, and the 'form-horizontal' is working in one, but not the other, and I have no idea why.
First app is called "Horizontal" (my test app) and the other is "Inventory"
Form in "horizontal" app:
<%= simple_form_for(#part, html: {class: 'form-horizontal' }) do |f| %>
<div class="field">
<%= f.input :name %>
</div>
<div class="field">
<%= f.input :number %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and looks like this in the browser:
and the form for the "inventory" app is:
<%= simple_form_for(#item, html: {class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<div class="field">
<%= f.input :part_number %>
</div>
<div class="field">
<%= f.input :on_order_qty %>
<%= f.input :revision %>
<%= f.input :current_rev %>
<%= f.input :name, required: false%><br>
</div>
<%= f.simple_fields_for :parts do |part| %>
<%= render 'part_fields', :f => part %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add additional supplier', f, :parts %><br><br>
</div>
<div class="fields">
<%= f.input :stock_qty %>
<%= f.input :ncmr_qty %>
</div>
<div class="form-actions">
<%= f.submit %>
</div>
<% end %>
but it looks like this in the browser:
Why won't the form-horizontal class work in the "Inventory" app?
It appears that the integer input fields are getting rendered horizontally, but something weird is happening in the text input fields. Here is the source html from the browser for the "Inventory" app:
<form accept-charset="UTF-8" action="/items" class="simple_form form-horizontal"
id="new_item" method="post"><div style="margin:0;padding:0;display:inline"><input
name="utf8" type="hidden" value="✓" /><input name="authenticity_token"
type="hidden" value="H3DKGhGdtfv1e8F1rg9TgDJUyaBspXOSFMpm2gnjwzk=" /></div>
<div class="field">
<div class="input string required item_part_number"><label class="string required"
for="item_part_number"><abbr title="required">*</abbr> Part number</label><input aria
required="true" class="string required" id="item_part_number" maxlength="255"
name="item[part_number]" required="required" size="255" type="text" /></div>
</div>
<div class="field">
<div class="input integer optional item_on_order_qty"><label class="integer optional"
for="item_on_order_qty">On order qty</label><input class="numeric integer optional"
id="item_on_order_qty" name="item[on_order_qty]" step="1" type="number" /></div>
<div class="input string optional item_revision"><label class="string optional"
for="item_revision">Revision</label><input class="string optional" id="item_revision"
maxlength="255" name="item[revision]" size="255" type="text" /></div>
<div class="input boolean optional item_current_rev"><input name="item[current_rev]"
type="hidden" value="0" /><input class="boolean optional" id="item_current_rev"
name="item[current_rev]" type="checkbox" value="1" /><label class="boolean optional"
for="item_current_rev">Current rev</label></div>
<div class="input string optional item_name"><label class="string optional"
for="item_name">Name</label><input class="string optional" id="item_name" maxlength="255"
name="item[name]" size="255" type="text" /></div><br>
</div>
( I took out the html for the nested fields and some other fields for brevity)
<div class="form-actions">
<input name="commit" type="submit" value="Create Item" />
</div>
</form>
I've tested in both Chrome and Firefox. I've checked that the bootstrap-sass gem and simple_form gem are the same versions. I have no fancy customization css or javascript, just the #import 'bootstrap'; line in a bootstrap_custom.css.scss file in both apps. I don't know why the text input fields cover the whole width of the screen in the "Inventory" app, but the integer fields seem to be fine and rendering horizontally. What's wrong here?
I ran into a similar issue and found a pretty quick fix here http://www.iconoclastlabs.com/blog/using-twitter-bootstrap-3-with-simple_form
The simple fix is (after doing the normal simple form bootstrap init stuff -see below), you add the following code to an initializer (like config/initializers/simple_form_bootstrap.rb)
inputs = %w[
CollectionSelectInput
DateTimeInput
FileInput
GroupedCollectionSelectInput
NumericInput
PasswordInput
RangeInput
StringInput
TextInput
]
inputs.each do |input_type|
superclass = "SimpleForm::Inputs::#{input_type}".constantize
new_class = Class.new(superclass) do
def input_html_classes
super.push('form-control')
end
end
Object.const_set(input_type, new_class)
end
and you are off to the races.
The "normal simple form bootstrap init stuff" goes something like:
rails generate simple_form:install --bootstrap
If you want horizontal forms, add this to your simple_form config
config.form_class = "simple_form form-horizontal"
CAVEAT: Based on some recent comments, it appears this many not work for more recent versions of simple_form. I wrote the post some time ago and the project that was using this code (for me) is no longer using simple_form so it's hard to track down the exact version number. I believe this will work for verisions 2.x. Once you get to v3 you may have issues and have to find a different solution.
To override on per form basis, change:
<%= simple_form_for(#item, html: {class: 'form-horizontal' }) do |f| %>
to
<%= simple_form_for(#item, wrapper: :horizontal_form) do |f| %>
to change all forms to horizontal, change initializer:
config/initializers/simple_form_bootstrap.rb line:
config.default_wrapper = :vertical_form
to
config.default_wrapper = :horizontal_form
(remember to restart rails server after changing initializer)
to change just an individual input, change:
<%= f.input :on_order_qty %>
to
<%= f.input :on_order_qty, wrapper: :horizontal_form %>
Simple Form 3.1.0.rc1 has been released!! This supports bootstrap 3. Just update your gem to the latest version this will solve your problem. You can check the other enhancements through the change logs here https://github.com/plataformatec/simple_form/blob/v3.1.0.rc1/CHANGELOG.md
Just update your simple_form to
gem 'simple_form', '3.1.0.rc2'
And then re-run
$ rails generate simple_form:install --bootstrap
I tried quite many different solutions but, nothing helped until I've added wrapper: :horizontal_form line to each form inputs. And, I have the latest simple_form version: 3.2.1
For example:
= f.input :payment_term, wrapper: :horizontal_form
Hint: https://gist.github.com/chunlea/11125126/
Use simple form RC1. There is an entire example project: https://github.com/rafaelfranca/simple_form-bootstrap . I've just copied bootstrap initializer and followed horirozontal view example at https://github.com/rafaelfranca/simple_form-bootstrap/tree/master/app/views/examples.
If all the above doesn't work try gem
gem 'simple_form_bootstrap3'
Need to replace form_for with horizontal_form_for
Please check out the very helpful sample app here for usage of Simple Form and the Bootstrap toolkit on a Rails 4 application.:
http://simple-form-bootstrap.plataformatec.com.br/
Don't forget the docs page.
I had an issue with the full length of the input field spanning my entire page. Here is what I did and I hope it helps someone else.
Using simple_form 3.4.0
Open config/initializers/simple_form_bootstrap.rb
At the bottom of the page I changed the following:
From
config.default_wrapper = :vertical_form
config.wrapper_mappings = {
check_boxes: :vertical_radio_and_checkboxes,
radio_buttons: :vertical_radio_and_checkboxes,
file: :vertical_file_input,
boolean: :vertical_boolean,
datetime: :multi_select,
date: :multi_select,
time: :multi_select
}
end
To:
config.default_wrapper = :horizontal_form
config.wrapper_mappings = {
check_boxes: :horizontal_radio_and_checkboxes,
radio_buttons: :horizontal_radio_and_checkboxes,
file: :horizontal_file_input,
boolean: :horizontal_boolean,
datetime: :multi_select,
date: :multi_select,
time: :multi_select
}
end
Then restart your app to reinitialize.
When i use form-horizontal in my code, i also modify the different inputs with the bootstrap classes. For exemple with bootstrap 3:
<div class="form-group">
<%= f.label :name, class: "control-label col-sm-3" %>
<div class="col-sm-4"><%= f.text_field :name, placeholder: "Your placeholder", class: "form-control" %></div>
</div>
And now you can adjust the col-sm to col-sm-12 if you want the entire width of your app. I think it's easier to customize this way. ( col-sm are for bootstrap 3, if you need older version i think you have to use the old span- notation)
More info for bootsrap form here: doc
Here is an exemple of code with bootstrap 2 and simple form: doc
The output form with bootsrap 2 should look like this:
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputName">Name</label>
<div class="controls">
<input type="text" id="Name" placeholder="Name">
</div>
</div>
</form>
I think you need to set a control-group class div and a controls class div.
Here is the doc form the old syntax: doc
Hope it helps

Rails nested attributes array

I am having trouble creating multiple model objects using nested attributes. The form .erb I have:
<%= f.fields_for :comments do |c| %>
<%= c.text_field :text %>
<% end %>
is generating input fields that look like this:
<input type="text" name="ad[comments_attributes][0][text]" />
<input type="text" name="ad[comments_attributes][1][text]" />
<input type="text" name="ad[comments_attributes][2][text]" />
when what I really want is for it to look like this:
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
Using form helpers, how can I make the form create an array of hashes like I have in the second example, instead of a hash of hashes as it does in the first?
You could use text_field_tag for this particular type requirement.
This FormTagHelper provides a number of methods for creating form tags that doesn’t rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.
If you give them all the same name and append [] to the end as follows:
<%= text_field_tag "ad[comments_attributes][][text]" %>
<%= text_field_tag "ad[comments_attributes][][text]" %>
<%= text_field_tag "ad[comments_attributes][][text]" %>
You can access these from the controller:
comments_attributes = params[:ad][:comments_attributes] # this is an
array
The above field_tag html output look like this:
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
If you enter values between the square brackets, rails will view it as a hash:
<%= text_field_tag "ad[comments_attributes][1][text]" %>
<%= text_field_tag "ad[comments_attributes][2][text]" %>
<%= text_field_tag "ad[comments_attributes][3][text]" %>
would be interpreted by the controller as a hash with keys "1", "2" and "3".
I hope i understand correctly what you needed.
Thanks

How does rails know what :something is?

I have the following code
form.label :artists
which outputs
<label for="artist_artist_name">Artist name</label>
How did rails find the strings artist_artist_name and Artist name?
In general, how can I track this kind of information down?
I have tried grep -ri artists * in the project root but there is no result (apart from form.label :artists). Same for Artist name...
The form helper is used as in the following snippet:
<%= form_for #person do |f| %>
<%= f.label :first_name %>:
<%= f.text_field :first_name %><br />
<%= f.label :last_name %>:
<%= f.text_field :last_name %><br />
<%= f.submit %>
<% end %>
What follows f.label or f.text_field is the identifier of a property for the object referred by #person.
The CSS ID you notice is simply obtained concatenating the name of the variable with an underscore, and the property name; the label is obtained replacing the underscores in the property with spaces, and rewriting the first word in capital case.
The code I reported would generate the following HTML (I removed the parts that were not important).
<form action="/people" class="new_person" id="new_person" method="post">
<label for="person_first_name">First name</label>:
<input id="person_first_name" name="person[first_name]" size="30" type="text" /><br />
<label for="person_last_name">Last name</label>:
<input id="person_last_name" name="person[last_name]" size="30" type="text" /><br />
<input name="commit" type="submit" value="Create Person" />
</form>

Is there any way to create a form with formtastic without a model?

I would like to use formtastic to create form but I don't have a model associated with that (login form with username, password and openid URL).
Of course I could create a model to do that but that model was just a hack without any useful code in it.
You can pass a string instead of a model, which will be used to generate the field names:
<% semantic_form_for 'user', :url => 'login' do |f| %>
<% f.inputs :name => 'Login Details' do %>
<%= f.input :username %>
<%= f.input :password %>
<% end %>
<% end %>
Which will produce something like:
<form action="/login" class="formtastic user" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="E/NksKRd7Twh4nGp1Qc8jBQNfqYDn8gg6sWdTdCtl+g=" /></div>
<fieldset class="inputs"><legend><span>Login Details</span></legend><ol>
<li class="string required" id="user_username_input"><label for="user_username">Username<abbr title="required">*</abbr></label><input id="user_username" name="user[username]" size="50" type="text" /></li>
<li class="password required" id="user_password_input"><label for="user_password">Password<abbr title="required">*</abbr></label><input id="user_password" name="user[password]" size="50" type="password" /></li>
</ol></fieldset>
</form>
But you will need to be more specific with your options as formtastic won't be able to work out what types of fields it should use, all will default to textfields (although it automatically makes fields named like password password type fields).
A better way to do this though would be with a sessions model, have a look at the way authlogic (http://github.com/binarylogic/authlogic) works for more info.

Resources