Spring how to use select with Thymeleaf [duplicate] - spring

I want to create a drop down menu that allows a client to search users by a field specified in the drop down menu. For example, search by state, search by city, etc.
This is what I have so far:
<p>Search options:</p>
<form action="#" th:action="#{/get/{value}" method="get">
<select>
<option th:value="AllUsers">Search all users</option>
<option th:value="ByUsername">Search by user name</option>
<option th:value="ByFirstname">Search by first name</option>
<option th:value="ByLastname">Search by last name</option>
<option th:value="ByAddress">Search by address</option>
<option th:value="ByCity">Search by city</option>
<option th:value="ByState">Search by state</option>
<option th:value="ByZipCode">Search by zip code</option>
<option th:value="ByPhoneNumber">Search by phone number</option>
<option th:value="ByEmail">Search by email</option>
</select>
<input type="text" th:field="value" name="searchField"/>
<input type="submit" value="Search" name="searchButton"/>
</form>
I'm just not sure how to connect the action and the value tag of the currently selected item in the drop down list to specify the URI. If a user selects, search by state, and he enters in "Maryland", how do I specify the corresponding URI tag?
This would be my method in Spring that executes the action:
#RequestMapping(value = "/get/ByState", method = RequestMethod.GET)
public String getByState() {
// ...
}
#RequestMapping(value = "/get/ByCity", method = RequestMethod.GET)
public String getByCity() {
// ...
}

Because the accepted answer is not using Thymeleaf and this question is top in Google I'm adding my solution here.
In my situation statues is a list of Enum values. Model attribute is populated as usually you do in Spring:
mav.addObject("statuses", EnumSet.allOf(Status.class));
Group has a filed of type Status (the enum).
<div class="form-group row">
<select class="form-control" id="status" name="status">
<option th:each="stat : ${statuses}"
th:value="${stat}"
th:text="${stat}"
th:selected="${stat.equals(group.status)}"/>
</select>
</div>
This automatically populates the list and selects value that is selected in my Group instance:

You have just the required answer in this link:
http://fruzenshtein.com/spring-mvc-form-select-tag/

Related

Form's dropdown menu selected items are null

My problem is very strange. I have a small form which has two drop down menus to select items and create a new item with those two included. Here is the object's most basic values:
public class Rental {
private Integer id;
private Movie movie;
private Client client;
}
The problem is as follows. My HTML file has this form:
<h1>Add New Rental</h1>
<form action="#" th:action="#{/rentals/add}" th:object="${rental}" method="post" >
<div class="form-group col-md-8">
<label for="client" class="col-form-label">Client</label>
<select class="form-control" th:field="*{client}" id="client">
<option disabled selected="selected" value="0">Select Client</option>
<option th:each="clnt : ${listClients}" th:value="${clnt}" th:text="${clnt.name + ' ' + clnt.lastname}"></option>
</select>
</div>
<div class="form-group col-md-8">
<label for="movie" class="col-form-label">Movie</label>
<select class="form-control" th:field="*{movie}" id="movie">
<option disabled selected="selected" value="0">Select Movie</option>
<option th:each="mov : ${listMovies}" th:value="${mov}" th:text="${mov.title}"></option>
</select>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-primary" value=" Submit ">
</div>
</form>
And the controller that handles this page is as follows:
#RequestMapping(path = "/rentals", method = RequestMethod.GET)
public String listRentals(Model model) {
model.addAttribute("rental", new Rental());
model.addAttribute("listRentals", this.MCRService.getRentals());
model.addAttribute("listClients", this.MCRService.getClients());
model.addAttribute("listMovies", this.MCRService.getMovies());
return "rentals";
}
#RequestMapping(value = "/rentals/add", method = RequestMethod.POST)
public String addRental(#ModelAttribute("rentals") Rental rent) {
Client client = this.MCRService.getClient(rent.getClient().getId());
Movie movie = this.MCRService.getMovie(rent.getMovie().getId());
if (((client.getRentalCollection().size() + 1) * 10) <= client.getBalance()) {
client.addMovie(movie);
this.MCRService.updateClient(client);
this.MCRService.updateMovie(movie);
}
return "redirect:/rentals";
}
But when I run this, select both a client and a movie, and I press submit, the console throws a NullPointerException, and turns out that the client and the movie are both null, which is weird since I'm using the entire object in the selection. What am I doing wrong here? Is it some sort of problem with the th:value and th:field? Or is my code flawed? Any help is appreciated!
I've solved it in this way. The changes to the html were in addding selectpicker to the select's class and changing the client's and movie's option for each's value to the id.
<select class="form-control selectpicker" th:field="*{client}" id="client">
<option disabled selected="selected" value="0">Select Client</option>
<option th:each="clnt : ${listClients}" th:value="${clnt.id}" th:text="${clnt.name + ' ' + clnt.lastname}"></option>
<select class="form-control selectpicker" th:field="*{movie}" id="movie">
<option disabled selected="selected" value="0">Select Movie</option>
<option th:each="mov : ${listMovies}" th:value="${mov.id}" th:text="${mov.title}"></option>
The java wasnt modified greatly, but with those three changes, the whole thing works!

How do I pass the selected dropdown value to a controller in Thymeleaf?

