How to filter data in Thymeleaf table - spring-boot

I'm a new Thymeleaf developer (Spring-Boot 2.1.5 environment).
I want to implement filtering over a list from an Input. When I enter the name of the client in the input it appears on a table (without submit button).
<form th:action="#{/clientslistbypage}" method="get" th:object="${Clients}" class="form-inline" >
<input type="text" name="client" th:value="${client}" id="clientSearch" >
<!-- <input type="submit" name="clients" th:value="Search">-->
</form>
I tried the Projection and Collection function but I do not know how to dynamically assign the input value to the Collection formula.(${Clients.?[firstName >='here i want to insert the value of the Searche Input']})
<tr th:each = "c: ${Clients.?[firstName >='']}" >
<td th:text = "${c.id}"></td>
<td th:text = "${c.firstName}"></td>
<td th:text = "${c.LAST_NAME} "></td>
</tr>
I tried DANDELION but unfortunately, do not run under Spring-Boot 2.1.5.
any proposal, tutorial, or example is welcome

Related

Thymeleaf generates URL with no query parameters, but '?' appears

I'm working on a simple Spring Boot MVC application using Thymeleaf.
Part of the thymeleaf code:
<tr th:each="dept: ${departments}">
<td th:text="${dept.getId()}"></td>
<td th:text="${dept.getName()}"></td>
<td>
<form th:object="${dept}" th:action="#{'/departments/' + ${dept.getId()}}">
<button class="btn btn-secondary">Details</button>
</form>
</td>
<td>
<form th:object="${dept}" th:action="#{/departments/{id}/edit(id=${dept.getId()})}">
<button class="btn btn-secondary">Edit</button>
</form>
</td>
<td>
<form th:object="${dept}" th:action="#{/departments/{id}(id=${dept.getId()})}" th:method="delete">
<button class="btn btn-secondary">Delete</button>
</form>
</td>
</tr>
The UI interface looks like this:
When clicking on the Edit button (same goes for the Details one), it loads correctly, but the URL generates the ? character for other query parameters, but there are actually none (for example http://localhost:8089/departments/3/edit?).
The controller code is:
#GetMapping("/{id}/edit")
public String editDepartment(#PathVariable("id") String departmentId, Model model) {
var department = departmentService.getDepartmentById(Long.valueOf(departmentId));
model.addAttribute("department", department);
return "edit-department"; // returns view
}
My problem is with the ? character that is being displayed. I don't want it to appear as there are no query parameters. Any help?
It's adding a question ? because you are submitting an empty form. Why not just use a link styled as a button?
<a class="btn btn-secondary" th:href="#{/departments/{id}/edit(id=${dept.id})}" role="button">Edit</a>
Try
<form th:object="${dept}" th:action="#{/departments/edit/{id}(id=${dept.getId()})}">

How do I compare and verify user input field to stored data BEFORE to sending form in ColdFusion

I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)
Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.
My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.
What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.
I do this as a hobby, am self-taught and am not sure if it’s even possible (or good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.
I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.
Here's the code I'm putting together:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/scripts/jquery.validate.js"></script>
<script>
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "/components/promocodecomponent.cfc?method=validateUserName"
}
}
});
});
</script>
<div class="row justify-content-center">
<div class="col-10">
<form id="signupform" autocomplete="off" method="get" action="">
<table>
<tr>
<td class="label">
<label id="lfirstname" for="firstname">First Name</label>
</td>
<td class="field">
<input id="firstname" name="firstname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="llastname" for="lastname">Last Name</label>
</td>
<td class="field">
<input id="lastname" name="lastname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lusername" for="username">Username</label>
</td>
<td class="field">
<input id="username" name="username" type="text" value="" maxlength="50">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="field" colspan="2">
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</td>
</tr>
</table>
</form>
</div>
</div>
Here's the component code:
component {
remote boolean function validateUserName(string username) returnFormat="json"{
if (arguments.username == "john") {
return true;
}
return "Username already in use";
}
}
Usually, you'd need to post some code that you've tried and isn't working. But you've outlined what you want and are just not sure where to start.
You can test just the value of the discount code before allowing the whole form to be submitted. You don't say how you're doing client-side form validation. I'd suggest using jQuery Validate to handle that, it's very easy to implement.
https://jqueryvalidation.org/documentation/
Go to the demo "The Remember The Milk sign-up form". This form checks the username field via Ajax before the rest of the form can be submitted.
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "users.action"
}
}
});
If not using this framework, then just make an Ajax request when change is triggered on the discount code field and make sure there's a positive response from that before you allow the form to be submitted.
Also, you need to do server-side validation of the discount code when someone submits the form. If they've entered a discount code that is invalid, then don't allow the form to be processed until they enter a valid code or they clear the value from that field.
I do this as a hobby, am self-taught ... I imagine ... would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.
The plugin is easy to use but there may be a slight learning curve depending on your jQuery and javascript skills. Bigger tasks are easier to tackle if you you break them into smaller ones and solve those one at a time. Start with the code snippet #AdrianJMoreno posted and delve into the documentation to understand what the code is doing and how:
validate() - a function that initializes the plugin for a specific form
rules - options that tells the plugin which form fields should be validated and how
remote - remote url to be called via ajax to validate a field's value. The remote endpoint should either return true/false or true/"some custom error message";
1. Build Sample Form
Once you have a sense of how the plugin works, move on to building a scaled down version of the Milk demo form using the code snippet.
JQuery and Validate libraries
<!-- modify js paths as needed -->
<script src="scripts/jquery-3.1.1.js"></script>
<script src="scripts/jquery.validate.min.js"></script>
Javascript initialization (so plugin validates the form)
<script>
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "users.action"
}
}
});
});
</script>
HTML form (only the fields in code snippet)
<form id="signupform" autocomplete="off" method="get" action="">
<table>
<tr>
<td class="label">
<label id="lfirstname" for="firstname">First Name</label>
</td>
<td class="field">
<input id="firstname" name="firstname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="llastname" for="lastname">Last Name</label>
</td>
<td class="field">
<input id="lastname" name="lastname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lusername" for="username">Username</label>
</td>
<td class="field">
<input id="username" name="username" type="text" value="" maxlength="50">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lsignupsubmit" for="signupsubmit">Signup</label>
</td>
<td class="field" colspan="2">
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</td>
</tr>
</table>
</form>
2. Test (Sample Form)
Test out the form in a browser. Since all fields are required, leaving the fields blank and submitting should trigger error messages on submit
3. Create Remote URL
The live demo form uses a mocking library to simulate a remote ajax call. The mock url "users.action" must be replaced with a real url on your server. That url will point to a new component (or "CFC") you create. The component should contain a remote accessible method that validates a given username.
Keep things simple for the initial test. Have the method return true if the input equals a test value like "John" and false for everything else. Ultimately you'll replace that with real business logic, like a database lookup, but one step at a time.
YourComponentName.cfc
component {
remote boolean function validateUserName(string username) returnFormat="json"{
if (arguments.username == "john") {
return true;
}
return false;
}
}
4. Test (Remote URL)
To test a remote method in a browser, specify the path, name of the method to invoke, and any parameters that method expects. Verify the component returns the expected results. The result should be true for username=John and false for any other value.
Example url:
https://localhost/path/YourComponentName.cfc?method=validateUsername&username=john
Valid: UserName=John:
InValid: UserName=Bob:
5. Fix Remote URL
With the component working, update the javascript code to point to the new cfc. Omit the username parameter because the plugin will pass it to the ajax call automatically.
For example, if the component location on disk is:
c:\path\webroot\path\YourComponentName.cfc
Use the url:
/path/YourComponentName.cfc
JS Snippet:
...,
username: {
...,
remote: "/path/YourComponentName.cfc?method=validateUserName"
}
6. Test Form (.. are you sensing a theme?)
Test the final form again with both a valid and invalid usernames to confirm it works as expected.
Invalid usernames "Mike" or "Bob" should trigger an error
Valid username "John" should not trigger an error
Next Steps ...
Continue to expand the working example and learn more about the plugin features by adding some customization. The next steps are left as an exercise for the reader ...
Replace hard coded test logic in the cfc with a database lookup
Replace default error message "Please fix this field" with a more user friendly message
Change the appearance of valid and invalid fields using CSS

