How to develop cascading dropdowns in spring 4 using thymeleaf - spring

i have a difficulty in developing cascading dropdowns in spring 4 with thymeleaf.
Here is my scenario:
i have 2 dropdowns like state and city. based on state selection, i need to populate city dropdown with corresponding cities for that state.
I am using Spring boot, spring 4 and thymeleaf template for view.
Thanks in advance.

Do you want to Dropdown / List selectors ?
Could I help you now. Please read this article.
Select fields have two parts: the <select> tag and its nested <option> tags. When creating this kind of field, only the <select> tag has to include a th:field attribute, but the th:value attributes in the nested <option> tags will be very important because they will provide the means of knowing which is the currently selected option (in a similar way to non-boolean checkboxes and radio buttons).
Let’s re-build the type field as a dropdown select:
<select th:field="*{type}">
<option th:each="type : ${allTypes}"
th:value="${type}"
th:text="#{${'seedstarter.type.' + type}}">Wireframe</option>
</select>
also you can check this Thymeleaf Website

You can use the appelsiini chained select to implement the cascading dropdown.
template.html
<select th:field="*{state}">
<option value="0">--</option>
<option th:each="state : ${states}" th:value="${state.stateId}" th:text="${state.name}">Florida</option>
</select>
<select th:field="*{city}">
<option value="0">--</option>
</select>
<script type="text/javascript">
$("#city").remoteChained({
parents: "#state",
url: /*[[#{/getStateCityValues}]]*/ ""
});
</script>
Controller.java
#PostMapping("/getStateCityValues")
public #ResponseBody
Map<String, String> getStateCityValues(#RequestParam("state") Integer state) {
Map<String, String> cityValues = new HashMap<>();
List<City> cities = cityService.getStateCities(state);
for(City city : cities){
cityValues.put(String.valueOf(city.getCityId()), city.getName());
}
return cityValues;
}

Related

Spring Boot Get Value of object from select using thymeleaf

So I have this project, and I want to return an object, from the previous choice of 2 select items. How can I do it? for example:
<select class="form-control" id="cityPicker1">
<option value="0">select option</option>
<option th:each="city: ${listCities}" th:value="${city.number}" th:text="${city.name}"></option>
</select>
<select class="form-control" id="cityPicker2">
<option value="0">select option</option>
<option th:each="city: ${listCities}" th:value="${city.number}" th:text="${city.name}"></option>
</select>
I want to display an item from another item list which has a number1 field and a number2 something like ticket.number1 and ticket.number2 but they have to match the values from the previous selects. I can't seem to find anything. Any ideas?
This is how I set it up in the controller:
#GetMapping("/tickets")
public String viewTicketsPage(Model model) {
List<City> listCities = cityRepo.findAll();
List<Ticket> listTickets = ticketRepo.findAll();
model.addAttribute("listCities", listCities);
model.addAttribute("listTickets", listTickets);
return "tickets";
}
I need to clarify a few things about your question.
1 - did you manage to get the checkboxes to work?
2 - can you send the selected data to the controller?
you need a controller to receive data from the page, send this data to the repository to fetch other data..
I believe you want to select a table, where the data matches the selected ones. .
take a look at JPQL, maybe this will help you:
https://www.baeldung.com/spring-data-jpa-query

Laravel Livewire Autofill Input Box Based On Drop Down Selection

I am asking for help. Is there any way I could fill an input box based on drop down selection? On my modal I have a dropdown option for subject description and I would like the subject number input field dynamically change its value. Any help would be much appreciated.
This is how I retrieved the data for my dropdown
subjects=DB::table('programs_subj')->select('corsdes', 'corsno')->get()
This is my dropdown code for the subject description which is working and the selected is saved but I could quite how to incorporate the subject number
<select name="corsdes" id="corsdes" wire:model="corsdes">
<option value="corsdes" wire:model="corsdes"></option>
#foreach($subjects as $sbj)
<option value="{{ $sbj->corsdes }}">{{ $sbj->corsdes}}</option>
#endforeach
</select>
<input name="corsno" id="corsno" wire:model="corsno"><input>
if you have the public properties $corsdes and $corsno then:
public function updatedCorsdes($value)
{
$this->corsno = $this->subjects->where('corsdes',$value)->first()->corsno;
}

Spring Thymeleaf th:selected on EnumList with multiple selection