How to transfer the selected value of the drop-down list (Thymeleaf) to the controller (Spring)? The list itself is formed normally, the problem is in the button.
Controller:
#RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (#RequestParam String task) {
System.out.println(task);
return "redirect:/courier";
}
View:
<div class="taskList" th:object="${task}">
<select class="form-control" id="courierTasks" name="courierTasks">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
<form th:action="#{/courier/notInTime}" method="post">
<input type="hidden"/>
<button type="submit">Not in time</button>
</form>
</div>
You just change #RequestParam to #Valid in your controller then change your select name to "task" in Thymeleaf and it should be into the form wrapper.
#RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (#Valid String task) {
System.out.println(task);
return "redirect:/courier";
}
<select class="form-control" id="courierTasks" name="task">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
You should add the select tag inside the form, so the form submits the task.
Try the following
<form th:action="#{/courier/notInTime}" method="post">
<div class="taskList" th:object="${task}">
<select class="form-control" id="courierTasks" name="courierTasks">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
<input type="hidden"/>
<button type="submit">Not in time</button>
</div>
</form>
Note that you can write a simple javascript function so the form submits the task even if its outside the form, however, I cannot see the reason not to add the select in the form at your case.
#Sopheak #Ioannis many thx.
Controller:
#RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (#Valid String task) {
System.out.println(task);
return "redirect:/courier";
}
View:
<form th:action="#{/courier/notInTime}" method="post">
<select class="form-control" id="task" name="task">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
<button type="submit">Not in time</button>
</form>

How to set a null value inside a drop-down selection without "parent_id" required

I would like to make a drop-down selection with the first selection comes with " NO PARENT ID REFERRED " and set as null value and pass into database in laravel
Here is my code
<div class="form-group">
<label for="bit_app_policy_category_parent">Parent Category</label>
<select id="bit_app_policy_category_parent" name="parent_id" class="form-control">
<option selected disabled>Please select one option</option>
#foreach($parents as $parent)
#if ($parent-> status != 'Freeze')
<option value="{{ $parent->id}}">{{$parent->description}} </option>
#endif
#endforeach
</select>
</div>
<div class="form-group">
<label for="bit_app_policy_category_status">Status<span class="required">*</span></label>
<select id="bit_app_policy_category_status" name="status" class="form-control">
<option value="Active">Active</option>
<option value="Freeze">Freeze</option>
</select>
</div>
Dropdown selection`
Expected result =
Please select one option
-----No parent ID referred-----(able to choose and pass value into db)
description 11 and so on .
PLEASE NOTE THAT IM UNABLE TO USE FORM METHOD AS MY LRAVEL UNABLE TO UPDATE DUDE TO SPECIFIC PURPOSES
try to add another <option> before foreach.
example codes:
<option value="null" selected>Please select one option</option>
#foreach($parents as $parent)
#if ($parent-> status != 'Freeze')
<option value="{{ $parent->id}}">{{$parent->description}} </option>
#endif
#endforeach
</select>
```

Laravel 5.4 passing form select option value to a Route::get

I am trying to do the following within my Laravel 5.4 project.
In a users.index blade page I am listing all users from a database in a table.
All the users belong to a district. Some districts have more users then the other.
At the top of this table view I created a form with a select field. The options hold the id's for the 10 districts:
<form class="form-horizontal" method="GET" action="/users/district">
<div class="form-group col-md-5">
<select name="district" class="form-control">
<option value="1">Amsterdam</option>
<option value="2">Arnhem</option>
<option value="3">Assen</option>
<option value="4">Groningen</option>
<option value="5">Leeuwarden</option>
<option value="6">Rotterdam</option>
<option value="7">Sittard</option>
<option value="8">Tilburg</option>
<option value="9">Utrecht</option>
<option value="10">Antillen</option>
</select>
</div>
<div class="form-group col-md-4 col-md-offset-1">
<button class="btn btn-md btn-primary">Haal gegevens op</button>
</div>
</form>
When I put the URL "http://localhost/users/district/5" in manually in the browser it shows me a table view with only users from the district with the ID of 5.
This is my UsersController:
public function perDistrict($district)
{
$users = User::where('district_id', $district)
->paginate(12);
$totalusers = User::count();
return view('users.index', compact('users', 'totalusers'));
}
I would like to use the form to get me the results but when I submit the form it show me this URL: "http://localhost/users/district?district=5" and it gives me no result of course.
How can I convert that to the URL "http://localhost/users/district/5" ?
This my route:
Route::get('users/district/{district}', 'UsersController#perDistrict');
Hope someone can help me.
https://www.codecourse.com/lessons/laravel-fundamentals/729 did the trick for me with some own customization.

Multiple selection of dropdown menu and direct to a link

I am looking for JavaScript or in jquery for my custom dropdown menu
<form name="menu">
<select ONCHANGE="location = this.options[this.selectedIndex].value;">
<option value="" selected="selected">Courses</option>
<option value="http://www.google.com">Course1</option>
<option value="http://www.youtube.com">Course2</option>
<option value="http://www.yahoo.com">Course3</option>
</select>
<select ONCHANGE="location = this.options[this.selectedIndex].value;">
<option value="" selected="selected">Location</option>
<option value="http://www.google.com">Location1</option>
<option value="http://www.youtube.com">Location2</option>
<option value="http://www.yahoo.com">Location3</option>
</select>
</form>
http://jsfiddle.net/kundansingh/d4FEV/2/
in this if i select any of the course and then the location it should redirect to a paticular url, so for each course, different locations will be there and url
Follow steps:
Just pass the value(url) to a javascript function as an argument.
Grab that value in that javascript function.
Redirect the url (might use window.location.assign(url) function)`

Resources