Get data from html form to ruby in Ruby on Rails
I have some html like this
<html>
<h1>Text to PDF</h1>
<textarea name="comments" cols="40" rows="5">
Enter your Text here...
</textarea><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
I want to give the value of the text into the controller for this page/view.
How do I do this with rails?
I am new to rails, what is the mechanism for this? I don't need to write to the database just want to hand it to the controller. If there is a good tutorial for this sort of thing that would be great, I am not convince I am approaching this correctly.
You can use params['comments'] in your controller to get the value.
In your controller-
def parse_comments
comments_from_form = params['myform']['comments']
#do your stuff with comments_from_form here
end
In your view-
<h1>Text to PDF </h1>
<%= form_tag :action => 'parse_comments' do %>
<%= text_area :myform, :comments, :cols => '40', :rows => '5' %>
<%= submit_tag "Submit" %>
<% end %>
(edit: added = to form_tag opening, without it code won't work)
Related
I am trying to make a form where you select tables that you want to export. I made a simple form with a list of tables that can be exported. My plan was to allow the user to toggle check boxes for the tables they want to export and as a result they would be able to download a zip file containing the tables.
Currently, when I try to go to the page with the form, I get an error:
undefined method 'model_name' for nil:NilClass
The majority of the usage of simple forms that I see online consists of using forms to create new items to save in their models. As a result, it seems that the line simple_form_for #example would mean that when the user clicks the submit button, there is a line in the controller such as #example = SomeClass.new". My understanding is that the user input of the form is saved in #example and can be used by the controller. However, as I am not creating a new item in the model, I just want to use the values from #example, I am not sure what to put in the controller to get rid of the error so that I can code the rest of the function in the controller.
Controller:
class FormController < ApplicationController
def index
#options = []
print(#options)
end
end
The form used:
<h2>Which tables do you want to export?</h2>
<div class="well">
<% tables_in_model = %w(Table1 Table2 Table3) %>
<%= simple_form_for #selected_options, :url => form_index_path, :method => :get do |f| %>
<%= f.input :options, as: :check_boxes, collection: tables_in_model %>
<%= f.button :submit, as: :Submit %>
<% end %>
</div>
As you said correctly in your question, simple_form should be used to render forms to the user when her actions are related to the creation or edition of ActiveRecord models.
For instance, when writing down code to enable a search feature, where your goal is to simply pass a bunch of user chosen params to a controller, you should not use it. I believe you are in a similar position with the feature you described.
Simple solution though: use rails form related DSL to get your form going!
Hope it's the answer you needed. Feel free to ask for more details if needed. Cheers!
i think you are using simple_form you need to specify like
#selected_options = SelectedOptionModel.new(params)
into your controller
then it passes into View.
if you don't have any model you can use form_tag
like this:
<%= form_tag("/search", method: "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
this will create html form like this:
<form accept-charset="UTF-8" action="/search" method="get">
<input name="utf8" type="hidden" value="✓" />
<label for="q">Search for:</label>
<input id="q" name="q" type="text" />
<input name="commit" type="submit" value="Search" />
</form>
When I try to create a category by using Ajax I get a strange behavior with my error message.
Right now I have my error message appearing like this:
My create.js.erb and new.js.erb both have the same code which is just this line:
$(".cc-form").html("<%= escape_javascript(render(:partial => 'categories/form', locals: { category: #category })) %>");
This is my category form:
<%= form_for(#category, :remote => true, :html => { :class => "add-form", :id => "cform" }) do |f| %>
<fieldset>
<p>
<%= f.label :name, "Category Name *" %>
<br />
<%= f.text_field :name %>
</p>
<div class="form-actions">
<%= f.submit "Create" %>
</div>
</fieldset>
Here is the code to enable custom error HTML:
# application.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
errors = Array(instance.error_message).join(',')
%(#{html_tag}<span class="validation-error"> #{errors}</span>).html_safe
end
Then the HTML itself along with the error HTML:
<p>
<label for="category_name">Category Name *</label><span class="validation-error"> can't be blank</span>
<br>
<input id="category_name" name="category[name]" size="30" type="text" value=""><span class="validation-error"> can't be blank</span>
</p>
I only want the error message next to the label and not the right side of the input. How would I do this? The format is tricky for me when I look at it.
Thanks.
I guess you use field_error_proc badly, because it's good to wrap the input field into element with special class. Field_error_proc tags both the label and input tag with field_with_error by default since the refered object (:name that means category.name having the errors array) is the same. It's not a defect, because it's good for changing your label's color to red in this case. I checked the Rails code (actionpack/lib/action_view/helpers/tags/label.rb) and you can't turn this behavior off for labels (it can be a feature request), so I guess there's only one solution for your problem if you use plain html for labels.
I have two solutions now for your problem:
Instead of
<%= f.label :name, "Category Name *" %>
use
<label for="category_name">Category Name *</label>
in your view.
It's not too nice, but you can use f.label if you make form .label .validation-error { display: none } in your stylesheet file. I know it's just a workaround, but if f.label is necessary, then I don't know better solution.
You have two of these <span> tags in the page:
<span class="validation-error"> can't be blank</span>
EDIT:
Okay, it looks like both the label and the input need to be wrapped with a custom error. Here are a couple of links:
http://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t
https://gist.github.com/1464315
While registering for openstreetmap, on the terms page, I noticed that clicking the labels didn't check the radio buttons associated with them. Here is the html:
<!-- legale is GB -->
<form action="/user/terms" method="post">
<p>
Please select your country of residence:
<input id="legale_fr" name="legale"
onchange="Element.update("contributorTerms", "<img alt=\"Searching\" src=\"/images/searching.gif?1313181320\" />");; new Ajax.Request('/user/terms?legale=FR', {asynchronous:true, evalScripts:true})"
type="radio" value="FR" />
<label for="legale_FR">France</label>
<input id="legale_it" name="legale" ... type="radio" value="IT" />
<label for="legale_IT">Italy</label>
<input checked="checked"
id="legale_gb" name="legale" ... type="radio" value="GB" />
<label for="legale_GB">Rest of the world</label>
</p>
</form>
As you can see the checkbox id="legale_gb" doesn't match the label for="legale_GB".
Now openstreetmap's website is actually open source so we can read the terms.html.erb:
<!-- legale is <%= #legale %> -->
<% form_tag :action => 'terms' do %>
<p>
<%= t 'user.terms.legale_select' %>
<% [['france', 'FR'], ['italy', 'IT'], ['rest_of_world', 'GB']].each do |name,legale| %>
<%=
radio_button_tag 'legale', legale, #legale == legale,
:onchange => remote_function(
:before => update_page do |page|
page.replace_html 'contributorTerms', image_tag('searching.gif')
end,
:url => {:legale => legale}
)
%>
<%= label_tag "legale_#{legale}", t('user.terms.legale_names.' + name) %>
<% end %>
</p>
<% end %>
I'm a rails newbie, but I can't see anything there that lowercases the id of the radio button tag. What's more, even when I look at the source of radio_button_tag, sanitize_to_id I can't see where this is coming from.
Anyone got any idea what's causing this?
Edit Swapped out label for radio in my description according to answer from
2 things:
Wrong tag, the offender is radio_button_tag (it's capped as expected in the label).
Seems like you're linking to the wrong Rails. According to this project's environment.rb, it's using Rails 2.3.14. If you look at radio_button_tag for that release, you'll see the culprit.
# our pretty tag value is downcased on line 318
pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase
# although the pretty name is not, oddly
pretty_name = name.to_s.gsub(/\[/, "_").gsub(/\]/, "")
# then the two are combined into the HTML id
html_options = { ..., "id" => "#{pretty_name}_#{pretty_tag_value}", ... }
I would like to use the form_for helper multiple times for the same model in the same page. But the input fields use the same ID attribute (in the HTML), so clicking on the label of a field in another form will select the same input in the first form.
Is there a solution besides settings all attributes manually via :for => "title_#{item.id}" and :id => "title_#{item.id}"?
Using Rails 3.0.9
You can use :namespace => 'some_unique_prefix' option. In contrast to :index, this will not change the value used in the name attribute.
It's also possible to use an array, e.g. when you have nested forms or different forms that happen to have some fields in common: :namespace => [#product.id, tag.id] or :namespace => [:product, #product.id]
I found the answer myself, one can pass a :index option to form_for. That string will be used in the id and for attributes:
<%= form_for #person, :index => #person.id do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
will parse
<form accept-charset="UTF-8" action="/person/11" class="edit_person" id="edit_person_11" method="post">
<!-- Hidden div for csrf removed -->
<label for="person_11_name">Name</label>
<input id="person_11_name" name="person[11][name]" size="30" type="text" />
<input name="commit" type="submit" value="Update Person" />
</form>
Notice it'll change the name of the inputs as well.
I believe you can add this param:
:html => { :id => 'id_i_want' }
I would like to create a login field everywhere on the top of my page, so I've add a :
in application.html.erb :
<%= render :partial => 'sessions/new' %>
in .../views/sessions/_new.html.erb
<%= form_tag do %>
<div>
<label for="name">Email :</label>
<%= text_field_tag :name, params[:name] %>
<label for="password">Mot de passe :</label>
<%= password_field_tag :password, params[:password] %>
</div>
<div>
<%= submit_tag "Connection" %>
</div>
</fieldset>
But it's work only if I am in a sessions controller when I test it in my browser,
I think that :
<%= submit_tag "Connection" %>
refers to his current controller (sessions) that's why it's doesn't work in ads/index for exemple but do its job in sessions/index.
What can I do ?
Do I have to specify the controller in the submit_tag ?
Thanks a lot :)
You need to tell the form tag the url that the form should submit to. Maybe by default it submits to the current action or something? You should never rely on the default whatever it is.
Read the api
http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M002551&name=form_tag
oh and btw the submit tag is just a button, it doesn't have anything to do with why the form does or doesn't work. There's a lot of confusion among rails novices about forms - a lot of people don't really understand how forms work. Before using any rails helpers at all, i'd strongly recommend making your form in pure html. That way you will understand what is actually going on, and the form helpers will be just that, ie "things that help you to do something more quickly" rather than being these magical things that leave you totally clueless when they don't do what you expect.
You need to specify the controller but on the form_tag not the submit_tag
e.g. <%= form_tag :controller => 'sessions', :action => 'new' %>