How to set event for submit button in wicket and catch it in home page - events

My problem is when I want to click on the submit button, the data will display in home page.
You will say that I should use a form for this, but I'm working only with panel and I can't add form inside of it.
So I want to create an event in this button and catch it in the home page.
This is my HTML code :
<wicket:panel>
<div class="input-group mb-3">
<div class="input-form">
<div class="form-select-sm">
<select wicket:id="option" class="form-select form-select-sm" aria-label=".form-select-sm example">
<option selected>Select your coffee</option>
<option>coffeeName</option>
</select>
</div>
<br>
<div class="input-group mb-3">
<input type="number" class="form-control" wicket:id="quantity-of-coffee" placeholder="Quantity" aria-label="Username" aria-describedby="basic-addon1" min="1" max="50">
</div>
<div class="submit-button">
<button wicket:id="submit" type="submit" class="btn btn-success">Add</button>
</div>
<br>
<div>
<wicket:enclosure>
<div class="alert alert-success" wicket:id="fb" role="alert">
</div>
</wicket:enclosure>
</div>
</div>
</div>
</wicket:panel>
and this is my customPanel class :
public class CustomPanel extends Panel{
public static final String DDC_MARKUP_ID="option";
public static final String QUANTITY_MARKUP_ID="quantity-of-coffee";
public static final String SUBMIT_BUTTON_MARKUP_ID="submit";
public static final String FEEDBACKPANEL_MARKUP_ID="fb";
public static final String ORDER_VIEW_MARKUP_ID="order-content";
public static final String COFFEE_NAME_MARKUP_ID="coffee-name";
public static final String COFFEE_QUANTITY_MARKUP_ID="quantity";
public static final String COFFEE_PRICE_MARKUP_ID="coffee-price";
public static final String ORDER_PRICES_VIEW_MARKUP_ID="order-total";
public static final String TOTAL_DISCOUNT_MARKUP_ID="discount";
public static final String ORDER_TOTAL_MARKUP_ID="total";
private IModel<List<CoffeQuantityAssociation>> listOfCoffees ;
private IModel<Order> order ;
private String choice="";
public CustomPanel(String id,IModel<Order> order,IModel<List<CoffeQuantityAssociation>> listOfCoffes) {
super(id);
this.order = order;
this.listOfCoffees=listOfCoffes;
}
#Override
protected void onInitialize() {
super.onInitialize();
FeedbackPanel feedbackPanel=new FeedbackPanel(FEEDBACKPANEL_MARKUP_ID);
Model<Integer> quantityModel=Model.of(0);
List<Coffe> coffeeListMockData=MockData.getListOfCoffes();
IModel<List<String>> coffeNamesListMockData=Model.ofList(MockData.getCoffeNames(coffeeListMockData));
DropDownChoice<String> ddc=new DropDownChoice<String>(DDC_MARKUP_ID,coffeNamesListMockData.getObject());
ddc.setDefaultModel(coffeNamesListMockData);
add(ddc);
add(new NumberTextField<Integer>(QUANTITY_MARKUP_ID,quantityModel)
.setLabel(new Model<>(QUANTITY_MARKUP_ID))
.setRequired(true))
.setDefaultModel(Model.of(QUANTITY_MARKUP_ID))
.add(RangeValidator.range(0, 50));
add(feedbackPanel);
get(FEEDBACKPANEL_MARKUP_ID).setVisible(false);
//choice=ddc.getModelObject();
Button submit= new Button(SUBMIT_BUTTON_MARKUP_ID);
// here i want to create the event
}

From the question's comments:
#martin-g I want to display data in home page by clicking on
the submit button of the panel. How can I do this with creating
an event in panel class and catch it in home page ?
It depends how you navigate from the current page (the one with the panel) to the home page.
You could use any of the following:
1) setResponsePage(new HomePage(myEvent));
2) setResponsePage(HomePage.class, new PageParameters().add("myParamKey", "someValue"));
3) in the button#onSubmit(): MySession.get().setAttribute("key", "value")
in the HomePage: String value = MySession.get().getAttribute("key")

Related

Show Springboot validation results in Thymeleaf template

