Rails simple_form server side validations lost URL params - simple-form

I'm using simple_form for a form and passing in some URL parameters
to prepopulate the form.
This code works OK
<%= f.input :first_name, :label => 'First Name', :input_html => { :value => params['first'] } %>
Using the URL
http://localhost:3000/charities/new?first=Bob
Which outputs this HTML
<input class="string required" id="charity_first_name" name="charity[first_name]" size="50" type="text" value="Bob" />
However if the form server side validation fails the page reloads but the prepopulate
value is gone? This is the rendered HTML
<input class="string required" id="charity_first_name" name="charity[first_name]" size="50" type="text" />
Can anyone help advise how to prepopulate simple_form and retain those
values if the serverside validastion fails and the page reloads?
Thank you.

if you want to make it works with validations you should preset object values in controller like this:
#charity = Charity.new
#charity.first_name = params[:first]

Related

patch method in ruby sinatra

I'm writing a web app using sinatra and activerecord but I can't figure it out what's wrong into my code...if you could just check it and guide me through it would be awesome !!All the models are linked but I can't update information about some books into the database..
RUBY SINATRA CODE :
get '/info/:isbn/edit' do
#book = Book.find_by(isbn: params[:isbn])
erb :edit
end
patch '/info/:isbn' do
book = Book.find_by(isbn: params[:isbn])
book.title = params[:title]
book.page_count = params[:number_pages]
book.category = params[:category]
book.save
redirect to "/info/#{ params[:isbn] }"
end
ERB PAGE
<form action="/info/<%= #book_isbn%>/edit" method="post">
<input type="hidden" value="patch" name="_method">
<label for="">Title</label>
<input type="text" name="title" value="<%= #book_title %>">
</form>
and this is the error page...
Check to make sure that your controller sets :method_override to true.
set :method_override, true
Without it Sinatra won't know what do with input type="hidden" value="patch" name="_method"
You are sending your form to the wrong URL:
<form action="/info/<%= #book_isbn%>/edit" method="post">
URL should be /info/<%= #book_isbn%>.

Trying to distinguish between two hidden values using an id

got yet another query from my still hodgepodge learning of ruby + watir.
The CMS i'm writing automation for creates an item and assigns an id to it at which point i execute the code below to collect and store the id as this is used for other actions against the item.
##grabprodvarelement = $browser.hidden(:name, "shopProductVariantHeadingID")
##prodvarid = ##grabprodvarelement.value
Once created there are then two buttons that control if the item is in stock or out of stock and published or unpublished.
Normally the code i use to update the publish status is
form_element = $browser.hidden(:name => 'shopProductVariantHeadingID', :value => "#{##prodvarid}").parent
form_element.button(:value => 'Change').click
However, in this instance when run against the html below, it is updating the stock flag, not the published status (I assume this is because it is the first instance of this 'change' value).
<td>
<span class="label label-important">Out of Stock</span>
<form action method='post' class='pull-right'>
<input type='submit' name='inStockChange' value='Change' class='btn btn-mini btn-secondary' style='float:right'>
<input type='hidden' name='shopProductVariantHeadingID' id='14' value ='14'>
<input type='hidden' name='stockChange' id='No' value ='No'>
</form>
</td>
<td>
<span class="label">Un-Published</span>
<form action method='post' class='pull-right'>
<input type='submit' name='publish' value='Change' class='btn btn-mini btn-secondary' style='float:right'>
<input type='hidden' name='shopProductVariantHeadingID' id='14' value ='14'>
<input type='hidden' name='published' id='No' value ='No'>
</form>
</td>
I've tried updating the code i use to;
form_element = $browser.hidden(:name => 'shopProductVariantHeadingID', :value => "#{##prodvarid}").parent
form_element.button(:name => 'publish').click
I thought this was enough to identify the the correct entry to click however, i get the error;
Watir::Exception::UnknownObjectException: unable to locate element, using (:name=>"publish", :tag_name=>"button")
any help would be appreciated.
The problem is actually with the way the form_element is located rather than how the button is clicked.
The line:
form_element = $browser.hidden(:name => 'shopProductVariantHeadingID', :value => "#{##prodvarid}").parent
Will always return the Out of Stock form; never then Un-Published form. This is because Watir will find the first matching hidden element, which is the one in the Out of Stock form. That causes form_element.button(:value => 'Change') to click the first change button and form_element.button(:name => 'publish') to not exist.
The form element will need to be located based on having the shopProductVariantHeadingID as well as the published button:
form_element = $browser.forms.find do |form|
form.hidden(:name => 'shopProductVariantHeadingID', :value => "#{##prodvarid}").exists? &&
form.button(:name => 'publish').exists?
end
form_element.button(:value => 'Change').click

Haml renders input element as escaped

