Grails One to Many form - forms

I am currently working on a grails project and am trying to create a one to many form. I have been using the tutorial at the link below to get started:
http://omarello.com/2010/08/grails-one-to-many-dynamic-forms/
The solution has a form with two field of data that are static and one dynamic fiwld where the user is allowed to add as many variables as they want and then save them. below you can see all the various files for this functionality:
Products.Groovy Domain Class
import org.apache.commons.collections.list.LazyList;
import org.apache.commons.collections.FactoryUtils;
/**
* Products
* A domain class describes the data object and it's mapping to the database
*/
class Products {
String productType
String product
List vars = new ArrayList()
//This represents a product belonging to a single department
static belongsTo = [dept:Depts]
static hasMany = [ vars:Dynam ]
static mapping = {
vars cascade:"all-delete-orphan"
}
def getVarsList() {
return LazyList.decorate(
vars,
FactoryUtils.instantiateFactory(Dynam.class))
}
static constraints = {
productType blank: false
product blank:false, size: 1..160
}
}
Dynam.groovy
class Dynam {
public enum VarType{
T("Testimonial"),
D("Dimentions"),
N("Networking")
final String value;
VarType(String value) {
this.value = value;
}
String toString(){
value;
}
String getKey(){
name()
}
static list() {
[T, D, N]
}
}
static constraints = {
index(blank:false, min:0)
data(blank:false)
type(blank:false, inList:VarType.list(), minSize:1, maxSize:1)
}
int index
String data
VarType type
boolean deleted
static transients = [ 'deleted' ]
static belongsTo = [ product:Products ]
def String toString() {
return "($index) ${data} - ${type.value}"
}
}
ProductsController.Groovy
Creation Function
def createDynProduct(){
def productsInstance = new Products()
productsInstance.properties = params
//This is used in order to create a new User Object for the current User logged in
def userObjects = springSecurityService.currentUser
//This passes the 2 models to the view one being Products and the other a User Department
[productsInstance: productsInstance, dept: userObjects.dept]
}
Save Function
def save() {
def productInfo = "dynam"
def userObjects = springSecurityService.currentUser
def dept = Depts.findByName(params.dept.name)
def product = new Products(product:productInfo, productType:params.productType, dept: dept, vars:params.varsList)
def _toBeRemoved = product.vars.findAll {!it}
// if there are vars to be removed
if (_toBeRemoved) {
product.vars.removeAll(_toBeRemoved)
}
//update my indexes
product.vars.eachWithIndex(){phn, i ->
if(phn)
phn.index = i
}
//If the the save is not successful do this
if (!product.save(flush: true)) {
render(view: "create", model: [productsInstance: product, dept: userObjects.dept])
return
}
redirect(action: "show", id: product.id)
}
createDynProduct.gsp
<%# page import="com.tool.Products" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name='layout' content='springSecurityUI'/>
<g:set var="entityName" value="${message(code: 'messages.label', default: 'Products')}" />
<title><g:message code="default.create.label" args="[entityName]" /></title>
</head>
<body>
<g:renderErrors bean="${productsInstance}" />
<g:form action='save' name='ProductForm' >
<br/>
<!-- Render the product template (_dynam.gsp) here -->
<g:render template="dynam" model="['productsInstance':productsInstance]"/>
<!-- Render the product template (_dynam.gsp) here -->
<div class="buttons">
<g:submitButton name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</div>
</g:form>
<!-- Render the var template (_var.gsp) hidden so we can clone it -->
<g:render template='var' model="['var':null,'i':'_clone','hidden':true]"/>
<!-- Render the var template (_var.gsp) hidden so we can clone it -->
</body>
</html>
_dynam.gsp
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name">
<label for="productType">Product Type</label>
</td>
<td>
<g:textField name='productType' bean="${productsInstance}" value="${productsInstance.productType}"
size='40'/>
</td>
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="Vars">Vars</label>
</td>
<!-- Render the vars template (_vars.gsp) here -->
<g:render template="vars" model="['productsInstance':productsInstance]" />
<!-- Render the vars template (_vars.gsp) here -->
</tr>
<tr class="prop">
<td valign="top" class="name">
<label for="Department">Department</label>
</td>
<td>
<g:textField name='dept.name' readonly="yes" value="${dept.name}" size='40'/>
</td>
</tr>
</tbody>
</table>
</div>
_vars.gsp
<script type="text/javascript">
var childCount = ${productsInstance?.vars.size()} + 0;
function addVar(){
var clone = $("#var_clone").clone()
var htmlId = 'varsList['+childCount+'].';
var varInput = clone.find("input[id$=number]");
clone.find("input[id$=id]")
.attr('id',htmlId + 'id')
.attr('name',htmlId + 'id');
clone.find("input[id$=deleted]")
.attr('id',htmlId + 'deleted')
.attr('name',htmlId + 'deleted');
clone.find("input[id$=new]")
.attr('id',htmlId + 'new')
.attr('name',htmlId + 'new')
.attr('value', 'true');
varInput.attr('id',htmlId + 'data')
.attr('name',htmlId + 'data');
clone.find("select[id$=type]")
.attr('id',htmlId + 'type')
.attr('name',htmlId + 'type');
clone.attr('id', 'var'+childCount);
$("#childList").append(clone);
clone.show();
varInput.focus();
childCount++;
}
//bind click event on delete buttons using jquery live
$('.del-var').live('click', function() {
//find the parent div
var prnt = $(this).parents(".var-div");
//find the deleted hidden input
var delInput = prnt.find("input[id$=deleted]");
//check if this is still not persisted
var newValue = prnt.find("input[id$=new]").attr('value');
//if it is new then i can safely remove from dom
if(newValue == 'true'){
prnt.remove();
}else{
//set the deletedFlag to true
delInput.attr('value','true');
//hide the div
prnt.hide();
}
});
</script>
<div id="childList">
<g:each var="var" in="${productsInstance.vars}" status="i">
<!-- Render the var template (_var.gsp) here -->
<g:render template='var' model="['var':var,'i':i,'hidden':false]"/>
<!-- Render the var template (_var.gsp) here -->
</g:each>
</div>
<input type="button" value="Add Var" onclick="addVar();" />
_var.gsp
<div id="var${i}" class="var-div" <g:if test="${hidden}">style="display:none;"</g:if>>
<g:hiddenField name='varsList[${i}].id' value='${var?.id}'/>
<g:hiddenField name='varsList[${i}].deleted' value='false'/>
<g:hiddenField name='varsList[${i}].new' value="${var?.id == null?'true':'false'}"/>
<g:textField name='varsList[${i}].number' value='${var?.data}' />
<g:select name="varsList[${i}].type"
from="${com.tool.Dynam.VarType.values()}"
optionKey="key"
optionValue="value"
value = "${var?.type?.key}"/>
<span class="del-var">
<img src="${resource(dir:'images/skin', file:'icon_delete.png')}"
style="vertical-align:middle;"/>
</span>
</div>
The solution works in part so you can go to the products page and it loads with the fields and the dynamic fields are added to the view fine and I can enter the data. However when I click save the data for the static fields is persisted but the dynamic vars are not saved to the domain.
I don’t get any errors but I believe it has something to do with the save function line below and the vars:params.varsList in particular.
def product = new Products(product:productInfo, productType:params.productType, dept: dept, vars:params.varsList)
I have checked the varsList data using println and it returns null, can someone please help with this?
Thanks in advance