Why "checked" attribute doesn't apply to my Thymeleaf's checkboxes?

I was working with Spring and Thymeleaf when I've encountered the following problem: I need a Form object, which has a list of items (Item) as attribute; I'm using an html form to print the Name of the Item, and to generate a checkbox for each Item (any checkbox's value is the corresponding item's id).
The form works correctly, sending to the Controller a list of item's ids corresponding to the checked checkboxes.
However, now, I'm trying to check some checkbox upon the occurrence of a condition (if itemIds, which is a list, contains the current item's id). For that I'm using:
th:checked="${#lists.contains(itemIds, item.id)}"/>
But it doesn't work (checkbox are all unchecked).
I tried also with a "dummy test":
th:checked="${1 == 1 ? 'checked' : ''}"/>
But, again, all the checkbox remain unchecked; the "checked" attribute is ignored as you can see in this example of the rendered HTML:
<input type="checkbox" value="12" class="chkCheckBox" id="ids1" name="ids">
What am I doing wrong? What am I missing here?
form.html
<form th:action="#{${uriBase}+'/new/' + ${date}}"
method="POST" th:object="${form}">
<div class="table-responsive">
<table class="table">
<thead class=" text-primary">
<tr>
<th>Name</th>
<th><input type="checkbox" th:id="checkAll"/>Check</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${items}">
<td th:text="${item.name}"></td>
<td>
<input type="checkbox" th:field="*{ids}"
th:value="${item.id}" th:class="chkCheckBox"
th:checked="${#lists.contains(itemIds, item.id)}"/>
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary pull-right">Submit</button>
<div class="clearfix"></div>
</div>
</form>
Form class
public class Form implements Serializable {
private List<Long> ids;
//getter and setter
}
Thank you in advance.
I have been struggling with this as well. If you use the th:field it will override the checked and value options, as Xaltotun mentions, because it is trying to get the value and checked option from the field/form.
If you change it to th:name it should work how you want...
But this forum seems to be helpful for doing it with th:feild.
As far as I understand there are 2 issues in your post:
The dummy example is incorrect.
th:checked="${1 == 1 ? 'checked' : ''}"
In fact the value must true or false not 'checked'. If you try with
th:checked="${1 == 1}"/>
It will work.
If you set th:field="*{ids}" then the checkbox should be trying to get the value from the field item.ids and will not use the "th:checked" or "th:value" properties. Does the item has the field ids?

