How do I pass an existing Variable that changes at refresh to a param in a post method using sinatra - ruby

I'm using sinatra as my web framework and right now I have
<p><%= #sentence %></p>
<form action='/' method='POST'>
<button type='submit'>Save Story</button>
</form>
in my erb file. The variable at #sentence changes at refresh. When I hit the save Story button I want it to create a param in the post method that is equal to #sentence so that I can save #sentence to the main page. Is there anyway to do this without javascript?
ANSWERED
I used
`<div class="row">
<form action='/' method='POST'>
<input id="sentence" type="hidden" name="sentence" value= "<%= #sentence %>" >
<button type='submit'>Save Story</button>
</form>
</div>`
its still only taking the first word on one of the 4 pages but there must be something else going on there.

You need to create a hidden input field with the value set to w.e #sentence is
<p><%= #sentence %></p>
<form action='/' method='POST'>
<input type="hidden" name="sentence" value="<%= #sentence %>" />
<button type='submit'>Save Story</button>
</form>
This will give the form something to pass that you can grab with post elsewhere, hope that helps, just put your variable where the ... is and be sure to tell it the language, here is a php example on how to add a varaible to a value.
value="<?php echo $state; ?>"
Here I'm basically telling the browser to echo(print) the state variable between the " and " using php start and end to initiate the language and end it, The hidden type input field is invisible to users and they cannot edit it, its a background trick you can use to pass information, it acts as a text field.
Information on hidden fields:
http://www.blooberry.com/indexdot/html/tagpages/i/inputhidden.htm
When you select an answer, please edit your main post to display ANSWERED and the updated code so users can see what you decide to use.

In sinatra you can do this:
<p><%= #sentence %></p>
<form action='/' method='POST'>
<input type="hidden" name="sentence" value="<%= #sentence %>" />
<button type='submit'>Save Story</button>
</form>

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%>.

Mechanizing checkbox with checkbox.check not working

I'm trying to mechanize the select devices part of the Apple Dev Portal "Edit iOS Provisioning Profile", which can be found here (if you're logged in).
The source looks like this:
<form name="profileEdit" method="get" action="https://developer.apple.com/services-developerportal/QH43B2/account/ios/profile/regenProvisioningProfile.action?content-type=text/x-url-arguments&accept=application/json&requestId=838c910b-f63d-843e7b1ce126&userLocale=en_US&teamId=BF5K33D" successURL="/account/ios/profile/profileDownload.action?provisioningProfileId=">
<input type="hidden" name="distributionType" value='store'/>
<input type="hidden" name="returnFullObjects" value="false"/>
<div class="nameSection">
<dl>
<dt class="selectDevices">Devices:</dt>
<dd class="selectDevices">
<div class="table">
<div class="rows">
<div><input type="checkbox" name="deviceIds" class="validate" value="8T8RG7HX" id="devices-6" ><span class="title">iPhone 4 - JC</span></div>
<div><input type="checkbox" name="deviceIds" class="validate" value="7Y9F8N47" id="devices-7" ><span class="title">iPhone 5 - DP</span></div>
<div><input type="checkbox" name="deviceIds" class="validate" value="ZNES97W7" id="devices-8" checked><span class="title">iPhone 5 - JC</span></div>
<div><input type="checkbox" name="deviceIds" class="validate" value="CRDSL7S5" id="devices-9" checked><span class="title">iPod 4 inch</span></div>
</div>
</div>
</dd>
<dd class="form-error deviceIds hidden">Please select a Device</dd>
</dl>
</div>
<div class="bottom-buttons">
<a class="button small left cancel"><span>Cancel</span></a>
<a class="button small blue right submit"><span>Generate</span></a>
</div>
</form>
What I want to do is check all boxes:
form = page.form_with(:name => 'profileEdit') or raise UnexpectedContentError
form.checkboxes_with(:name => 'deviceIds').each do |checkbox|
puts checkbox["id"] # prints correct value of devices-6...
checkbox.check
end
form.method = 'GET'
form.submit
I get no run time errors, however when I refresh the actual page, not all checkboxes are checked as I intended. Am I missing something?
For this:
form.checkboxes_with(:name => 'deviceIds').each do |checkbox|
puts checkbox["id"] # prints correct value of devices-6...
checkbox.check
end
What do these result in:
tmp1 = form.checkboxes_with(:name => 'deviceIds').map { |cb| cb.check }
tmp2 = form.checkboxes_with(:name => 'deviceIds').map { |cb| cb.checked? }
I would expect [true, true, true, true] for both. If not, something is clearing those out. The check() method is implemented in RadioButton which does clear the checked state of all buttons of the same name, but it should be limited to radiobutton types. The checked attribute is writable by itself, so you could try directly writing it:
form.checkboxes_with(:name => 'deviceIds').each do |cb|
cb.checked = true
end
And avoid what may be a bug or inconsistency in that page/mechanize/whatever. Just a guess, but something to try.
As for as I have understood, your issue is that you are visiting the actual page after setting checkboxes which will not work. But if you inspect the results returned after submit you will realize that Mechanize has set the check boxes and returned the response.
If you want to visually see that in an actual browser, you may need to use Watir / Webdriver etc.