Related

How can i dynamically add an Input select element on click of a button in ember

Am creating an ember application where am in need of dynamicaly adding a select element which will have options fetched from a server. so the select elements look like this. And instead of having all dropdown boxes predefined i need to add them dynamicaly like on a click of a button like( + add more). like
and each of those drop down boxes should contain the datas that is fetched from the server. plus i need a way to get the datas from those dynamically created select fields.
my .hbs for the current drop down page is..
map.hbs
<center><h4>Map</h4></center>
<container class = "cond">
{{#each this.model.sf as |row|}}
<select class = "sel">
{{#each this.model.sf as |sf|}}
<option value = {{sf.attrname}}>{{sf.attrname}}</option>
{{/each}}
</select><br>
{{/each}}
I tried ember-dynamic-fields but its depracted and I couldnt able to use it.. and all other solutions on web or for ember way older versions.. nothing works on ember 4.6 so could anyone helpout?
Using The Platform's native FormData functionality, demo'd here.
I think we can generate any number of inputs based on input data in the following way:
Store the form's state in some variable
conditionally show further select / inputs based on the properties in that form state.
Code-wise, that'd look like this:
{{#if (dataHasValueFor "fieldName")}}
Show previously hidden field
{{/if}}
And of course the devil is in the implementation details, so, a full working example (with sample data I made up -- we can iterate on this if you want for your specific data set, just leave a comment on this post/answer).
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { on } from '#ember/modifier';
import { get } from '#ember/helper';
// This could be your model data from your route
const DATA = {
fruits: [
'apple', 'banana', 'orange', 'mango',
'watermellon', 'avacado', 'tomato?'
],
veggies: ['cocumber', 'tomato?', 'green bean', 'kale', 'spinach'],
peppers: ['carolina reaper', 'habanero', 'jalapeño']
}
export default class Demo extends Component {
#tracked formData;
get categories() {
return Object.keys(DATA);
}
handleInput = (event) => {
let formData = new FormData(event.currentTarget);
let data = Object.fromEntries(formData.entries());
this.formData = data;
}
handleSubmit = (event) => {
event.preventDefault();
handleInput(event);
}
isSelected = (name, value) => this.formData?.[name] === value;
<template>
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<label>
Food Category<br>
<select name="category" placeholder="Select...">
<option selected disabled>Select a food group</option>
{{#each this.categories as |name|}}
<option
value={{name}}
selected={{this.isSelected "category" name}}
>
{{name}}
</option>
{{/each}}
</select>
</label>
<hr>
{{#let (get this.formData "category") as |selectedCategory|}}
{{#if selectedCategory}}
<label>
{{selectedCategory}}<br>
<select name={{selectedCategory}}>
<option selected disabled>
Select {{selectedCategory}}
</option>
{{#each (get DATA selectedCategory) as |food|}}
<option
value={{food}}
selected={{this.isSelected selectedCategory food}}
>
{{food}}
</option>
{{/each}}
</select>
</label>
{{/if}}
{{/let}}
</form>
<hr>
FormData:
<pre>{{toJson this.formData}}</pre>
</template>
}
const toJson = (input) => JSON.stringify(input, null, 4);
This demo is interactive here, on limber.glimdown.com
Note that the syntax used here is what will be default in the upcoming Polaris Edition of Ember, and is available via ember-template-imports
Update (after comments)
Demo here
I took some liberties with the how the fields are dynamic, because I think this more easily shows the concept asked about in the question: dynamically showing fields in a form.
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { on } from '#ember/modifier';
import { get } from '#ember/helper';
export default class Demo extends Component {
#tracked formData;
handleInput = (event) => {
let formData = new FormData(event.currentTarget);
let data = Object.fromEntries(formData.entries());
this.formData = data;
}
handleSubmit = (event) => {
event.preventDefault();
handleInput(event);
}
<template>
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<div class="grid">
<label>
Name <input type="checkbox" name='hasName'>
</label>
<label>
Email <input type="checkbox" name='hasEmail'>
</label>
<label>
Alias <input type="checkbox" name='hasAlias'>
</label>
<hr>
{{#if (get this.formData 'hasName')}}
<label>
Name
<input type="text" name="name" class="border" />
</label>
{{/if}}
{{#if (get this.formData 'hasEmail')}}
<label>
Email
<input type="email" name="email" class="border" />
</label>
{{/if}}
{{#if (get this.formData 'hasAlias')}}
<label>
Alias
<input type="text" name="alias" class="border" />
</label>
{{/if}}
</div>
</form>
<hr>
FormData:
<pre>{{toJson this.formData}}</pre>
</template>
}
const toJson = (input) => JSON.stringify(input, null, 4);
And... since it seems you have a lot of fields, you may want to go as dynamic as possible:
demo here
which is the following code:
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<div class="grid">
{{#each FIELDS as |field|}}
<label>
{{field}} <input type="checkbox" name='has-{{field}}'>
</label>
{{/each}}
<hr>
{{#each FIELDS as |field|}}
{{#if (get this.formData (concat 'has-' field))}}
<label>
{{field}}
<input type="text" name={{field}} class="border" />
</label>
{{/if}}
{{/each}}
</div>
</form>
I guess Simple js code did the magic of adding and retriving data.. pity of me after finding out.. And for some dynamic ember formdata the previous answer from nullvox helped out.. so here is the code
.hbs
<table class="table">
<th>
<td>Sf</td>
</th>
<th>
<td>Db</td>
</th>
<tbody id = "map">
</tbody>
</table>
<button class = "btn btn-sm btn-primary" type="button" {{action "submit"}}>Submit</button>
<button class = "btn btn-success btn-sm" onclick = {{action "get"}} type="button">Add another</button>
controller code for creating element
#action
get() {
let div = document.getElementById('map');
let tr = document.createElement('tr');
let td = document.createElement('td');
let td2 = document.createElement('td');
var select = document.createElement('select');
select.setAttribute('class', 'sfselect');
div.appendChild(tr);
tr.appendChild(td);
td.appendChild(select);
for (var i = 0; i < sf.length; i++) {
var option = document.createElement('option');
option.value = sf[i];
option.text = sf[i];
select.appendChild(option);
}
var select2 = document.createElement('select');
select2.setAttribute('class', 'dbselect');
tr.appendChild(td2);
td2.appendChild(select2);
for (var i = 0; i < db.length; i++) {
var option = document.createElement('option');
option.value = db[i];
option.text = db[i];
select2.appendChild(option);
}
}
controller code for getting data
#action submit() {
var sfattr = document.querySelectorAll('.sfselect');
var dbattr = document.querySelectorAll('.dbselect');
var sf = [];
var db = [];
console.log(sfattr.length);
let datas;
for (var i = 0; i < sfattr.length; i++) {
sf[i] = sfattr[i].value;
db[i] = dbattr[i].value;
}
let m1 = sf.toString();
let m2 = db.toString();
$.ajax({
url: 'http://localhost:8080/lorduoauth/Map',
method: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: {
m1: m1,
m2: m2,
},
success: function (response) {
console.log(datas);
alert(response);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('error' + errorMessage);
},
});
}
thus the output looks like this

webapp form value to spreadsheet

I have a webapp form and I'm looking for a way to push the value of the form into google spreadsheet.
My current attempt is to assign a name to each form input (a1,a2,a3...) then attempt to iterate the form values into an array like this:
Code.gs
function doGet(e) {
return HtmlService
.createTemplateFromFile('Index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
}
function writeForm(form) {
var ss =
SpreadsheetApp.openById('1bKrGjBV*****');
var sheet = ss.getSheets()[0];
var data = ss.getDataRange().getValues();
var input = [''];
var ndata = form
for(var j=0;j<data.length;j++){
var value = form.a+j
input.push(value)
}
for(var k=0;k<data.length;k++){
sheet.getRange(k+1,4).setValue(ndata[k]);
}
var range = sheet.getRange(1, 5);
}
function getData(){
return SpreadsheetApp
.openById('1bKrGjBV*****')
.getSheets()[0]
.getDataRange()
.getValues();
}
Index.html
<body>
<center><h1>Produce Inventory Form </h1></center>
<style>
table,th,td{border:1px solid black;}
</style>
<? var data = getData(); ?>
<form id="invform">
<input type = "submit" value="Submit" onclick
="google.script.run.writeForm(this.parentNode)">
<table align="center">
<tr><th>Code</th><th>Name</th><th>ChName</th><th>On Hand</th></tr>
<? for(var i=0;i<data.length;i++){ ?>
<tr>
<th><?= data[i][0] ?></th>
<th><?= data[i][1] ?></th>
<th><?= data[i][2] ?></th>
<th><input type = "text" style="width:40px" min="0" maxlength="3" name=a<?
=i ?>>
</tr>
<? } ?>
</table>
</body>
With this method, the problem I'm getting into is
var value = form.a+j
Doesn't do what I was hoping for, which is to assign a variable to form.a1, form.a2, form.a3, ... then push it into an array.
I'm pretty sure there's a better way but I have yet to find a solution. Apologize for the messy code, but I was focused on getting the result.
How about a following modification?
Modification points :
For Index.html, </form> is missing.
About form.a+j, you can retrieve the values using form["a" + j].
ndata is JSON like {a1: "value", a2: "value"}. So when ndata is imported to cells, it becomes undefined.
When several values are imported to cells, the importing efficiency becomes higher by using setValues().
When these are reflected to your script, the modified script is as follows. The values inputted to forms are imported to "D1:D" of spreadsheet.
Modified script :
Code.gs
function doGet(e) {
return HtmlService
.createTemplateFromFile('Index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE)
}
function writeForm(form) {
var ss = SpreadsheetApp.openById('1bKrGjBV*****');
var sheet = ss.getSheets()[0];
var data = ss.getDataRange().getValues();
var input = []; // Modified
// var ndata = form
for(var j=0;j<data.length;j++){
var value = form["a" + j]; // Modified
input.push([value]) // Modified
}
sheet.getRange(1, 4, input.length, input[0].length).setValues(input); // Added
// for(var k=0;k<data.length;k++) {
// sheet.getRange(k+1,4).setValue(ndata[k]);
// }
// var range = sheet.getRange(1, 5);
}
function getData(){
return SpreadsheetApp
.openById('1bKrGjBV*****')
.getSheets()[0]
.getDataRange()
.getValues();
}
Index.html
<body>
<center><h1>Produce Inventory Form </h1></center>
<style>
table,th,td{border:1px solid black;}
</style>
<? var data = getData(); ?>
<form id="invform">
<input type = "submit" value="Submit" onclick="google.script.run.writeForm(this.parentNode)">
<table align="center">
<tr><th>Code</th><th>Name</th><th>ChName</th><th>On Hand</th></tr>
<? for(var i=0;i<data.length;i++){ ?>
<tr>
<th><?= data[i][0] ?></th>
<th><?= data[i][1] ?></th>
<th><?= data[i][2] ?></th>
<th><input type = "text" style="width:40px" min="0" maxlength="3" name=a<?= i ?>>
</tr>
<? } ?>
</table>
</form> <!-- Added -->
</body>
If I misunderstand your question, I'm sorry.

dropdown will accept a value that is not part of the list as well in Knockout

When entering an E-mail address, the user will have to select the E-mail
domain from the pre-defined list (e.g., gmail.com; outlook.com; hotmail.com).
The Domain dropdown will accept a value that is not part of the list as well.
I should have both select and input feature.
HTML:
<!-- Mulitple array of emails -->
<div>
<table class="table table-bordered">
<tbody data-bind='foreach: billDeliveryEmails'>
<tr>
<td><input class='required' data-bind='value: userName' /></td>
<td><select data-bind="options: $root.availableEmailDomains(), value: domainName, optionsText: 'domainName', optionsValue: 'domainName'"></select></td>
<td><a data-bind="click:'removeDeliveryEmailAddress'">Delete</a></td>
</tr>
</tbody>
</table>
<a class="atm-bloque-link" data-bind="click:'addDeliveryEmailAddress'">Agregue otra direccion de email</a>
</div>
VM:
// Domain class
function Domain(domainName) {
var self = this;
self.domainName = domainName;
}
billDeliveryEmails : [],
availableEmailDomains : ko.observableArray([
new Domain("hotmail.com"),
new Domain("yahoo.com")
])
addDeliveryEmailAddress: function ($element, data, context, bindingContext, event) {
bindingContext.$root.billDeliveryEmails.push({
userName: "",
domainName: this.viewModel.get('availableEmailDomains')[0]
});
event.preventDefault();
},
removeDeliveryEmailAddress: function ($element, data, context, bindingContext, event) {
bindingContext.$root.billDeliveryEmails.splice(0, 1)
event.preventDefault();
}
Based on the link in your comment, here's an example:
function Domain(domainName) {
var self = this;
self.domainName = domainName;
}
var vm = function () {
var self = this;
self.browser = ko.observable();
self.browserList = ko.observableArray([
new Domain('yahoo.com'),
new Domain('hotmail.com')
])
}();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" data-bind="value: browser" /></label>
<datalist id="browsers" data-bind="foreach: browserList">
<option data-bind="text: domainName">
</datalist>
<br />
Your browser is: <span data-bind="text: browser"></span>
An observable array is used to populate the list and a regular observable tracks the selected value.

Select field in grails workflow

I have a problem prefilling a dropdown list in an grails webflow
I have a controller for the webflow
class ClearanceRequestController {
def index() {
redirect(action: "start")
}
def startFlow = {
contact {
on('next') {
flow.developer = params.developer
flow.project = params.project
flow.projectResponsible = params.projectResponsible
flow.email = params.email
[flow : flow]
}.to('application')
on('cancel').to('finish')
...
and the view looks like this:
contact.gsp
<g:if test="${message}">
<div class="message">${message}</div>
</g:if>
<g:form action="start" method="post">
<div class="dialog">
<table>
<tbody>
<tr class="prop">
<td valign="top" class="name">
<label for="projectName">Projekt:</label>
</td>
<td valign="top">
<input type="text" id="projectName" name="project" value="${params.project}" />
</td>
</tr>
<g:select name="state" from="${Project?.DIVISION_OPTIONS}" value="${Project?.DIVISION_OPTIONS}"/>
This is the Project definition
class Project {
static DIVISION_OPTIONS = ["A", "B", "C", "D"]
String name
String division
String toString(){
"$name"
}
static constraints = {
name(unique: true)
division(inList: DIVISION_OPTIONS)
}
}
I don't know how to get the data from the constraints. I tried to access
Project.constraints.division.inList
or
Project.DIVISION_OPTIONS
but both didn't worked. I assume I have to initialize the Project somewhere and pass it to the contact.gsp, but I don't know how.
OK I got it, just import the Project in the page, like
<%# page import="com.companyName.Project" contentType="text/html;charset=UTF-8" %>
or like:
<g:select name="state" from="${com.companyName.Project?.DIVISION_OPTIONS}" value="${com.companyName.Project?.DIVISION_OPTIONS}"/>

Processing form's element(s) in JSP

I have a HTML form in JSP page, and in the I have a JavaScript validation. The user must enter one field: name or id or year, and a java file will search the student in database by name or by id or by year. The JavaScript alerts when no field is filled and performs the action if one field is filled.
<html>
<head>
<title>Student to search into database</title>
<script language="javascript">
function validate2(objForm){
int k = 0;
if(objForm.name.value.length==0){
objForm.name.focus();
k++;
}
if(objForm.year.value.length==0){
objForm.year.focus();
k++;
}
if(objForm.id.value.length==0){
objForm.year.focus();
k++;
}
if(k == 0){
return false;
}
return true;
}
</script>
</head>
<body bgcolor=#ADD8E6><center>
<form action="FoundStudents.jsp" method="post" name="entry2" onSubmit="validate2(this)">
<input type="hidden" value="list" name="seek_stud">
...........................................................................................
The problem is I want to process the parameter which I receive in FoundStudents.jsp: If I get the year, I look in DB which student(s) are in that year and display all that student(s)' data(do that in a java file). How could I do that in FoundStudents.Jsp without checking again which field is filled(I've done that in JavaScript from SearchStudent.jsp). I mean the FoundStudents.jsp calls a method in the java file for searching and displaying.
I tried by now with the input hidden that worked, but that is for more forms. I have only 1.
FoundStudent.jsp
<%#page import="stud.diploma.students.StudentsManager"%>
<%#page import="stud.diploma.students.Student"%>
<%#page import="java.util.ArrayList"%>
<%#page import="stud.diploma.database.ConnectionsManager"%>
<%# page language="java" import="java.sql.*, java.lang.*" %>
<%
Student search = null;
if(request.getParameter("seek_stud") != null){
//reading params from the SearchStudent form
String name = request.getParameter("name");
String year_prime = request.getParameter("year");
int year, id;
try{
year = Integer.parseInt(year_prime);
}catch(Exception e1){
year = 0;
}
String id_prime = request.getParameter("id");
try{
id = Integer.parseInt("id");
}catch(Exception e2){
id = 0;
}
if(name.length() != 0){
search = StudentsManager.getInstance().studByName(name);
}
if(year > 0){
search = StudentsManager.getInstance().studByYear(year);
}
if(id > 0){
search = StudentsManager.getInstance().studById(id);
}
if(search != null){
%>
<html>
<body bgcolor=#4AA02C>
<center>
<h2>Student's data</h2>
<table border="1" cellspacing="1" cellpadding="8" bgcolor= #EBDDE2>
<tr>
<td bgcolor= #FF9966><b>ID</b></td>
<td bgcolor= #FF9966><b>Name</b></td>
<td bgcolor= #FF9966><b>Year</b></td>
</tr>
<tr>
<td><%= search.getId()%></td>
<td><%= search.getName()%></td>
<td><%= search.getYear()%></td>
</tr>
</table>
</center>
</body>
</html>
<%}else{%>
<%
String redirectURL = "MainMenu.html";
response.sendRedirect(redirectURL);
%>
<%}%>
<%}%>
This FoundStudent.jsp is for the version of multiple forms (using hidden input) that worked. (the javascript test was just a little bit different, I typed it insted of what I had in the beginning)
It searched by name and by year only. Didn't search by ID (I had exception here <td><%= search.getId()%></td> I'm still trying to see how to deal with it. ID is a AUTO_INCREMENT PRIMARY KEY)
Lines like : search = StudentsManager.getInstance().studByName(name);
Search is a Student type object. (Object Student is creaded in a java file)
StudentsManager is a java class that receives calls to it's methods from JSP. getInstance() creates an instance of StudentsManager. Method studByName(name) receives the parameter name from the form and searches it in the database.
So I changed the (java)script to:
<script language="javascript">
function validateSea(){
if(document.entry2.name.value != ''){
return true;
}
else
if(document.entry2.year.value != ''){
return true;
}
alert('Please fill one field.');
return false;
}
</script>
</head>
which is for 1 form. I'm not sure if I did the correct thing, but in FoundStudents.jsp, where I receive the parameters of the form, I test:
if((request.getParameter("year") != null)||(request.getParameter("name") != null)){
//reading params from the SearchStudent form
................}
It works this way.