I have integrated google and facebook omniauth in my rails application. The signup and signin works great. But, I also have a form which should be submitted along with omniauth, so that I can access the form content as parameters.
This is the piece of code:
%section#hero.hero-blk
.container
.intro.text-center
%h1 Ask Question Instantly
%h3.hero-tagline Ask anonymously anytime
.row
.col-md-6
.ask-question
%h2.text-center Talk to us
%form{method: 'post', action: new_forward_questions_path}
=hidden_field_tag :authenticity_token, form_authenticity_token
%textarea.form-control{:autofocus => "", :cols => "20", :id => "question-content", :name => "content", :placeholder => "Describe your question on relationship, marriage. Please type atleast 50 characters", :rows => "7"}
%div#chars-left
%input{type: 'hidden', name: 'source', value: 'home'}
.text-center
%button#ask-button-index.glow-button.btn.btn-primary{type: 'submit'}
%img{:alt => "", :src => image_path("incognito-new.svg")}/
Ask Anonymously
.modal-body
#dialog-loading-icon.collapse
%p
Please wait, submitting your question
=image_tag "ripple.gif"
= simple_form_for #question do |f|
= f.input :content, as: :hidden, input_html: {id: 'hidden_question_content'}
- if current_user.nil? or current_user.asker.nil? or current_user.asker.new_record?
.social-sign-in.visitor-oauth.text-center
= link_to "Sign up with Gmail", user_google_oauth2_omniauth_authorize_path(#question), class: "zocial gmail"
= link_to "Sign up with Facebook", user_facebook_omniauth_authorize_path, class: "zocial facebook"
Below is the screenshot of html generated As you can see the modal form gets populated with "Oauth Oauth Oauth" This is the content which I am writing inside the textarea and when I click on the button the modal pops up and has the same content I typed:
I have tried passing #question here but nothing gets passed. In controller I am trying to access the params through request.env["omniauth.params"] but it is always blank.
How can I access or pass this content parameter to omniauth and access it in controller?
You don't need a form here since the content is a hidden input. You can pass it as extra params to link_to like below
= link_to "Sign up with Gmail", user_google_oauth2_omniauth_authorize_path(content: "Your desired value"), class: "zocial gmail"
and look for content in request.env["omniauth.params"]
Update:
The only way I can think of by appending the value of content to the url on a click event using Javascript of Jquery
<script type="text/javascript">
$(".gmail, .facebook").click(function(){
var hidden_content = $("#hidden_question_content").val();
var url = $(this).attr('href');
window.location.href = "url?content="+hidden_content;
});
</script>
Related
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();'>
I have a Ruby on Rails app.I am using Devise for authentication.I have set a 30 minutes timeout for the users which auto logs out the users on 30 minutes of browser inactivity.The problem I am facing is that when the session logs out on timeout after 30 minutes,it takes to the login screen and the browser saved email address and password shows up in the login text boxes.But on clicking the login button it doesn't logs me into the application.When the page reloads after the login fail,I can login as usual.
When i checked the problem further,I found that the email address and password values are nil even though it shows up on the browser screen.
The Login form code is given below:
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name,:role => "super_admin")) do |f| %>
<%= f.email_field :email, :placeholder => "EMAIL", :data => { :'placeholder' => 'EMAIL'}, :class => 'with_holder' %>
<%= f.password_field :password, :placeholder => "PASSWORD", :class => 'disablecopypaste with_holder' , :data => { :'placeholder' => 'PASSWORD'}%>
<% if devise_mapping.rememberable? -%>
<%= f.check_box :remember_me %>
<% end -%>
<a id="save_post" href="javascript:void(0);">LOG IN</a>
<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
<%= link_to "FORGOT PASSWORD?", new_password_path(resource_name, :role => 'super_admin') %>
<% end -%>
Am I doing anything wrong here?it would be really helpful if anyone can help me with this problem
If you see Email and Password on your login form when reloading the page, it is the browser behavior, not your Devise. It could be because your input has autocomplete attribute and you have selected to Save Password on your browser. Try setting autocomplete=off on your input to see if it helps
At Last found out the issue..The issue was in submitting the form,the form was not being submitted in usual method.It as being submitted from a JS method which catches the click event of <a id="save_post" href="javascript:void(0);">LOG IN</a> and submits the POST action of its parent form.
The issue was that the form was not being Loaded at the time of the click and hence it was returning empty strings for the email and password fields.Once I changed the method of submitting the form to the usual way ie putting a form submit button
<%= f.submit "LOG IN", :id => "login_submit" %>
it works fine
As the button is also an element inside the form,it will only get loaded once other elemts inside the form get loaded,hence it wont return empty strings on clicking the button.
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
I'm trying to implement the password reset functionality in an app, using Devise. I'm at a point where the "forgot password" link works (in that it sends the email), and the email contains the link to "Change my password".
The change password link works and sends you to a form (at the URL http://localhost:3000/users/password/edit?reset_password_token=c7cKb4hMhSLRs72n9dYj) asking for the new password (and to confirm it), but after typing in a new password and clicking "Chang my password", it redirects to localhost:3000/users/password and says "Please review the problems below:" and presents a from with one field for Email, and a button for "Send password reset instructions". This is, of course, the form for submitting your email to get password reset instructions, but it also has an error notice of "can't be blank", as if someone clicked the button with the field empty.
I used a tutorial to configure ActionMailer to send the email, which I thought was going to be the most difficult part of this process, but now I can't figure out why the form to change one's password is not working.
I'm very new to Rails, and this is my first time working with Devise and ActionMailer, so I apologize if I haven't included some needed information. Just let me know and I can add anything that helps.
Thanks.
Ok, so with the help of someone at a Rails meeting tonight, I found out what the problem was. It didn't really have anything to do with the controllers or routes, but rather I had caused the bug by incorrectly adding some code to the form. Here's the corrected code for my form:
<h2>Change your password</h2>
<%= simple_form_for(resource, :as => resource_name, :url => password_path(resource_name),
html: { method: :put, class: "pure-form pure-form-stacked" }) do |f| %>
<%= f.error_notification %>
<%= f.hidden_field :reset_password_token %>
<%= f.input :password, label: "New password", autofocus: true, required: true %>
<%= f.input :password_confirmation, label: "Confirm new password", required: true %>
<div><%= f.submit "Change my password", class: "pure-button" %></div>
<% end %>
<%= render "devise/shared/links" %>
My problem was that instead of including the class: "pure-form pure-form-stacked line as a second key/value pair into html: {}, I had a second html: {} line.
In case that's not clear, I had this:
html: { method: :put },
html: { class: "pure-form pure-form-stacked" }
instead of this:
html: { method: :put, class: "pure-form pure-form-stacked" }
and for some reason, in the first version, only the second html: {} was being submitted with the form, so it didn't get processed as a put request.
I have run into a bit of a problem and a head scratcher, as I'm not sure whether what I want to do is even possible with RoR.
A bit of background info: I have an app with several controllers... and would like to work with 2 of them for this modal example. The first is a users_controller and the other is a recommendations_controller.
Here is what I'm trying to do: In the user index view I have a lists of posts. Each post has a recommend button. If a user clicks it he/she is sent to the recommendation index page, and can search and find a user he/she would like to share the post with. The reason I have it set up this way is because the Recommendation model creates the recommend relationship.
I would like like it so when the user clicks the recommend button on the User index page, a modal appears (one that accesses the recommendation controller) and the user can search for the user he/she would like to share the post with. Basically, I want to know whether it's possible to access the Recommendation controller via the User controller's index view page.
If it's not, is there a work around? I can post the code I have if it's helpful, but I'm not sure that would help in this case--as I'm trying to see whether it's even possible to do what I'm trying to do.
Thank you!
More Details:
recommendations_controller:
def index
#user = Search.find_users(params[:name], current_profile)
respond_to do |format|
format.html
format.js
end
end
index.js.haml (located in the view/recommendations folder)
:plain
$(#my-modal).show();
index.html.haml (located in the view/recommendations folder)
= form_tag post_recommendations_url, :method => "get" do
= text_field_tag :name, '', :class => "span12", :placeholder => "Please enter the name of the users you would like to share this post with."
%center
= submit_tag "Search", :class => "btn btn-primary"
index.html.haml (located in the view/posts folder)
%a{:href => "#{post_recommendations_path(post)}", :remote => true}
%i.icon-share.icon-large
Recommend Post
#my-modal.modal.hide.fade
.modal-header
%a.close{"data-dismiss" => "modal"} ×
%h6 This is a header
.modal-body
%p This is where I would like the contents of the index.html.haml file, located in the view/recommendations folder to appear.
Part 2: Displaying the search results inside the modal/partial
Matzi, at the moment, a user clicks a link near the post they want to recommend. This link renders the modal with a partial (_recommendation.html.haml) inside of it.
This partial (now inside the modal) contains the search form_tag and the code to render all the users that match the search results. Unfortunately, when I try to run a search by entering a name and clicking the search button (again, now located inside of the modal) it takes me to the following url instead of rendering the results inside the modal.
http://localhost:3000/posts/2/recommendations?utf8=%E2%9C%93&name=Test&commit=Search
here is what my updated index.html.haml (located in the view/posts folder) looks like:
= link_to 'Recommend Post', post_recommendations_path(post), :remote => true, "data-toggle" => "modal"
#my-modal.modal.hide
.modal-header
%a.close{"data-dismiss" => "modal"} ×
%h6
%i.icon-share.icon-large
Recommend Post
.modal-body
#modal-rec-body
%p *this is where _recommendation.html.haml is rendered*
updated index.js.haml
:plain
$("#modal-rec-body").html("#{escape_javascript(render('recommendations/recommendation'))}");
$('#my-modal').modal({
keyboard: true,
show: true
});
_recommendation.html.haml
.span12
= form_tag post_recommendations_path, :method => "get" do
= text_field_tag :name, '', :class => "span12", :placeholder => "Please enter the name of the user you would like to share this post with.", :style => "max-width:520px;"
%center
= submit_tag "Search", :class => "btn btn-primary", :remote => "true"
- #user.each do |i|
- unless current_profile == i
.row-fluid
.span6
.row-fluid
.well{:style => "margin-left:0px;"}
.row-fluid
.span2
=image_tag i.avatar(:bio), :class=> "sidebar_avatar"
.span6
%dl{:style => "margin:0px"}
%dt
%i.icon-user
Name
%dd= i.name
%dt
%i.icon-map-marker
Location
%dd= i.location
.span4
- form_for :recommendation do |r|
= r.hidden_field :friend_id, :value => i.account.id
= r.submit "Send Recommendation", :class => "btn btn-primary"
Problem: Unfortunately it seems that when I click the submit (search) button inside the modal instead of rendering the results inside the modal it re-directs the browser to the post_recommendations_path (posts/post.id/recommendations). I would like to display the search results inside the modal without having it redirect to the post recommendations path.
As always, thank you so much! I'm extremely grateful for your help--and I've gotten a much better grasp for AJAX thanks to you. Thank you!
Of course you can do this, but it needs some ajax magic.
First of all, you need to create an action, responding to .js requests, in the recommendation controller. It is done so far in your update. But, your .js is not quite right. The problem is that you render the modal form from the post view, but propably in post controller you dont have the right fields. I recommend the following .js.erb:
$("#modal-body").html(<%= escape_javascript render(:partial => 'recommendations/index')%>);
$("#my-modal").show();
This fills the modal with the form. The next step is to do a remote request from this form. Modify your posts/index the following way:
= form_tag post_recommendations_url, :remote => true, :method => "get" do
= text_field_tag :name, '', :class => "span12", :placeholder => "Please enter the name of the users you would like to share this post with."
%center
= submit_tag "Search", :class => "btn btn-primary"
The difference is the :remote => true tag, this sends an ajax request to your controller, so you must prepare for .js and .html response (in case of no JS on client). The .js should hide the modal form, and may refresh the original page, the html may redirect you back to the post.
Part 2:
The problem is the :remote part. It needs to be part of the form's definition, not the submit button's. My mistake.
I found this guide now, it seems quite good.
I hope it helps! Ask if something is not clear.