Form Submit using a Javascript to invoke webflow transition, doesn't take the updated value on form

I am trying to invoke a form submit using javascript (jquery) to invoke a webflow transition. It works and the submit invokes the desired transition. But, the updated radio button values is not reflected on the model object which is posted.
Here is the code:
<form:form method="post" action="#" commandName="infoModel" name="pageForm">
<form:input type="input" path="testMsg" id="success" />
<input type="button" id="clearSelections" value="Clear Selections">
<div class="question">
<h4><c:out value="${infoModel.questionInfo.description}"/> </h4>
<form:radiobuttons path="infoModel.answerId"
itemValue="answerId" itemLabel="answerDescription" items="${infoModel.answers}" delimiter="<br/>" />
</div>
<input type="submit" name="_eventId_saveQualitativeInput" value="Save" id="save" />
$(document).ready(function() {
$('#tabs').tabs();
//Clear selections (copy is server-side)
$('#clearSelections').click(function() {
//$('input[type="radio"]').prop('checked', false);
$('input[type="radio"]').removeAttr('checked');
$('#save').trigger('click');
});
});
</form:form>
The form:radiobutton, generates the below html:
<div class="question">
<h4>Is this a general obligation of the entity representing a full faith and credit pledge? </h4>
<span>
<input type="radio" checked="checked" value="273" name="infoModel.answerId" id="infoModel.answerId1">
<label for="infoModel.answerId1">Yes</label>
</span>
<span><br>
<input type="radio" value="274" name="infoModel.answerId" id="infoModel.answerId2">
<label for="infoModel.answerId2">No</label>
</span>
<br>
<span class="error"></span>
</div>
The input id= "success" value is registered and when the control goes to the server, the value of input id= "success" is updated in the "infoModel" object. But the value of answerId is not updated on the "infoModel" object.
Thoughts if i am missing something in the form:radiobutton element or if there is something else wrong?
Thanks in advance!
EDIT:::::::
Thanks mico! that makes sense. I stripped of some of the code first time to make it precise, but i have a list which is being used for building the radio-buttons, below is the code:
<c:forEach items="${infoModel.list["index"]}" var="qa" varStatus="rowCount">
<div class="question">
<h4><c:out value="${question.questionInfo.description}"/> </h4>
<form:radiobuttons path="list["index"][${rowCount.index}].answerId" itemValue="answerId" itemLabel="answerDescription" items="${question.answers}" delimiter="<br/>" />
<br>
</div>
</c:forEach>
Could you please suggest how i could try this one out?
NOTE: The same code works on a regular form submit on click of a button of type submit. Its the javascript form submit which is not working. I also tried to do whatever i want to do in javascript and then invoke the button.trigger('click'); form got submitted but the changes made on form in my javascript didnt reflect.
With commandName inside a form:form tag you set "Name of the model attribute under which the form object is exposed" (see Spring Documentation). Then in path you should tell the continuation of the path inside the model attribute.
With this said I would only drop the extra word infoModel from path="infoModel.answerId" and have it rewritten as path="answerId" there under the form:radiobutton.

Retrieving a parameter from GSP in Controller, Grails

I do have this code on my demo.gsp file. But I´m new to grails and I don´t really know very well how to retrieve the value of the input on my Controller to validate it like i.e "inputResult=="hi" then ok else bad".
<g:form action='${postUrl}' method='post' id='loginForm' class='cssform' autocomplete='off'>
<p>
<label for="password">
<g:message code="access.code"/>:
</label>
</p>
<p>
<input name="j_password" class="loghominput" id="password" type="password"/>
</p>
<div class="greenbutton2">
<a href="#" onclick="document.getElementById('loginForm').submit(); return false">
<g:message code="home.enter"/></a><input type="submit" style="display:none" value="Enter"/>
</div>
</g:form>
My Controller is like this.
class AskDemoController {
def demo = {
}
}
Thanks!
You can access parameters submitted by your form in the controller by using the params object. Something like this...
def somethingInTheForm = params.nameOfTheParam;
if (somethingInTheForm){
render 'good'
}else{
render 'bad'
}
Take a look here for documentation.
However - i would suggest going through some to the Tutorials to gain a better understanding of the power of grails.

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