rails 4 form submit as div, validation not working - ruby-on-rails

I have a problem when trying to submit a form with a div (instead of a f.submit button)
<%= form_for #user, url: {action: "submit_user"}, html: {id: "user_submit", class: "form"}, :method => "post" do |f| %>
<%= f.text_field :first name, :required => true, :placeholder => 'first name', :autocomplete => :off %>
<%= f.text_field :last name, :required => true, :placeholder => 'last name', :autocomplete => :off %>
<div id="submituser" class="some very fancy css here" onclick = "document.forms['user_submit'].submit();">
<% end %>
The problem is that the form is sent, but without the validations (causing it to send blank first and last name if nothing is entered)
note that when using
<% f.submit "submit" %>
validations do work.
Thanks

I guess document.forms['user_submit'].submit(); does not trigger the submit event, so You have to launch validation manually. But what is the point of using div instead of button? You could style a button with some very fancy css here too. OR make a 'hidden' submit button and add onclick = "document.form.button.click()" to div :-)

Found my answer here:
Difference between handling $(“form”).submit or an click event?
And i quote #Giovanni Sferro:
The click callback is called only if the user actually click on the submit button. But there are cases in which you would submit the form automatically by javascript, in that case the click callback is not fired while the submit callback is. I would recommend to use always the submit for validation and intrinsic action of the form, while using the click callback for animation or other things related to the action of clicking on the button.
so my (working) code looks like this:
<div id="submituser" class="some very fancy css here" onclick = '$("#user_submit input[type=\"submit\"]").click();'>

Related

validation for form_tag in ruby on rails

I am working on Ruby 2 and rails 4. I want to add html validation 'required' inside the form_tag of Rails.My codes are below.
<%= form_tag file_download_contacts_path, :method => :post, :id => 'contact-form', :class => 'special' do |f| %>
<div><%= label_tag :Name %><br />
<%= text_field_tag "contact[name]" , nil, placeholder: "Your Name" %></div>
<div><%= label_tag :Email %><br />
<%= email_field_tag "contact[email]" , nil, placeholder: "your#mail.com" %></div>
<div><%= label_tag :Mobile %><br />
<%= telephone_field_tag "contact[phone]" , nil, placeholder: "Your Contact No" %></div>
<div><br /><%= button_tag 'Submit' %></div>
<% end %>
click on submit button it directly goes to file_download_contacts_path page though the text areas are blank. How can I prevent this? In Html we can use 'required'. Please help me if any body can. Thank you.
Something like this should help you
$(document).ready(function () {
$(“#contact-form”).validate({
debug: true,
rules: {
“contact[email]“: {required: true, email: true},
“contact[name]“: {required: true, name: true},
“contact[phone]“: {required: true, phone: true}
}
});
});
Source
Rails cannot do any form validation before it's submitted, since the validation needs to happen in the client (and rails is of course server-side). You need to use javascript. If you google "javascript form validation" you will see a tremendous amount of information.
jQuery is a very popular javascript library which has various form validation plugins, google and have a look.
Note: Above answers are all correct and perfect with simple explanation, but in case if you want to show an actual error message to the user, (In case you want to a complex validation), then below answer is for you,
Here In my scenario I have two checkbox in my form, and I want to validate that at least one checkbox should be clicked, if not then I will show a error message to the user.
<%= form_tag( add_to_telegram_path, method: :post, id: 'add-to-telegram-form') do |t| %>
Select channel
<%= check_box_tag "channel_names[]", id: 'channel_1'%> Channel 1
<%= check_box_tag "channel_names[]", id: 'channel_2'%> Channel 2
<%= button_tag "Send", :class => 'btn btn-success', id: 'add-to-telegram-btn', onclick: "validTelegram()" %>
<%end%>
Then in JS,
function validTelegram() {
event.preventDefault();
var checkboxes = Array.from(document.getElementsByName("channel_names[]"));
if(checkboxes.reduce((acc, curr) => acc || curr.checked, false)){
$('#add-to-telegram-form').submit();
} else {
//swal('Error','Please select atleast one channel!','warning');
alert('Some error!')
}
}
I called a JS function on the submit click of form_tag, (If you are using sibmit_tag replace it with button_tag)
I have prevented default behaviour of the submit button
Then I started to get the elements by its Id/Class or by Name, and checked what ever I want to do in the JS, and then based on my validation Either I am calling submit() on the form ID, or showing the error message.
Note: For showing error message I have used Sweet alert, you can stick with the alert();, but in case If you are looking for better UI, then uncomment my swal() code in JS and comment out alert();
You can read more about Sweet Alert PopUp