I am getting started with Springboot and am unable to propagate validation results (errors) back to the thyme template. I have a typical setup: #Entity object, #Service, and #Repository. Here are the sections of my Controller and index template (and its form). UserVital, UserBlood, etc. are the data objects mapped to the DB tables using hibernate. Hope this information is enough for the members to point me in the right direction.
Data Object
#Entity
#Table(name = ".....")
public class UserVital {
#NotNull(message = "Height (Feet) cannot be null")
#Range(min = 0, max = 15, message = "Height (Feet) must be greater than 0")
#Column(name = "feet", nullable = false)
private int heightInFeet;
.............
}
Controller
#GetMapping("/")
public String getUsers(Model model) {
UserVital vital = new UserVital();
UserGrithMeasurements grith = new UserGrithMeasurements();
UserBloodChemistry blood = new UserBloodChemistry();
List<Category> categories = categoryService.getAllCategories();
model.addAttribute("categories", categories.get(0));
model.addAttribute("vital", vital);
model.addAttribute("grith", grith);
model.addAttribute("blood", blood);
return "index";
}
#PostMapping("/add")
public String addData(#Valid UserVital vital, BindingResult vitalValidationResult,
#Valid UserGrithMeasurements grith, BindingResult grithValidationResult, #Valid UserBloodChemistry blood,
BindingResult bloodValidationResult, Model model) {
if (vitalValidationResult.hasErrors() || grithValidationResult.hasErrors()
|| bloodValidationResult.hasErrors()) {
return "index";
} else {
model.addAttribute("successMsg", "Details saved successfully!!");
return "index";
}
}
Thyme Form
<form class="tab-content" method="POST" th:action="#{/add}">
<div class="form-group row">
<label for="height" class="col-sm-2 control-label" th:text="#{height}"></label>
<div class="col-sm-2">
<input type="number" class="form-control" id="feet" th:attr="placeholder=#{feet}"
th:field="${vital.heightInFeet}">
</div>
<div class="form-group col-sm-12">
<label for="neck" class="col-sm-2 control-label" th:text="#{neck}"></label>
<div class="col-sm-2">
<input type="number" class="form-control" id="systolic" th:attr="placeholder=#{inches}"
th:field="${grith.neck}">
<div class="col-sm-2">
<input type="number" class="form-control" id="ldl" th:field="${blood.ldl}">
.....
</form>
Question: As you can see I have multiple BindingResult objects. Each BindingResult object holding the validation results of the respective data object (vitalValidationResult holds validation result of UserVital object vital, etc.). Now, how do I write "th:if" statements in the template that will allow me to check if there are any errors in the fields.
Thanks.
I have solved the problem by encapsulating the required form fields in a div and then placing "th:object=${objectName}" in the div.
<form >
<div class="tab-pane active text-center" id="tab_1_1" th:object=${vital}>
<div class="tab-pane active text-center" id="tab_1_2" th:object=${grith}>
</form>

Spring Web application tymeleaf : POST request directed to wrong address

I have post mapping for URL: "/bank/addnew" My controller looks like:
Upon submission the form is submitted to "http://127.0.0.1:8082/banks/%20/banks" However, I need it to go to "http://127.0.0.1:8082/banks/addnew". Thanks for the Help!
#Controller
public class BankController {
#Autowired private BankService bankService;
#GetMapping("/banks")
public String bankList() {
return "bank/bank_list";
}
#PostMapping(value="/banks/addnew")
public String addNew(Bank bank) {
bankService.save(bank);
return "redirect: /banks";
}
}
And my template:
<form method="POST" action="#" th:action="#{/banks/addnew}" >
<div class="form-group">
<label for="recipient-name" class="col-form-label">Bank Name:</label>
<input type="text" class="form-control" id="recipient-name" name="name">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
The Post Method was actually working okay. I checked it by printing the Model object inside the target controller. However, it was being submitted to the database a NULL value because I didn't initialize getters and setters for my Model. Finally, there was a space in the return string, thus I removed it.
The controller Should have a return statement with no space.
return "redirect:/banks";

How to send list of items from JSP back to Controller in Spring boot?

