its a crud app i am inputting user info into a form and then saving it in an array and then rendering it into a table .I can add more rows with different user data . And i can delete a certain row from the table . I also have a edit button but i don't have no idea how to do that.
Register.html file
<div class="container">
<h2 class="page-header">Register</h2>
<form (ngSubmit)="onRegisterSubmit()" [formGroup] = "form">
<div class="form-group">
<label>Full Name</label>
<input type="text" [(ngModel)]="fullname" formControlName="fullname" class="form-control" >
</div>
<div class="form-group">
<label>Username</label>
<input type="text" [(ngModel)]="username" formControlName="username" class="form-control" >
</div>
<div class="form-group">
<label>Email</label>
<input type="text" [(ngModel)]="email" formControlName="email" class="form-control" >
</div>
<div class="form-group">
<label>Password</label>
<input type="password" [(ngModel)]="password" formControlName="password" class="form-control">
</div>
<input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid">
</form>
<br>
<br>
<table border="2" class="table table-striped">
<tr>
<th>Full Name</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
<th>Delete</th>
<th>Edit</th>
</tr>
<div > </div>
<tr *ngFor="let user of userDetails">
<td>{{user.username}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td>{{user.password}}</td>
<td><button (click)="userDelete()">X</button></td>
<td><button (click)="userEdit()">Edit</button></td>
</tr>
</table>
</div>
Register.ts file
export class RegisterComponent implements OnInit {
fullname : string;
username : string;
email : string;
password : string;
userDetails:Array<object>;
constructor(
private validateService: ValidateService,
private flashMessage:FlashMessagesService)
{ }
form;
ngOnInit() {
this.userDetails=[];
this.form = new FormGroup({
fullname : new FormControl("", Validators.required),
username : new FormControl("", Validators.required),
email : new FormControl("", Validators.required),
password : new FormControl("", Validators.required)
});
}
onRegisterSubmit(){
let user = {
fullname : this.fullname ,
username : this.username,
email : this.email ,
password : this.password
}
this.userDetails.push(user);
if(!this.validateService.validateRegister(user)){
this.flashMessage.show('Please fill in all fields', {cssClass: 'alert-danger', timeout: 3000});
return false;
}
// Validate Email
if(!this.validateService.validateEmail(user.email)){
this.flashMessage.show('Please use a valid email', {cssClass: 'alert-danger', timeout: 3000});
return false;
}
}
userDelete(){
this.userDetails.pop();
}
userEdit(){
//No logic
}
}
Validation service file
export class ValidateService {
constructor() { }
validateRegister(user){
if(user.fullname == undefined || user.email == undefined || user.username == undefined || user.password == undefined){
return false;
} else {
return true;
}
}
validateEmail(email){
const re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
To hardcode new values is simple:
<tr *ngFor="let user of userDetails; index as i">
<td>{{user.username}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td>{{user.password}}</td>
<td><button (click)="userDelete()">X</button></td>
<td><button (click)="userEdit(i)">Edit</button></td>
</tr>
userEdit(i) {
let editUser = this.userDetails[i];
editUser = { fullname: 'Tadas Blynda', etc. }
}
But what you need is probably this:
<div>
<form (ngSubmit)="onRegisterSubmit()" [formGroup] = "form" [hidden]="clicked">
<div class="form-group">
<label>Full Name</label>
<input type="text" [(ngModel)]="fullname" formControlName="fullname" class="form-control" >
</div>
<div class="form-group">
<label>Username</label>
<input type="text" [(ngModel)]="username" formControlName="username" class="form-control" >
</div>
<div class="form-group">
<label>Email</label>
<input type="text" [(ngModel)]="email" formControlName="email" class="form-control" >
</div>
<div class="form-group">
<label>Password</label>
<input type="password" [(ngModel)]="password" formControlName="password" class="form-control">
</div>
<input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid">
</form>
</div>
<div>
<form (ngSubmit)="onEditSubmit()" [formGroup] = "form" [hidden]="!clicked">
<div class="form-group">
<label>Full Name</label>
<input type="text" [(ngModel)]="fullname" formControlName="fullname" class="form-control"
placeholder="userDetails[editIndex]?.fullname" >
</div>
<div class="form-group">
<label>Username</label>
<input type="text" [(ngModel)]="username" formControlName="username" class="form-control" >
</div>
<div class="form-group">
<label>Email</label>
<input type="text" [(ngModel)]="email" formControlName="email" class="form-control" >
</div>
<div class="form-group">
<label>Password</label>
<input type="password" [(ngModel)]="password" formControlName="password" class="form-control">
</div>
<input type="submit" class="btn btn-primary" value="Submit" [disabled]="!form.valid">
</form>
</div>
<br>
<br>
<table border="2" class="table table-striped">
<tr>
<th>Full Name</th>
<th>Username</th>
<th>Email</th>
<th>Password</th>
<th>Delete</th>
<th>Edit</th>
</tr>
<div > </div>
<tr *ngFor="let user of userDetails; index as i">
<td>{{user.fullname}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td>{{user.password}}</td>
<td><button (click)="userDelete()">X</button></td>
<td><button (click)="clickEdit(i)">Edit</button></td>
</tr>
</table>
And
export class AppComponent {
fullname : string;
username : string;
email : string;
password : string;
clicked = false;
userDetails:Array<object>;
form;
ngOnInit() {
this.userDetails=[];
this.form = new FormGroup({
fullname : new FormControl("", Validators.required),
username : new FormControl("", Validators.required),
email : new FormControl("", Validators.required),
password : new FormControl("", Validators.required)
});
}
onRegisterSubmit(){
let user = {
fullname : this.fullname ,
username : this.username,
email : this.email ,
password : this.password
}
this.userDetails.push(user);
}
editIndex = null;
clickEdit(i){
this.clicked = !this.clicked;
this.editIndex = i;
}
onEditSubmit() {
let editUser = {
fullname : this.fullname ,
username : this.username,
email : this.email ,
password : this.password
}
this.userDetails[this.editIndex] = editUser;
this.clicked = !this.clicked;
}
}
Let me know please, if any issues.
Related
I'm trying to create a submit form, but all my v-model are giving me this error.
Here is one example of how I'm creating the form inputs:
<template>
<div class="card mx-xl-5">
<!-- Card body -->
<div class="card-body">
<div>
<form v-on:submit.prevent="pushLocation">
<div class="form-row">
<div class="col-md-6">
<label>Name:</label>
<input
type="text"
class="form-control"
v-model="txtLocationName"
/>
</div>
<div class="col-md-6"> <div class="card mx-xl-5">
<label>Description</label>
<input
type="text"
class="form-control"
v-model="txtLocDescription"
placeholder="Description"
/>
</div>
</div>
<div class="form-group">
<label for="type">Tipo de localização</label>
<select class="form-control" id="type" v-model="typeLoc">
<option value="museum">Museum</option>
<option value="restaurant">Restaurant</option>
<option value="tourist_attraction">Monument</option>
<option value="art_gallery">Galery</option>
</select>
</div>
<div class="col-md-6">
<label>Imagem</label>
<input type="url" class="form-control" v-model="urlImg" placeholder="Link" />
</div>
<div class="form-group row">
<div class="col-auto">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
</div>
</div>
And here is how I'm setting the properties on my script:
name: "LocationList",
data: function() {
return {
id: 0,
txtLocationName: "",
txtLocDescription: "",
typeLoc: "",
urlImg: "",
listLocation: [],
locationChecked: false
};},
methods: {
getLastLocationId() {
if (this.listLocation.length) {
return this.listLocation[this.listLocation.length - 1].id;
} else {
return 0;
}
},
checkLocationName() {
if (this.listLocation.length) {
for (const location of this.listLocation) {
if (location.Name == this.txtLocName) {
(this.locationChecked = false),
alert("nome de localização indisponivel");
} else {
this.userChecked = true;
}
}
}
},
pushLocation() {
this.checkLocationName();
this.getCoordenates();
if (this.locationChecked == true) {
this.$store.commit("ADD_USER", {
id: this.getLastLocationId() + 1,
Name: this.txtLocationName,
Description: this.txtLocDescription,
Type: this.typeLoc,
imgLink: this.urlImg
});
this.$router.push({ name: "adminLocations" });
} else {
alert("erro no registo");
}
}
}
I've done this type of forms multiple times, yet I can figure out why i'm having this error.I added the rest of my vue component. I get the error on all the property and methods, not only on "urlImg".Meaning all the properties that exist in the data and are in the form are giving me this error.
One last point, the final function, pushLocation() is also giving the error, saying that it is not a real function.
After i submit the form and re-initialize the form it still doesn't reset the validations. I have tried multiple solution but it still does not work
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
this.form.clearValidators();
this.form.clearAsyncValidators();
None of this actually do the job.
This is my html code:
<form [formGroup]="form">
<div class="row">
<mat-form-field style="margin-top: 20px; margin-left: 20px">
<input [errorStateMatcher]="matcher" formControlName="name" matInput placeholder="Prescurtare">
<mat-error *ngIf="form.controls['name'].hasError('required')">
Introduceti o valoare
</mat-error>
</mat-form-field>
</div>
<div class="row">
<mat-form-field style="margin-top: 20px; margin-left: 20px">
<input formControlName="fullName" matInput placeholder="Nume complet">
<mat-error *ngIf="form.controls['name'].hasError('required')">
Introduceti o valoare
</mat-error>
</mat-form-field>
</div>
<div class="col-xs-12" formArrayName="groups">
<label for="imagePath">Grupe</label>
<button mat-icon-button color="primary" (click)="addNewDepartment()">
<mat-icon aria-label="Example icon-button with a heart icon">add</mat-icon>
</button>
<div class="row" *ngFor="let ingredientCtrl of form.get('groups').controls; let i = index" [formGroupName]="i" style="margin-top: 10px;">
<mat-form-field style="margin-left: 50px">
<input formControlName="name" matInput placeholder="Nume">
<mat-error *ngIf="form.get('groups').controls[i].hasError('required')">
Introduceti o valoare
</mat-error>
</mat-form-field>
<mat-form-field style="margin-left: 50px">
<input formControlName="year" matInput placeholder="Anul" [matAutocomplete]="auto">
<mat-error *ngIf="form.get('groups').controls[i].hasError('required')">
Introduceti o valoare
</mat-error>
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of options" [value]="option">{{option}}</mat-option>
</mat-autocomplete>
<div class="col-xs-2">
<button mat-icon-button color="accent" (click)="onDeleteDepartment(i)">
<mat-icon aria-label="Delete">delete</mat-icon>
</button>
</div>
</div>
</div>
<button type="submit" [disabled]="!form.valid" (click)="onSubmit()" class="btn btn-success" style="margin-top: 20px">Salveaza</button>
</form>
My typescript code:
form: FormGroup;
private initForm() {
let name = '';
let fullName = '';
const groups = new FormArray([], [Validators.required]);
this.form = new FormGroup(
{
'name': new FormControl(name, [Validators.required]),
'fullName': new FormControl(fullName, [Validators.required]),
'groups': groups
});
this.matcher = new DepartmentStateMatcher();
}
onSubmit() {
this.dataService.addDepartment(this.form.value);
this.resetForm();
setTimeout(() => { this.exampleDatabase.departmentsChange.value.push(this.dataService.getDialogData()); this.refreshTable(); }, 100);
}
private resetForm() {
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
this.form.clearValidators();
this.form.clearAsyncValidators();
let name = '';
let fullName = '';
const groups = new FormArray([], [Validators.required]);
this.form = new FormGroup(
{
'name': new FormControl(name, [Validators.required]),
'fullName': new FormControl(fullName, [Validators.required]),
'groups': groups
});
this.matcher = new DepartmentStateMatcher();
}
export class DepartmentStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
}
}
I would expect that validations would be reset but they are not.
I am using reactive forms Angular 4 and added a custom validator addressValidation to the form group - addressGroup.
I am updating all fields to mark as touched on submit click. Looks like the custom validator addressValidation doesn't trigger eventhough I marked all fields as touched. I tried marking the formgroup (addressGroup) as touched and dirty on submit but no help.
In general what I am trying to achieve is - By default I want to make street number and Street name required. If po box is entered then street number and Name is not required. Apt # is only required only if street number and name is entered. I am trying to achieve this on the custom validator in the formGroup.
Any idea on what I am doing wrong. Any other alternate way to achieve the above requirement. I am new to Angular and slowly learning the concepts. Any suggestion on How to trigger the custom validator on submit.
buildForm(): void {
this.contactForm = this.fb.group({
emailAddressControl: ['', [Validators.required, Validators.email, Validators.maxLength(100)]],
phoneControl: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]],
addressGroup: this.fb.group({
streetNumber: ['', [Validators.maxLength(10)]],
pOBox: ['', [Validators.maxLength(8)]],
aptNumber: ['', [Validators.maxLength(8)]],
streetName: ['', [Validators.maxLength(60)]],
cityControl: ['', [Validators.required, Validators.maxLength(50)]],
stateControl: ['', [Validators.required, Validators.maxLength(2)]],
zipControl: ['', [Validators.required, Validators.maxLength(14)]],
countryControl: ['UNITED STATES OF AMERICA', [Validators.required]],
}, { validator: addressValidation })
})
this.contactForm.valueChanges
.debounceTime(800)
.subscribe(data => this.onValueChanged(data));
this.onValueChanged();
}
onSubmit(): void {
this.markAllFormFieldsAsTouched(this.contactForm);
this.onValueChanged();
}
private markAllFormFieldsAsTouched(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
console.log(field);
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
}
else if (control instanceof FormGroup) {
this.markAllFormFieldsAsTouched(control);
control.markAsTouched({ onlySelf: true });
}
else if (control instanceof FormArray) {
for (let formgroupKey in control.controls) {
let formgroup = control.controls[formgroupKey];
if (formgroup instanceof FormGroup) {
this.markAllFormFieldsAsTouched(formgroup);
}
}
}
});
}
function addressValidation(c: AbstractControl): { [key: string]: boolean } | null {
if (c.pristine) {
return null;
}
const pOBoxControl = c.get('pOBox');
const streetNameControl = c.get('streetName');
const streetNumberControl = c.get('streetNumber');
const aptNumberControl = c.get('aptNumber');
if (pOBoxControl.value === null || pOBoxControl.value === "") {
if (streetNumberControl.value === null || streetNumberControl.value === "") {
return { ['streetNumberRequired']: true, ['streetNameRequired']: true };
}
if (streetNameControl.value === null || streetNameControl.value === "") {
return { 'streetNameRequired': true };
}
}
else {
if ((streetNameControl.value === null || streetNameControl.value === "")
&& (streetNameControl.value === null || streetNumberControl.value === "") && aptNumberControl.value !== "") {
return { 'apartmentNumberInvalid': true };
}
}
}
Template
<div class="card">
<div class="card-header bg-info text-white">
<h2>Mailing Address:</h2>
</div>
<div formGroupName="addressGroup" class="card-body">
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<label class="form-control-label">PO Box:</label>
<input class="form-control"
[ngClass]="displayFieldCss('pOBox')"
type="text"
formControlName="pOBox"
placeholder=""
maxlength="8" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('pOBox')">
{{validationMessage.pOBox}}
</span>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label class="form-control-label">Street Number:</label>
<input class="form-control"
[ngClass]="displayFieldCss('streetNumber')"
type="text"
formControlName="streetNumber"
placeholder=""
maxlength="10" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('streetNumber')">
{{validationMessage.streetNumber}}
</span>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label class="form-control-label">Apt Number:</label>
<input class="form-control"
[ngClass]="displayFieldCss('aptNumber')"
type="text"
formControlName="aptNumber"
placeholder=""
maxlength="8" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('aptNumber')">
{{validationMessage.aptNumber}}
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label class="form-control-label">Street Name:</label>
<input class="form-control"
[ngClass]="displayFieldCss('streetName')"
type="text"
formControlName="streetName"
placeholder=""
maxlength="60" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('streetName')">
{{validationMessage.streetName}}
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<div class="form-group">
<label class="form-control-label">City:</label>
<input class="form-control"
[ngClass]="displayFieldCss('cityControl')"
type="text"
formControlName="cityControl"
placeholder="(required)"
maxlength="50" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('cityControl')">
{{validationMessage.cityControl}}
</span>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label class="form-control-label">State/Province (Code):</label>
<input class="form-control"
[ngClass]="displayFieldCss('stateControl')"
type="text"
formControlName="stateControl"
placeholder="(required)"
maxlength="3" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('stateControl')">
{{validationMessage.stateControl}}
</span>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label class="form-control-label">Zip:</label>
<input class="form-control"
[ngClass]="displayFieldCss('zipControl')"
type="text"
formControlName="zipControl"
placeholder="(required)"
maxlength="14" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('zipControl')">
{{validationMessage.zipControl}}
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label class="form-control-label">Country:</label>
<input class="form-control"
[ngClass]="displayFieldCss('countryControl')"
type="text"
formControlName="countryControl"
placeholder="(required)"
maxlength="50" />
<span class="invalid-feedback" *ngIf="isValidToDisplayErrors('countryControl')">
{{validationMessage.countryControl}}
</span>
</div>
</div>
</div>
</div>
</div>
You must use control.updateValueAndValidity() like this
onSubmit(): void {
if (this.form.valid) {
} else {
this.validateAllFormFields(this.committeForm);
this.logValidationErrors(this.committeForm);
this.scrollToError();
}
}
validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.updateValueAndValidity()
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
I have the following form:
<form role="form" [ngFormModel]="userEditForm" (ngSubmit)="editUser(user)">
<div>
<label for="username">Username</label>
<input type="text" #username id="username" placeholder="Username" [ngFormControl]="userEditForm.controls['username']">
</div>
<div>
<label for="firstName">First Name</label>
<input type="text" #firstName id="firstName" placeholder="First Name" [ngFormControl]="userEditForm.controls['firstName']">
</div>
<div>
<label for="lastName">Last Name</label>
<input type="text" #lastName id="lastName" placeholder="Last Name" [ngFormControl]="userEditForm.controls['lastName']">
</div>
<div>
<label for="email">Email</label>
<input type="text" #email id="email" placeholder="Email" [ngFormControl]="userEditForm.controls['email']">
</div>
<button type="submit">Submit</button>
And in my component I have defined:
constructor(private _routeParams:RouteParams, private _formBuilder:FormBuilder, private _UserInject:UserInject){
this.userEditForm = _formBuilder.group({
'firstName': [this.user.firstName],
'lastName': [this.user.lastName],
'username': [this.user.username],
'email': [this.user.email],
})
}
ngOnInit(){
let id = this._routeParams.get('userId');
this.user = this._UserInject.getUser(id);
}
}
However, this creates an error, because this.user is not yet defined in the constructor. Any ideas?
UPDATE
It works when I use formBuilder in the ngOnInit - however, I am not sure if thats a proper way to do it.
Just move
this.userEditForm = _formBuilder.group({
'firstName': [this.user.firstName],
'lastName': [this.user.lastName],
'username': [this.user.username],
'email': [this.user.email],
})
after the code where you assign this.user (into ngOnInit())
Hi i am new in thymeleaf + spring and i start learn it.
and wanted to integrate these 2 form in one page .
that means now 2 forms are in 2 different pages and the th:action are different ..
here i want these 2 forms work in one page
i tried that with a page with 2 forms and 2 actions but that caught error..
Create Standard Code
<form action="#" th:action="#{/saveStandard.html}" th:object="${standard}">
<table>
<h1>Create Standard</h1>
<tr>
<td>Standard Name:</td>
<td><input type="text" placeholder="Enter Standard Name" required="required"
th:field="*{standardName}"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" name="save" /></td>
</tr>
</table>
</form>
Create Division Code
<form action="#" th:action="#{/saveDivision.html}"
th:object="${division}">
<table>
<td>Division Name:</td>
<tr>
<td><input type="text" placeholder="Enter Division Name" required="required"
th:field="*{divisionName}" />
</td>
</tr>
<td><input type="submit" class="btn btn-primary" value="Create"
name="save" /></td>
</table>
</form>
these are controllers..
#RequestMapping(value = Array("/saveStandard.html"), params = Array({ "save" }))
def saveStandard(standard: Standard): String = {
standard.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
standardService.addStandard(standard)
"redirect:/school/CreateStandard.html"
}
#RequestMapping(value = Array("/saveDivision.html"), params = Array({ "save" }))
def saveDivision(division: Division): String = {
division.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
divisionService.addDivision(division)
"redirect:/school/CreateDivision.html"
}
if you knew about this question please share your answer here..
and Thanks...
Hi It is posible here a example
HTML Example
<section id="registration" class="section">
<div class="container tagline">
<em>Register User</em><br />
<form method="post" th:action="#{/user/register}" th:object="${newUser}">
<div>
<label for="givenName">Id</label>
<input id="id" placeholder="Enter Id" type="text" th:field="*{id}" />
<p th:if="${#fields.hasErrors('id')}" th:text="${#strings.listJoin(#fields.errors('id'), ', ')}">
</p>
</div>
<div>
<label for="givenName">Name</label>
<input id="name" placeholder="Enter Name" type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}"
th:text="${#strings.listJoin(#fields.errors('name'), ', ')}"></p>
</div>
<div>
<label for="email">Email</label>
<input id="email" placeholder="Enter the Email" type="text" th:field="*{email}" />
<p th:if="${#fields.hasErrors('email')}"
th:text="${#strings.listJoin(#fields.errors('email'), ', ')}"></p>
</div>
<button type="submit">Create user</button>
</form>
</div>
</section>
<div>
<form method="get" th:action="#{/user/searchById}" th:object="${searchUser}">
<input id="id" placeholder="Search by id" type="text" th:field="*{id}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByName}" th:object="${searchUser}">
<input id="id" placeholder="Search by Name" type="text" th:field="*{name}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByEmail}" th:object="${searchUser}">
<input id="id" placeholder="Search by Email" type="text" th:field="*{email}" size="10" >
<button type="submit" >search</button>
</form>
</div>
Spring
#Controller
#RequestMapping("/user")
public class User {
BookingFacadeUserImp userService = new BookingFacadeUserImp();
#GetMapping()
public ModelAndView init() {
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#PostMapping("/register")
public ModelAndView saveUser(#Valid #ModelAttribute("newUser") UserDTO user, BindingResult result)
throws NumberFormatException, ParseException {
System.out.println("Register: " + user);
userService.createUser(user);
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#GetMapping("/delete/{id}")
public ModelAndView delete(#PathVariable long id) {
userService.deleteUser(id);
return init();
}
#PostMapping("/update")
public ModelAndView updateUser(#ModelAttribute("updateUser") UserDTO user) {
userService.updateUser(user);
return init();
}
#GetMapping("/searchById")
public ModelAndView searchById(#ModelAttribute("searchUser") UserDTO user) {
if (user.getId() > 0)
return getModelView().addObject("users", getUsersById(user.getId()));
else
return init();
}
#GetMapping("/searchByName")
public ModelAndView searchByName(#ModelAttribute("searchUser") UserDTO user) {
if (!user.getName().equals(""))
return getModelView().addObject("users", getUsersByName(user.getName(),100,0));
else
return init();
}
public ModelAndView getModelView() {
ModelAndView model = new ModelAndView("user");
model.addObject("newUser", new UserDTO());
model.addObject("searchUser", new UserDTO());
return model;
}
public List<UserDTO> getUsersById(long id) {
List<UserDTO> list = new ArrayList<UserDTO>();
list.add((UserDTO) userService.getUserById(id));
return list;
}
public List<com.example.demo.task1.model.User> getUsersByName(String name, int pageSiza, int pageNum) {
return userService.getUsersByName(name, pageSiza, pageNum);
}
public List<com.example.demo.task1.model.User> getUsersByEmail(String email) {
return (List<com.example.demo.task1.model.User>) userService.getUserByEmail(email);
}
}