In Ruby on Rails, how can I get radio button state, true or false, to put in a label?

My form has two radio buttons, public and private:
<div class='review-form'>
<%= simple_form_for(#review) do |f| %>
# input boxes for current_user to put text here
#'public' radio button, checked by default, class is for css
<%= f.radio_button :visible, "true" , :class => "share_button" %>
#'private' radio button, class is for css
<%= f.radio_button :visible, "false", :class => "keep_private_button" %>
#user can cancel
<%= link_to I18n.t('write_review.cancel_button'), landing_page,
:class => 'btn' %>
#user can submit
<%= f.button :submit, I18n.t('write_review.submit_button'),
:class => 'btn btn-primary' %>
How can I determine if the radio button in each review is true or false, so I can use it after the review has been saved in my app?
For example, something like:
<% if #review.radio_button.value = true %>
<%= label_tag("This review is public") %>
<% end %>
<% if #review.radio_button.value = false %>
<%= label_tag("This review is private") %>
<% end %>
Where is "elsewhere?" Is this after the user has saved? If so, then you should just be able to say:
if #review.visible?
or
if review.visible?
depending on the scope of your variable.
If, by "elsewhere," you mean on the same page, then you'll need some clever javascript. You can use something like jQuery to help here, but essentially you'll just want a listener on those radio buttons that, on click, fires off to a javascript function that evaluates the radio buttons, then updates the text of a div on the page appropriately. It's a very common pattern that I'll leave as an exercise for the alert reader, as, again, I'm not sure exactly what you mean by "elsewhere" -- from your question, though, I'm guessing it's the former (after the user has saved).
Hope that helps!

Multiple submit actions with formtastic

I'm trying to setup a formtastic form with multiple submit actions, following along with Railscast #38. What's the equivalent of this in Formtastic?
<%= submit_tag 'Create' %>
<%= submit_tag 'Preview', :name => 'preview_button' %>
This post gave me hope, but it looks like commit_button was deprecated in 2.1.0, and I can't seem to figure out the new syntax.
Here's my code for what it's worth. I'd like each submit button to go to the same controller, where I will handle them differently:
# Use prepaid credits to checkout
<%= f.action :submit, :as => :button, :label => "Order Critique (1 credit will be spent)", :button_html => { :class => "btn btn-primary", :disable_with => 'Processing...' } %>
# Use credit card to checkout
<%= f.action :submit, :as => :button, :label => "Order Critique ($10)", :button_html => { :class => "btn btn-primary", :disable_with => 'Processing...' } %>
TL;DR: If you use javascript to submit a form, it won't carry over the submit button's name in the commit params.
My problem ended up being the code used in Railscasts Episode #288. This CoffeeScript function gets fired when you submit the form, after the Stripe token checks out:
handleStripeResponse: (status, response) ->
if status == 200
$("#stripe_card_token").val(response.id)
$("#my_form_id")[0].submit()
else
# other stuff
Since javascript is doing the form submission with $("#my_form_id")[0].submit(), the name parameter won't be carried over in the commit params.
My solution was to add a "clicked" attribute to the button that gets clicked...
$('form_input[type=submit]').click ->
$('input[type=submit]', $(this).parents('form')).removeAttr('clicked')
$(this).attr('clicked', 'true')
..and then grab the id attribute of the clicked button populate a hidden field with it:
submitter = $("input[type=submit].clicked=true").attr("id")
I don't particularly like this solution. It feels like my js knows too much, and I don't like depending on js for this sort of thing. Any criticism or better solutions are certainly welcome :)