I'm trying to display list of questions on JSP page and using the check-box to select and submit them back to controller.
I can display them without any problem but when they're Posted back 'QuestionsListWrapper' is Null. Can someone point to me where I'm going wrong.
Entity Question
public class Questions implements Serializable {
#Id
#GeneratedValue
private Integer quesId;
#Transient
private boolean isSelected;
Wrapper class
public class QuestionsListWrapper {
private List<Questions> quesWrapperList;
public List<Questions> getQuesWrapperList() {
return quesWrapperList;
}
public void setQuesWrapperList(List<Questions> quesWrapperList) {
this.quesWrapperList = quesWrapperList;
}
Controller Get
#GetMapping("/group/{id}")
public String showForm(#PathVariable("id") Integer id, Model model) {
Assessments ass = as.getAssById(id);
List<Questions> qlist = qs.getQuesByAssessment(ass);
QuestionsListWrapper qlw = new QuestionsListWrapper();
qlw.setQuesWrapperList(qlist);
model.addAttribute("questions", qlw.getQuesWrapperList());
return "stuEssay";
Controller Post
#PostMapping("/saveSelectedQuestions")
//Here questions is null
public String saveSelectedQuestions(#ModelAttribute("questions") QuestionsListWrapper questions, Model model) {
List<Questions> selected = questions.getQuesWrapperList();
System.out.println(questions.toString());
System.out.println(questions.getQuesWrapperList());
return "redirect:/studentHome";
JSP
<form:form action="/saveSelectedQuestions" method="post" modelAttribute="questions">
<c:forEach items="${questions}" var="question" varStatus="count">
<input type="hidden" name="quesId" value="${question.quesId}">
<div class="form-group">
<textarea rows="3" >${question.quesText}</textarea>
<input type="checkbox" name="isSelected[${count.count}]"/>
</div>
</c:forEach><!-- End of question list -->
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form:form>

Pass a object from Select in Thyemleaf

I have the following class:
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "person_id")
private int personId;
#Column(name = "person_name", unique = true)
private String personName;
#Column(name = "gender")
private Gender personGender;
}
Here is Gender as well:
public class Gender{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "gender_id")
private int genderId;
#Column(name = "gender_name", unique = true)
private String genderName;
}
I've assembled a Thymelef dropdown menu when creating a new Person that looks like this:
#RequestMapping(value = ("/newPerson"), method = RequestMethod.GET)
public ModelAndView createPerson() {
ModelAndView model = new ModelAndView();
Person person= new Person ();
model.addObject("person", person);
List<Gender> genders= genderService.getAll();
model.addObject("genders", genders);
model.setViewName("user/newPerson");
return model;
}
(I realize it looks kinda dumb, but it is a simplified version of my code.)
And here is the HTML:
<form class="form-createNew" role="form" method="POST"
th:action="#{/newPerson}" th:object="${person}">
<div class="form-row">
<div class="col">
<div class="form-label-group">
<input type="text" th:field="*{personName}" id="personName" class="form-control" placeholder="Person name">
</div>
</div>
</div>
<div class="form-row">
<div class="col">
<div class="form-label-group">
<select th:field="*{personGender}" class="form-control"
id="personGender" name="personGender">
<option value="" selected disabled hidden>Select gender</option>
<option th:each="gender: ${genders}"
th:value="${gender.genderId}"
th:text="${gender.genderName}"></option>
</select>
</div>
</div>
</div>
<button id="registerBtn" class="btn btn-lg btn-primary btn-block shadow-none text-uppercase" type="submit"> Create </button>
</form>
And finally my question:
What I am receiving at the POST method in the controller for /newPerson is a Person object with the value from the input field, but NULL for the Gender. What is causing that and where am I wrong here? I went through similar questions on SO regarding that issue and also the Thymeleaf Docs/Baeldung and everything looks okay to me.
Any help is appreciated! :)
You are sending for your post controller something like this:
personGender: gernderId
You must do:
personGender.genderId : genderId
For that use in your html:
th:field="*{personGender.genderId}"
instead of
th:field="*{personGender}"
I think it will help you!

Spring Boot ModelAndView - cannot update value to Model

I am trying to create a form with 3 fields within the class LoginForm: usuario, senha, msgLogin.
I receive the fields usuário and senha from the input boxes and then I try to redirect to the same page with the same fields plus the field MsgLogin. But I've not been able to update the msgLogin field and I don't understand why.
These are the code:
HTML:
<form id="frmLogin" class="form col-md-12" action="#" th:action="#{/login}" th:object="${loginForm}" method="post">
<div class="form-group">
<label for="usuario" class="col-md-1">Usuário: </label>
<input type="text" id="usuario" placeholder="Email" th:field="*{usuario}"/>
</div>
<div class="form-group">
<label for="senha" class="col-md-1">Senha: </label>
<input type="password" id="senha" placeholder="senha" th:field="*{senha}"/>
</div>
<div class="row">
<button id="entrar">Entrar</button>
</div>
<div class="row">
<div id="msgLogin"></div>
<p th:text="${loginForm.msgLogin}" />
</div>
</form>
The Controller:
#RequestMapping("/")
public String init(#ModelAttribute LoginForm loginForm) {
Logger.getAnonymousLogger().info("Tela Inicial.");
return "home";
}
#PostMapping("/login")
public ModelAndView entrar(LoginForm loginForm) throws IOException {
Logger.getAnonymousLogger().info("Entrando no Internet Banking.");
service.login(usuario, senha);
ModelMap model = new ModelMap();
loginForm.setMsgLogin("I want to update that value!");
model.addAttribute("loginForm", loginForm);
return new ModelAndView("redirect:/", model);
}
Class using Lombok:
#Getter
#Setter
public class LoginForm {
private String usuario;
private String senha;
private String msgLogin;
}
A redirect send a 302 HTTP status back to the browser to resubmit using a new url, so it resubmits the same two fields to the new url. There's no expectation of payload data in the 302 response.
In your Controller, change the last line in your entrar method to: return new ModelAndView("/login", model);

Resources