Angular 2 doesn't update my view after I add or edit item

I've finally made my app in angular 2. Everything is solved, except one thing. When I add item into my table or edited it, I can't see the change until I refresh page or click for example next page button (I have implemented pagination). I included:
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
in this order. My method for adding item is very simple:
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(departments => this.department = departments.json());
this.getAll();}
Whhen I add item, and put breakpoint on get method, It is called correctly and I get right information from my DB, but I don't know why view isn't refreshed then. Do you have any idea why is it happened? Thanks for suggestions!
EDIT: department is just department: Department, where Department is interface with properties (departmentNo, departmentName, departmentLocation). The view for adding item looks like:
<form [ngFormModel]="myForm"
(ngSubmit)="addDepartment(newItem); showAddView=false" [hidden]="!showAddView" align="center">
<div>
<label for="editAbrv">Department name:</label><br>
<input type="text" [(ngModel)]="newItem.departmentName" [ngFormControl]="myForm.controls['departmentName']" >
<div *ngIf="myForm.controls['departmentName'].hasError('required')" class="ui error message"><b style="color:red;">Name is required</b></div>
</div>
<br/>
<div>
<label for="editAbrv">Department Location:</label><br>
<input type="text" [(ngModel)]="newItem.departmentLocation" [ngFormControl]="myForm.controls['departmentLocation']" >
<div *ngIf="myForm.controls['departmentLocation'].hasError('required')" class="ui error message"><b style="color:red;">Location is required</b></div>
</div>
<br/>
<div>
<button type="submit" [disabled]="!myForm.valid" class="ui button">Add item</button>
<button><a href="javascript:void(0);" (click)="showHide($event)" >
Cancel
</a></button>
</div>
</form>
and my department table is:
<table align="center">
<thead>
<tr>
<td>#</td>
<td><strong>Department</strong></td>
<td><strong>Department Location</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
<tbody>
<tr *ngFor="#department of departments | searchString:filter.value ; #i = index">
<td>{{i + 1}}.</td>
<td> {{department.departmentName}}</td>
<td>{{department.departmentLocation}}</td>
<td>
<button class="btnEdit" (click)="showEdit(department)">Edit</button>
</td>
<td>
<button class="btnDelete" (click)="deleteDepartment(department)" >Delete</button>
</td>
</tr>
</tbody>
</table>
With this code, you don't wait for the response of the addDepartment request and execute the getAll request directly.
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(departments => this.department = departments.json());
this.getAll();
}
You should move the call to getAll within the callback registered in subscribe. At this moment, the addDepartment is actually done and you can reload the list...
The code could be refactored like this (it's a guess since I haven't the content of addDepartment and getAll methods):
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(addedDepartment => {
this.department = this.getAll();
});
}
This issue occurs because of the way you're using departmant and how change detection works. When you use *ngFor="#department of departments", angular change detection looks for a object reference on departments array. When you update/change one of the items in this array object reference to the array itself doesn't change, so angular doesn't run change detection.
You have few options:
1) change reference of the array by replacing it with new array with updated values
2) tell angular explicitly to run change detection (which I think is easier in your case):
constructor(private _cdRef: ChangeDetectorRef) {...}
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(departments => this.department = departments.json());
this.getAll();
this._cdRef.markForCheck();
}

How to edit a list of child entities in Spring 3 MVC

How would I edit an entity with child rows in Spring 3 MVC?
I'd like a form like:
<forms:form>
<p>Parent name <forms:input path="model.name" type="text" /></p>
<p>Children:
<ul>
<s:foreach in="${model.children}" var="${child} varStatus="row">
<li>
name: <forms:input path="model.children[${row.index}].name" />
<button name="?">delete</button>
</li>
</s:foreach>
</ul>
</p>
<p><button name="?">add child</button></p>
</forms:form>
I'm having a lot of trouble getting this to work in Spring 3.
I would love to be able to:
edit child properties inline on the parent's form, with validation etc.
delete children inline on the parent's form
add children inline on the parent's form
Have you checked out jqGrid?
If you want DIY, then have a nested loop and create the crud links in the inner loop.
An HTML table might be appropriate for presentation.
Here is part of the "child" loop.
<tbody style="background: #ccc">
<c:forEach items="${parent.children}" var="work">
<tr>
<td>${work.id}</td>
<td>${work.title}</td>
<spring:url var="editWorkUrl" value="/work/edit/${work.id}" />
<spring:url var="deleteWorkUrl" value="/work/delete/${work.id}" />
<td>Edit
</td>
<td>Delete
</td>
</tr>
</c:forEach>
</tbody>

Resources