I have this enum
enum Types{
A, B
}
I have a form class
public class MyForm {
private Types[] types;
//getter setters
}
here is my form with select
<form th:action="${#httpServletRequest.requestURI}" th:object="${myForm}" method="POST" id="form">
<select name="types" multiple="" id="testSelect"
th:each="type : ${T(com.test.Types).values()}"
th:value="${type}"
th:text="${type}"
th:selected="*{types != null AND #arrays.contains(types, type)}"
>
</select>
</form>
here is the error i am getting.
Property or field 'type' cannot be found on object of type 'com.test.MyForm' - maybe not public or not valid?
First, I believe you have a typo, it should be type != and not types !=. Also, you are using * in your selected, instead of $. Also, I believe you are using #list.contains() of Thymeleaf in a way that shouldn't work. You should use the whole function, just like this #list.contains(types, type). One last thing, the selected, value and text tags should should go in the option element, not the select. In the end your code should look like the following one.
<select name="types" multiple="" id="testSelect">
<option th:each="type : ${T(com.test.Types).values()}"
th:value="${type}" th:text="${type}"
th:selected="${types != null AND #arrays.contains(types, type)}">
</option>
</select>
One last thing, I am not sure where did the variable types came from, I am assuming you initialized it somewhere.
The best would be to change your form backing bean to have some collection of your enumerations, instead of array such as:
public class MyForm {
private List<Types> types = new ArrayList<Types>();
//getter setters
}
Then before you render the form, you can just fill this array with types, which you want to be preselected in the controller just by adding them to the list.
Then should be able to simply skip th:selected logic...
<select th:field="*{types}" multiple="multiple" id="testSelect">
<option th:each="type : ${T(com.test.Types).values()}"
th:value="${type}" th:text="${type}">
</option>
</select>
Thymeleaf will do the magic for you ;-)

DropDown list issue in knockout js asp.net mvc 3

I have the following problem. I'm developing web application on asp.net mvc and using KnockoutJS in one of views. I have the following viewmodel
public class ExampleViewModel
{
public IEnumerable<Element> ElementsList { get; set; }
}
class Element
{
public bool Required {get;set;}
}
option Required must be set with dropdown list. I have the following block code in view
<div data-bind="foreach: ElementsList">
<select data-bind="attr: { name: 'ElementsList[' + $index() + '].Required' }, value: Required">
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</div>
when I select Yes or No from drop down and submit form I have appropriate value saved in database, but when I open this view in browser after that all values in drop down list are 'Yes'. Despite the fact that when I open view and debug it I can see with Quick Watch, that each value from ElementsList has correct value of Required option ('Yes' or 'No'), all dropdown lists have a value 'Yes'.

asp.net helper for DropDownList won't render correctly

I'm attempting to get a dropdown list to select the correct value when the page loads.
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value"), new { #class = "selectbox", selected = Model.CounterpartyType })
However, when the page renders it always selects the first value in the dropdown list.
The html source for the page:
<select class="selectbox" id="CounterpartyTypeSelect" name="CounterpartyTypeSelect" selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">
<option value="5802239e-c601-4f1e-9067-26321213f6e6">Societa per Azioni (SpA)</option>
<option value="f8160341-4a69-436f-9882-4da31a78f1d5">Gesellschaft mit beshrankter Haftung (GmbH)</option>
<option value="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">Sociedad Anonima (SA)</option>
<option value="cdbeb1d3-301b-4884-b65a-612ddd8306f3">Private Limited Company (Ltd)</option>
<option value="1fe68d96-f31b-4859-9869-8c76a5eb1508">Corporation (Inc)</option>
<option value="9c9e5722-ab59-4d1c-a0a3-91b42a3ee721">Limitada (LTDA)</option>
<option value="0cb57339-8705-4e3a-8f6a-95e9664962b7">Public Limited Company (Plc)</option>
<option value="0924d6f1-06a9-49a3-ac05-b3e2686a0e92">Partnership</option>
<option value="c8fbe021-a8f7-4e9d-ab38-dbeb5af5a631">Limited Liability Company (LLC)</option>
<option value="30d9e22b-34f5-43c5-8471-e614dbedb6a6">Aktiengesellschaft(AG)</option>
</select>
As you can see it is putting the "selected" attribute into the outer select tag instead of on the option that matches the Id. I have another select with identical parameters (except variable names of course) and it renders correctly this way. I do not want to use DropDownListFor<T> because I have a HiddenFor field that actually submits this value in the form and javascript that sets the value to match the Select choice. I've confirmed my database is storing the values that I set correctly. What is going on?
SelectList() has an overload for you to choose the selected item. You are adding it as an HTML attribute in the helper and those get rendered to the parent select tag.
Do this:
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value", Model.CounterpartyType), new { #class = "selectbox" })
Use the overload for SelectList that takes four arguments:
new SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);
What's happening in the first line of your code new { #class = "selectbox", selected = Model.CounterpartyType } is you're providing the selected attribute as an HTML attribute of the parent select element.
So you see selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d" appearing in your first line of output, which btw doesn't do anything.
Also you're providing the value to search for in the Helper as a hardcoded string "value" instead of the actual value you need from the model. The browser will default to the first option since it can't find any value matching 'value'.
To fix this, provide Model.CounterpartyType as the third parameter to your SelectList parameter instead of 'value'.

Resources