If search don't return values from database show an empty form - webmatrix

So i got a page that have a search form, and when the user search for a value if there are no records on database the form returns empty, but if there are records the form is populated with data.
What i was thinking was this
var db = Database.Open("myDataBase");
var selectCommand = "SELECT * FROM exportClient";
var searchTerm = "";
if(!Request.QueryString["searchField"].IsEmpty() ) {
selectCommand = "SELECT * FROM exportClient WHERE clientAccount = #0";
searchTerm = Request.QueryString["searchField"];
}
if(IsPost){
var selectedData = db.Query(selectCommand, searchTerm);
}
And Then:
<body>
<div class="col_12">
<form method="get">
<label>search</label><input type="text" class="col_3" name="searchField" />
<button type="submit" class="button red" value="search">search</button>
</form>
</div>
#if(!Request.QueryString["searchField"].IsEmpty() ){
foreach(var row in db.Query(selectCommand, searchTerm)) {
<div class="col_12 box">
<form method="post">
// HERE IS THE FORM POPULATED
</form>
</div>
}
} else {
<div class="col_12 box">
<form method="post">
// HERE IS THE FORM NOT POPULATED
</form>
</div>
}
</body>
But what is happening is that the form that is not populated is always showing up when i enter the page, and i need that the only thing that user see when enter the page is the input field to do the search.
What am i doing wrong ?

I'm not sure of having understood your goal, but in my opinion your main problem is to detect if either exists or not a query string.
I think that your code should be like this
#if(Request.QueryString.HasKeys())
{
if(!Request.QueryString["searchField"].IsEmpty() ){
<p>searchField has value</p>
} else {
<p>searchField hasn't value</p>
}
}

There are a number of potential issues I can see with your code, hopefully you can put these together to achieve what you wanted:
As Selva points out, you are missing the action attribute on your forms.
The selectedData variable you create inside your IsPost() block goes out of scope before you do anything with it. Perhaps you didn't include all your code though, so ignore this if it just isn't relevant to the question.
To answer the main question: if you don't want the empty form to appear when the user hasn't yet performed a search, surely you just need to completely remove the else block - including the empty form - from your HTML?
Hope that helps.

Related

How to create dynamic url in Spring Thymeleaf

#GetMapping("/deposit")
public String deposit(#RequestParam("amount") double amount,#RequestParam ("id") int id) {
if (amount > 0) {
accountService.deposit(id, amount);
}
return "redirect:/account";
}
I have two parameters that I need to send from my html file, my problem is that 'amount' parameter should be coming from html file. How can I dynamically do that?
<input type="number" id="amount">
<a th:href="#{/account/deposit(id=${account.id}, amount=????)}">Deposit</a>
I want to put the input value into amount in th:href would appreciate any help.
As it is mentioned by #andrewJames it would be mush easier to submit this value using form. For example:
In your HTML
<form th:action="#{/account/deposit(id=${account.id})}" method="post">
<input type="number" id="amount" name="amount">
<button type="submit">Deposit</button>
</form>
In your Controller
#PostMapping( "/deposit" )
public String onDepositSubmit( #RequestParam Long id, #RequestParam Integer amount ) {
if (amount > 0) {
accountService.deposit(id, amount);
}
return "redirect:/account";
}
This would be the easiest solution. However, it is possible to dinamically alter a link as at the client-side the link is already rendered to a normal link (e.g. /account/deposit?id=12345), so you can manipulate it using JS as you wish, for example something like this (using JQuery):
<input type="number" id="amount">
<a th:href="#{/account/deposit(id=${account.id},amount=0)}" id="amount_link">Deposit</a>
<script>
let amountInput = $( '#amount' )
let amountLink = $( '#amount_link' )
amountInput.keyup( function() {
let url = new URL( amountLink.attr( 'href' ) );
url.searchParams.set( 'amount', amountInput.val() )
amountLink.attr( 'href', url.toString() )
} )
</script>
Which would create a keyup event listener on input and update link every time the character is typed or deleted. However, this is needlessly complicated and as such is considered a bad practice.

