remote:true - submit button works but this.form.submit not - ruby-on-rails-6

I have form_with form, i want to send the data by Ajax remote:true request.
What works:
- when i click submit button, everything is fine, i receive an alertbox (this is what i've put in my .js.erb file)
What doesn't work:
- i have search form with many fields, i want to submit form when any of the fields is changed. Without ajax it works fine, the code "onchange="this.form.submit();" works perfectly.
But when i use Ajax, this.form.submit() is still reloading the page.
Expected results:
- When i change any field, it will send data without reloading page. If it is possible, i want to avoid regular Ajax and use remote:true form_with method.
What i've tried
- i've used many jquery variations f.e.:
this.form.submit();
$('#id_of_submit_button').click(); // it works but i want to make it without using submit button
$(this).closest("form").submit();
My code:
show.html.erb
<%= form_with(url: "/cars/" + #car.id.to_s + "#formcarsection", id: "filterform", remote: true, method: "get") do |f| %>
<%= f.text_field :vin, onchange: "this.form.submit();", class: "form-control" %>
<input type="submit" id="submitbtn" value="Count" class="car__submit-btn">
<%= end %>
cars_controller.html.erb
def show
respond_to do |format|
format.html
format.js { render 'cars/show.js.erb' }
end
end
cars/show.js.erb
alert("Hello! I am an alert box!!");

The remote: true needs to be added to each field.
<%= f.text_field :vin, data: { url: "/cars/" + #car.id.to_s + "#formcarsection", remote: true, class: "form-control" } %>

Related

Stimulus Reflex drop down with selectize.js

I have a search form for an index page following the tabular demo. It works perfectly. The list I have that I want to filter by is quite long and I wanted to make it searchable so I added selectize.js, that piece also works just fine.
The problem is they don't work together. After selecting an item now it doesn't fire off the call to TabularReflex#search to filter the results.
#app/views/foo.index.html
<%= form_with scope: :search, url: '/search', html: { "data-reflex" =>"debounced:change->TabularReflex#search"} do |f| %>
<%= f.select :foo, options_for_select(#search.foo), {include_blank: 'Select a Foo'}, {class: 'selectize'} %>
<% end %>

Rails: Embed child in submit_tag

I have this form:
= form_tag(path, name: "name") do |f|
= hidden_field_tag "abc", content
= submit_tag "" do
%i.icon.ion-android-sync
As you can see, I am trying to put an Ionicon inside the Form Submit tag.
I've tried a bunch of ways, none of which worked.
With the given example I get an empty button with an approximate width of 3px.
Is it possible to embed a child in a submit_tag? If, how would you go about doing so?
Thanks a lot for each answer!
The short answer is "no". However, you can make a button with type of "submit" that'll do the same thing and allow you to put content in it:
%button{type: "submit"}
%i.icon.ion-android-sync
No the Rails submit helper won't let you do that.
I use a custom submit helper in my app :
# Render a form submit button
# === Params
# +value+:: Value of the input/commit button, used for route constraints
# +text+:: Text for the button
# +:html_options+::
def submit(value=nil, text=nil, html_options={})
text ||= 'Submit'
html_options[:name] ||= 'commit'
html_options[:type] = 'submit'
html_options[:data] ||= {}
html_options[:data][:disable_with] ||= 'Please wait'
html_options[:autocomplete] = "off" # https://github.com/rails/jquery-ujs/issues/357
content_tag(:div, class: 'form-submit-wrapper') do
button_tag(html_options){ block_given? ? yield : text }
end
end
You can just pass whatever HTML you want in a block (sorry this is ERB, I'm not really familiar with HAML)
<%= submit do %>
<i class="icon ion-android-sync"></i>
<% end %>
The first two params are only helpful if you have several submit buttons for your form
<%= submit('preview_action', 'Preview result') do %>
<i class="icon ion-android-sync"></i>
<% end %>
<%= submit('really_do_action', 'Do it for real') do %>
<i class="icon ion-android-sync"></i>
<% end %>

Rails 4 button_to using helper improper redirection

I am building an index for one of my models. Instead of the usual table, I want to have two combo-boxes: one for selecting the object, the other for selecting the method (either edit or destroy). Upon clicking the submit button, I should be redirected to the appropriate method reference (e.g. admin_users/1/edit or admin_users/17/destroy). I have written a helper that constructs the url reference, but for some reason it does not work. when I use button_to I get redirected to the create method, when I use button_tag nothing works. Any ideas?
view code:
<%= form_tag do %>
<p id="notice"><%= flash[:notice] %></p>
<h1>Listing admin_users</h1>
<p><strong>select admin user</strong></p>
<%= select_tag(#req_id, options_from_collection_for_select(#admin_users, :id, :login)) %>
<br/>
<p><strong>select action</strong></p>
<%= select_tag(#oper, options_for_select([['edit'],['destroy']])) %>
<br/>
<%=button_tag 'go go!', get_path(#req_id,#oper) %>
<% end %>
helper code:
module AdminUsersHelper
def get_path(req_id,oper)
a=[req_id, oper].join("/")
["admin_users", a].join("/")
end
end
The default method for a form submit is POST. You'll need to change the method accordingly.
<%= form_tag( '/users/confirm', method: :get ) %>
May I suggest submitting with Javascript? You'll have a more dynamic control over the method of the submission. Take a look Here
so, eventually I went on the javascript solution, just as #Hassanin Ahmed suggested. Thanks for Helping!
<%= form_tag('/admin_users', id: "admin_users_menu") do %>
[...]
<font size=4>
<u>select user:</u>
</font>
<br>
<br>
<select id="admin_user_id" name="admin_user[id]">
<%= options_for_select #admin_users.collect{|user| [user.login, user.id]} %>
</select>
<br>
<br>
<font size=4> <u>select option:</u></font><br><br>
<input type="radio" checked name="select_op" value= "edit" > edit
<br>
<br>
<input type="radio" name="select_op" value= "delete" > delete
<br>
<br>
<%= submit_tag "go" %>
<br>
<br>
<% end %>
<script>
$(function (){
$("#admin_users_menu").submit(function() {return direct_me() })
})
function direct_me(){
//getting the admin_user id
var au_id=$('select').val()
//getting the desired method
var op=$('input[name=select_op]:radio:checked').val()
//making the default url
var u="admin_users/"+au_id
var f=$("form")
if(op=='edit'){
u=u+"/edit"
f.attr("method","GET")
}
else if(op=='delete'){
f.attr("method","POST")
f.append("<input type='hidden' name='_method' value='delete'>");
}
f.attr("action",u)
if(op=='delete') return confirm("Are you sure?")
}
</script>

Capybara rspec inconsistent behaviour when trying to click buttons / submit forms

This is something that leads me to waste hours and I wish I knew why. I've found lots of examples (not all answered) where forms are not being submitted, it works on a webpage, but not in capybara. things like find/xpath work in the irb.
web page
file box with a upload button, attaching the file works (i'm using poltergeist render to see that file name is attached)
debugging / options tried
find () works e.g. in irb it returns an object: Capybara Element tag=input
if i attempt to "visit '' it returns {"status"=>"fail", "click"=>{"x"=>124, "y"=>283}} [nothing in the log that action called. DEFINITELY works in development environment]
click_on 'Upload' fails: {"status"=>"fail", "click"=>{"x"=>124, "y"=>283}}
find_button('Upload').click: {"status"=>"fail", "click"=>{"x"=>124, "y"=>283}}
find("#upload_bill_button1").trigger("click"): returns "click"
i have tried exec_script of javascript checkBill() . page.execute_script('checkBill()'): returns nil
find(:css, '#upload_bill_button1').click . returns: {"x"=>124, "y"=>282}
nothing in the logs to show the action is being completed
i have
js=>true as its a javascript submit (does a test first, code below).
made sure all ids are unique
capybara::DSL added
system setup
Mac ox X
poltergeist (working for all my other tests)
ruby 1.9.3
phantom 1.9.2
is there further debug to figure out the problem ? other logs i'm missing?
any guidance much appreciated
<div class="row">
<div class="large-10 columns" >
<%=form_tag( "/upload_bill", :method=>:post, :multipart => true, :id => "form_upload1") do -%>
<fieldset>
<legend>Select your bill file</legend>
<%=file_field_tag 'bill', :onclick => "checkBill()" -%>
<div class="large-2 columns" >
<!-- TODO: make the browse button the zurb class type -->
<%- if params[:action].eql?( 'index')%>
<%=submit_tag "Upload", :onclick => "checkBill();return false;", :id => "upload_bill_button1", :class => "button postfix" -%>
<% end %>
</div>
</fieldset>
<% end %>
</div>
</div>
<%- if params[:action].eql?('import_bill')%>
<%=link_to (image_tag "/images/btn-uploadbill.png"), "#", :onclick=>"checkBill();return false;", :id => "upload_bill_button2" -%>
<%=link_to (image_tag "/images/btn-cancel.png"), root_path %>
<%- end %>
<script type="text/javascript">
function checkBill(){
var bill = $("#bill").val();
if(bill.split('.').reverse()[0]=="csv"||bill.split('.').reverse()[0]=="pdf"||bill.split('.').reverse()[0]=="pdftranslatedtxt"){
//success bill supported, data send to app
jQuery('#form_upload1').submit();
}
else if(bill==""){return false; }
else{// return error wrong format of bill alert('We only currently support PDF or CSV file format.')
}
}
</script>
UPDATE
I have the code working on some instance of this page. I have also have one situation where the find/trigger is working (the logs show actions, but the poltergeist:render shows no page update)
so, rspec function is
def new_import_bill(billfile)
path = DATA_TEST+billfile
attach_file("bill", path)
find("#upload_bill_button1").trigger("click")
end
I have debugged the page output e.g.
puts page.html
and there is no difference between the page html that works and the pages that do not work., but in certain situations it refuses to click or the poltergeist.render does not update.
as per this poltergeist bug (https://github.com/jonleighton/poltergeist/issues/209) I have tried removing full:true. No difference
has anyone else come across these inconsistences?

Cannot call other action

I'm studying ASP MVC, and developping SportsStore (Create/Edit feature). When Create a product, Create action will view a Edit view, but when press Sudmit, it call action Create (Post), althrough I will set it call Edit action:
<% using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype="multipart/form-data" }))
{%>
<%--<%= Html.ValidationSummary() %>--%>
<%--<%= Html.Hidden("ProductID") %>--%>
<p>Name: <%= Html.TextBox("Name")%>
<div><%= Html.ValidationMessage("Name")%></div>
</p>
<p>Description: <%= Html.TextArea("Description", null, 4, 20, null)%>
<div><%= Html.ValidationMessage("Description")%></div>
</p>
<p>Price: <%= Html.TextBox("Price")%>
<div><%= Html.ValidationMessage("Price")%></div>
</p>
<p>Category: <%= Html.TextBox("Category")%>
<div><%= Html.ValidationMessage("Category")%></div>
</p>
<p>
Image:
<% if (Model.ImageData == null)
{ %>
None
<% }
else
{ %>
<img src= "<%= Url.Action("GetImage", "Products", new {Model.ProductID}) %>" />
<% } %>
<div>Upload new image: <input type="file" name="file" id="file" /></div>
</p>
<input type="submit" value="Save" />
<%= Html.ActionLink("Cancel and return to list", "Index")%>
<% } %>
Please help me fix it
The code you have seems reasonable if you want it to post back to the Edit action. Your question is a bit confusing, but I'm going to assume that you want to reuse the view and have it post back to Create when rendered from Create and Edit when rendered from Edit. The easiest way is to simply omit the parameters from the BeginForm call. This will cause the form action to be set to the current controller and action, which would give you what you seem to want. An alternative would be to develop templates (display/editor) for the model but have separate views for Create/Edit that simply render the template Html.EditorFor( m => m, "ProductTemplate" ). This would allow you to customize the view -- perhaps the Create view requires you to upload an image? -- yet still reuse most of the code.

Resources