Ruby on rails pass value of hyper link from link_to tag

I have the following code in my view:
<%= form_for :command_selected, :method => "get", :url => {:action => "command_domain_selected"} do |f| %>
<a> <%= link_to "Make Deployment", {:controller=>"authorization", :action => 'command_domain_selected',:id=>'make_deployment'}, :remote=> true %><br /></a>
<%= f.radio_button :domain, '1dev' %> <%= label :domain, '1dev'%><br />
<%= f.radio_button :domain, '2dev' %> <%= label :domain, '2dev'%><br />
<script type=text/javascript>
$('a').click(function(){ $('form').submit(); return false; });
</script>
<%end%>
When i click on the "Make Deployment" link in the above code, only the selected radio button is passed as the parameter to the command_domain_selected action in the controller. Please let me know how to pass the value of the hyperlink too.
Thank you
I added the following code too:
<%= link_to 'Make Deployment', "#", :onclick=>"$('.search_form').submit()" , :id => 'make_deployment'%>
But the parameters that are being passed are just the radio button values and not the hyperlink value
I'm with Yuri. Use a form (method get and it will all go in the URL). Then just style the button to look like a link if you're that fussed!
Otherwise if you must continue with the hideousness add a hidden_field with the extra param you want to submit. Its not passing the hyperlink params because that has nothing to do with a form (unlike a submit button which does)

2 submit buttons in a form

I have a question about forms. I have a fairly standard form that saves a post (called an eReport in my app) with a title and body. The table also has a "published" field, which is boolean. The saved eReport only shows on the public site if this field is set to true, with false being the default.
Rather than the default check box, I would like to display two buttons at the end of the form: a "Publish Now" button and a "Save as Draft" button. If the user presses the former, the published field would be set to true. If the latter, then false. In PHP, I used to display 2 submit fields with different name values, then handle the input with an if/else statement to determine the proper SQL query to build. In Rails, I'm assuming I would place this logic in the controller, under the appropriate action, but I'm not sure how to manipulate the name or id values of buttons.
For the record, I'm using Formtastic, but if someone could show me how to do this with the default Rails form tags, that's OK too. Here's the code for my form as it stands right now:
<% semantic_form_for #ereport do |form| %>
<% form.inputs do %>
<%= form.input :title %>
<%= form.input :body %>
<% end %>
<% form.buttons do %>
<%= form.commit_button :label => "Publish Now" %>
<%= form.commit_button :label => "Save as Draft" %>
<% end %>
<% end %>
Thanks in advance for the help!
I don't know about formtastic, but with the default rails form builder, you could do it like this:
<%= form.submit "Save with option A", :name => "save_option_a" %>
<%= form.submit "Save with option B", :name => "save_option_b" %>
Then in the controller, you can pick those up in params:
if params[:save_option_a]
# do stuff
end
in addition to #iddlefingers answer, here is a view of the log of the application (striping some useless params due to explanation purposes)
Parameters: {"utf8"=>"✓", ..., "comentar"=>"Confirmar"}
where we can see that comentar is the name of the parameter, and "Confirmar" is it's value, which is the button's text too.
which was obtained by submit_tag "Confirmar", :name => 'comentar'
So in general you could have (if you want to reduce the number of params you are working with) several submit_tag "onevalue", :name => 'SAMEname', submit_tag "othervalue", :name => 'SAMEname'...
and retrieve them in your controller
if params[:SAMEname] == "onevalue"
# do stuff
elsif params[:SAMEname] == "othervalue"
#do different stuff
end
I think you need to use jQuery.
You can bind the button click event and submit the form for specified location.

Resources