Why is there nothing in my userConsul model

When I submit the form I want to collect the userConsult information. I then call my repository and call the Insert method. inside the brackets I include e.g.
userRepo.insertoIntoDB(userConsult.getepidemiology);
(I have left the other get methods as it is so long.
I run this and when I check my database I notice that only the fields I didnt use userConsult have items inside.
I think there is something to do with my options/select tag however I am unsure why there is nothing inside it. It works fine when I use input tags. I am using thymeleaf.
The Insert function works fine if I give it test inputs myself.
Please see my code below:
<form method="POST" th:action="#{/saveConsultation}" th:object="${userConsul}">
<label for="epidemiology">EPIDEMIOLOGY:</label>
<select id="epidemiology">
<option th:each="data : ${consultationData}"
th:text="${data.epidemiology}"
th:value="${data.epidemiology}">
</select>
<a th:href="#{/saveConsultation/{id}(id = ${patient.patientNumber})}" type="submit">Submit</a>
<input type="reset" value="Reset diagnosis">
</form><br>
Consultation Controller:
#RequestMapping("/saveConsultation/{id}")
public String saveConsultation(#ModelAttribute("userConsul") userConsul userConsul,HttpSession session,Model model,#PathVariable("id") int patientID){
Object USER_SESSION = session.getAttribute("USER_SESSION");
if (USER_SESSION == null) {
session.setAttribute("message", "You need to login to access the Consultation page");
return "redirect:/login";
}
User OldUser = (User) USER_SESSION;
int userId = OldUser.getID();
userRepository.insertIntoUserCase(userConsul.getEpidemiology(),userConsul.getComplaints(),userConsul.getExamination(),userConsul.getDiagnosis1(),userConsul.getDiagnosis2(),userConsul.getDiagnosis3(),patientID,userId);
return "test";
}

How to get checked checkbox value from html page to spring mvc controller

im using spring mvc framework with thymeleaf template engine
the problem is , i have 1 page with multiple check box iterated sing thymeleaf th:each iterator.When i clicked multiple check boxes i want to pass check box values to the controller method..
html content
<table>
<tr th:each="q : ${questions}">
<h3 th:text="${q.questionPattern.questionPattern}"></h3>
<div>
<p >
<input type="checkbox" class="ads_Checkbox" th:text="${q.questionName}" th:value="${q.id}" name="id"/>
</p>
</div>
</tr>
</table>
*Controller*
#RequestMapping(value = Array("/saveAssessment"), params = Array({ "save" }))
def save(#RequestParam set: String, id:Long): String = {
var userAccount: UserAccount = secService.getLoggedUserAccount
println(userAccount)
var questionSetQuestion:QuestionSetQuestion=new QuestionSetQuestion
var questionSet: QuestionSet = new QuestionSet
questionSet.setUser(userAccount)
questionSet.setSetName(set)
questionSet.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetService.addQuestionSet(questionSet)
var list2: List[Question] = questionService.findAllQuestion
var limit=list2.size
var qustn:Question=null
var a = 1;
for( a <- 1 to limit ){
println( a );
qustn= questionService.findQuestionById(a)
questionSetQuestion.setQuestion(qustn)
questionSetQuestion.setQuestionSet(questionSet)
questionSetQuestion.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
questionSetQuestionService.addQuestionSetQuestion(questionSetQuestion) } "redirect:/teacher/Assessment.html" }
I think you pretty much have it. With a checkbox, you can only send one piece of information back with the form...that being the value. So if you are trying to determine which checkboxes are checked when the user clicks the submit button, then I would have the checkboxes all use one name...like "id" (exactly like you have). Value is the actual id of the question (again like you have). Once submitted, "id" will be a String array which includes all the values of the checkboxes that were checked.
So your controller method needs to take param called "ids" mapped to parameter "id" which is a string[]. Now for each id, you can call questionService.findQuestionById.
(I'm not a Groovy guru so no code example sry :)
I have used JSTL with JSP and thymeleaf was something new. I read the THYMELEAF documentation.
There is a section which explains multi valued check boxes.
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:value="${q.id}" name="id"/>
In the above code we are not binding the value to the field of the command object. Instead try doing this
<input type="checkbox"
class="ads_Checkbox"
th:text="${q.questionName}"
th:field="*{selectedQuestions}"
th:value="${q.id}" />
here the selectedQuestions is an array object present in the spring command object.

Validation of dynamic created form (AngularJS)

I try to made nested form with validation. All works fine, but when I remove one of nested form, validation continue to use removed form. I made jsfiddle example http://jsfiddle.net/sokolov_stas/VAyXu/
When example runs, form are valid. If click "+" button, nested form will be added and valid will be false. Then click "-" button, and valid will be false all the same.
The question is: How to remove dynamic created form from validation processing.
Well, for one thing, a <form> inside of a <form> is not valid HTML.
Second, you're not supposed to be doing DOM manipulation from inside the controller. The controller is for "business" logic. See the section on controllers here
For what you're doing, you'd probably be better off using one form, with an ng-repeat inside of it, and adding additional elements to an array:
<form name="myForm" ng-controller="FormCtrl" ng-submit="doSomething()">
<div ng-repeat="item in items">
<input ng-model="item" type="text" required/>
</div>
<a ng-click="addItem()">+</a>
<a ng-click="removeItem()">-</a>
<button type="submit">Submit</button>
<div>Form valid: {{myForm.$valid}}</div>
</form>
and the controller:
function FormCtrl($scope) {
$scope.items = [];
$scope.addItem = function() {
$scope.items.push(null);
};
$scope.removeItem = function() {
$scope.items.pop();
};
$scope.doSomething = function () {
//your submission stuff goes here.
};
}

How to rerender part of page after ajax submit of form in Lift (Scala)

this is probably a stupid question but I cannot figure out how to do it.
So I'm new to Scala/Lift and I read the ajax form chapter in http://simply.liftweb.net/index-4.8.html#toc-Section-4.8 but the "RedirectTo" in the example does not seem to be very "ajaxian" to me. Often in case of submitting a form via ajax, you would just partially rerender the same page, right?
So that's what I'm trying to do and am completely failing right now.
How do I let Lift rerender just a part of the same page after I submit the form via ajax?
Any hints would be appreciated. Thanks.
Basically, what I have looks like this:
<div id="main" class="lift:surround?with=default;at=content">
<h2>Welcome to your project!</h2>
<div class="lift:Test">
<div>
<form class="lift:form.ajax">
<fieldset>
<label for="name">Name:</label>
<input id="name" name="name" type=text>
<p></p>
<input id="save" type="submit" value="Save">
</fieldset>
</form>
</div>
<div>
<span id="theName">Name</span>
</div>
</div>
</div>
class Test {
def render = {
var name = ""
def process(): JsCmd = {
Thread.sleep(500)
S.notice("Entered name is: %s".format(name))
Noop
}
"#theName " #> "This shall be updated with the name given in the form above" &
"#name" #> (SHtml.text(name, name = _) ++ SHtml.hidden(process))
}
}
How would I update "theName" when submitting the form?
Have a look at http://lift.la/shtmlidmemoize-simple-ajax-updating (Example Code). There is SHtml.memoize and SHtml.idMemoize which automatically caches the HTML code. Not sure why it is not used in this example in the Simply Lift book.
You have a 2 step form right? The above poster is correct.
Save your transformation in a RequestVar.
in your above example, the method you want to save is render, so 1st memoize the transform:
private def renderTest= SHtml.memoize { render }
Then, you can save this memoized transformation in a RequestVar (lasts for 1 request), or maybe a TransientRequestVar depending on your needs.
private object testTemplate extends RequestVar(renderTest)
When you want to replay the transform, from an ajax event - testTemplate.is.applyAgain.
I might have misunderstood the original question, b/c if you want to do a 2 step form, you don't really need the memoize. The memoize is if something changes on your current form, and you want to update it via an ajax event, i.e. on click or on change, b/c normally the form wouldn't update unless you did an ajax submit.

Resources