I have a haml like ;
= form_for #company, :html => {:multipart => true}, :url => update_user_company_path do |f|
.field
Title:#{f.text_field :name}
= f.fields_for :attachments do |builder|
- if builder.object.new_record?
.field
= builder.hidden_field :name, :value => 'logo'
= builder.file_field :file
- elsif builder.object.name.eql?('logo') && !builder.object.file.url.eql?('/files/original/missing.png')
.field
%span.thumbnail
= link_to "Delete", delete_company_attachment_path(#company, builder.object), :method => :delete, :class => "remove_image"
= image_tag builder.object.file.url, :style => "height:86px;width:125px"
= f.submit 'Ok'
Chrome renders this code as intended, but in Firefox it is like;
<form method="post" id="edit_company_29" enctype="multipart/form-data" class="edit_company" action="/users/25/company" accept-charset="UTF-8"><div style="margin:0;padding:0;display:inline"><input type="hidden" value="✓" name="utf8"><input type="hidden" value="put" name="_method"><input type="hidden" value="thisismytokenvalue=" name="authenticity_token"></div>
<div class="field">
Title:<input type="text" value="sdgdfgghjh" size="30" name="company[name]" id="company_name">
</div>
<input id="company_attachments_attributes_0_id" name="company[attachments_attributes][0][id]" type="hidden" value="114" /><input id="company_attachments_attributes_1_id" name="company[attachments_attributes][1][id]" type="hidden" value="115" /><div class="field">
<input type="hidden" value="logo" name="company[attachments_attributes][2][name]" id="company_attachments_attributes_2_name">
<input type="file" name="company[attachments_attributes][2][file]" id="company_attachments_attributes_2_file">
</div>
<input type="submit" value="Ok" name="commit">
</form>
Why is an element escaped. If you check haml, you can see I didn't put them.
Where did it come from?
Why is it happening?
Wow ... I've just had a similar issue. My guess is that if you pass nil to the form_builder's fields_for the hidden_input isn't returned with html_safe. To quickly fix that add a
-else
=""
after the whole elsif block
You must return something other than nil in the fields_for block.
This issue has been fixed in Haml 4.0.4 by mattwildig, with the help of #lulalala. Here is an explanation of the problem:
The #fields_for helper generates a hidden input field for each record, which it adds to the result of capturing the block. Normally the return value of capture will be a SafeBuffer, so this won’t be escaped. However if the block doesn’t write anything to the buffer then Haml returns a literal empty String from capture. The hidden input element is concatted to this string, and when it is combined with the rest of the entries, since it is a String being added to a SafeBuffer, it gets escaped.

ASP.NET MVC3 Unobtrusive Validation and Hand Coded Element Question

I understand with built in function to render UI controls like
#Html.TextBoxFor(model => model.CustomerId)
#Html.ValidationMessageFor(model => model.CustomerId)
The rendered Html will look like
<input data-val="true" data-val-number="The field CustomerId must be a number." data-val-required="The CustomerId field is required." id="CustomerId" name="CustomerId" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="CustomerId" data-valmsg-replace="true"></span>
All the attributes inside input elements are used to support unobtrusive validation feature.
But for some reason I cannot render by using Html helper, but I have to hand code Html markup like
<select id="MyId" name="MyId" />
<%=Html.ValidationMessageFor(model => model.MyId)%>
In this case how can I still make unobtrusive validation word without hard code all these attributes in select element?
Thanks
Hardy
Unobtrusive validation relies completely on this attributes to determine which validation it will apply to the element, you will have to hard code them in your html is you dont want to use the helper, just make sure the name attribute of you select tag is equal to the property name it binds to.

Sinatra HTTP 'PUT' method

Something's wrong with the PUT action here, the form gets processed but the updated field is not being saved.
I've did what Sinatra users are doing, by adding in "_method" for Sinatra to recognise that's its a HTTP PUT action. Could anyone spot any mistake here?
# edit
get '/entries/*/:id/edit' do
#entry = Entries.get(params[:id])
#title = "edit"
erb :edit, :layout => :edit_layout
end
# update
put '/entries/:id' do
#entry = Entries.get(params[:id])
if #entry.save
redirect "/entries/id=#{#entry.id}"
else
redirect "/enewsletters"
end
end
<!-- Edit form -->
<form action="/enewsletters/edit/<%= #entry.id %>" method="post">
<input name="_method" value="put" type="hidden"/>
<p>
<label>Content</label><br/>
<input type="text" name="entry[title]" value="<%= #enew.title %>">
</p>
<p>
<input type="submit" name="commit" value="update">
</p>
</form>
You don't seem to be doing any update to the #entry, you're just fetching the specific entry with the id from params. Are you using ActiveRecord? If so, instead of #entry.save, try #entry.update_attributes(params[:entry]).
Edit: I'm guessing you're not using AR since I just noticed the .get call. Whatever ORM you are using must have an easy way to update the attributes and then save the record.

Resources