Thymeleaf = how to th:each adding value in tag input - spring-boot

so I want to make input income/outcome increase according to the income/outcome data that has been obtained from the controller
I have tried using th:each as follows to add income/outcome from each transaction
this is my form
<form class="form-horizontal" th:action="#{/report/create}" method="post">
<div th:each="transactions : ${transaction}">
<input type="hidden" name="income" th:value="${report.income + transactions.income}">
<input type="hidden" name="outcome" th:value="${report.outcome + transaction.outcome}">
</div>
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
with that I only got the first income/outcome from the loop

Not sure how you implemented the backend, but your spelling for transactions isn't correct. Other than that, it should work as I've done something similar myself in the past. Typically you would have
#GetMapping("/my-page")
public String showAll(Model model) {
//....
model.addAttribute("report", report);
// however you define (a list) of transactions
model.addAttribute("transactions", transactions);
return "my-page";
}
then in your html
<div th:each="transaction : ${transactions}">
<input type="hidden" name="income" th:value="${report.income + transaction.income}">
<input type="hidden" name="outcome" th:value="${report.outcome + transaction.outcome}">

Related

Error in passing the foreign key in the form for editing

I have two tables, one named Client and the other named Projects linked together via a foreign key (this is client_id, which is present in Projects).
Each project has an edit button; when I click to edit a project I have a form with all fields secured to it.
To edit a project I have to pass the client id (client_id) associated with that project.
To do this, I did the following:
ROUTE
Route::get('/project/edit/{project}', [ProjectController::class, 'edit'])->name('project.edit');
CONTROLLER
public function edit(Project $project)
{
$client_id = Project::select('client_id')->where('id',$project->id)->get();
//dd($client_id);
return view('project.edit', compact('project','client_id'));
}
VIEW
<div class="row mt-3">
<div class="col-12 col-md-6 namelabel">
<form action="{{route('project.store')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="mb-3">
<input type="hidden" class="form-control" name="client_id" value="{{$client_id}}" >
</div>
<div class="mb-3">
<label for="name" class="form-label">Project name</label>
<input type="text" class="form-control" name="name" value="{{$project->name}}">
</div>
<div class="mb-3">
<div class="mb-3">
<label for="logo" class="form-label">Insert image</label>
<input type="file" name="logo">
</div>
<div class="mb-3">
<label for="project_start_date" class="form-label">Data init</label>
<input type="date" class="form-control" name="project_start_date" value="{{$project->project_start_date}}">
</div>
<label for="description" class="form-label">Description</label>
<textarea name="description" cols="30" rows="10" class="form-control">{{$project->description}}</textarea>
</div>
<button type="submit" class="btn btn-primary mb-5">Modifica progetto</button>
</form>
</div>
</div>
I get the following error:
Incorrect integer value: '[{"client_id":14}]' for column 'client_id' at row 1
How can I solve this problem?
Thanks to those who will help me
This statement
Project::select('client_id')->where('id',$project->id)->get()
does not return the client_id. It returns an Eloquent Collection of Projects with only the client_id Attribute.
You can chain the pluck function to extract only value and then you can call first to get the value from the collection.
Project::select('client_id')
->where('id',$project->id)
->get()
->pluck('client_id')
->first()
After checking your code in the full detail you don't need to do the select part at all.
You have already the Project Model so you can access all of it's fields directly.
$project->client_id
In your view you are doing this already with the name of the project:
{{$project->name}}
You can do the same with the client_id as well:
{{$project->client_id}}

.netcore client-side validation for different onPost handlers (multiple events)

In my .nercore razor page project I have a number of forms with multiple onPost handlers - different buttons for different events (eg. add / copy / edit / delete)
My problem is - I do not understand how I can differentiate client-side validation depending on the button pressed.
EDIT
Let's assume, I have the following .cshtml which defines two input data fields and two buttons. By pressing one button (Add) the first Field A should be validated, by pressing the second (copy) - another one (Field B):
#page "{id:int}/{modeR:int}"
#model MyProject.Pages.MyProjectDB.AddRecordModel
#{
ViewData["Title"] = "Add Record";
}
<div class="row">
<div class="col-md-7">
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="myClass.FieldA" class="control-label"></label>
<input asp-for="myClass.FieldA" class="form-control" />
<span asp-validation-for="myClass.FieldA" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="myClass.FieldB" class="control-label"></label>
<input asp-for="myClass.FieldB" class="form-control" />
<span asp-validation-for="myClass.FieldB" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" value="Add" class="btn btn-success">Add Record)</button>
<button type="submit" value="Copy" class="btn btn-warning">Edit Record</button>
</div>
</form>
</div>
</div>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
at the end of my .cshtml page, but it runs always when onPost is called.
I need to run validation "in groups": for one button set of one fields and ignore others, for another - another set and so on like written above
Is there any way to achieve it without writing custom javascript or do it on server side?..
ANOTHER EDIT
The answer was provided for the case where we have clear separation of input fields / buttons. But how can we handle this if we have two input fields and one button. Validation should NOT be fire if either of them is filled in and should fire if both are null. I understand, this sounds a bit strange, but in my example I have one input field and one dropdown-list. So, either a field should be filled-in or an item should be selected from the list, but for code simplicity let's stay with two input fields (Filed A and Field B, one of them should be filled) and one button:
#page "{id:int}/{modeR:int}"
#model MyProject.Pages.MyProjectDB.AddRecordModel
#{
ViewData["Title"] = "Add Record";
}
<div class="row">
<div class="col-md-7">
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="myClass.FieldA" class="control-label"></label>
<input asp-for="myClass.FieldA" class="form-control" />
<span asp-validation-for="myClass.FieldA" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="myClass.FieldB" class="control-label"></label>
<input asp-for="myClass.FieldB" class="form-control" />
<span asp-validation-for="myClass.FieldB" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" value="Add" class="btn btn-success">Add Record)</button>
</div>
</form>
</div>
</div>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Thanks in advance!
By pressing one button (Add) the first Field A should be validated, by pressing the second (copy) - another one (Field B) should be validated
You can try to put them in separate <form> and specify handler method via the asp-page-handler attribute, like below.
<h1>Go Add Handler</h1>
<form method="post">
<div class="form-group">
<label asp-for="myClass.FieldA" class="control-label"></label>
<input asp-for="myClass.FieldA" class="form-control" />
<span asp-validation-for="myClass.FieldA" class="text-danger"></span>
</div>
<div>
<button type="submit" value="Add" class="btn btn-success" asp-page-handler="Add">Add Record</button>
</div>
</form>
<hr />
<h1>Go Copy Handler</h1>
<form id="myform" method="post">
<div class="form-group">
<label asp-for="myClass.FieldB" class="control-label"></label>
<input asp-for="myClass.FieldB" class="form-control" />
<span asp-validation-for="myClass.FieldB" class="text-danger"></span>
</div>
<div>
<button type="submit" value="Copy" class="btn btn-warning" asp-page-handler="Copy">Edit Record</button>
</div>
</form>
#section scripts{
#await Html.PartialAsync("_ValidationScriptsPartial")
}
Test Result

Edit db record with modal window

I'm trying to edit some database record based on an ID that I'm saving into a button value.
#foreach ($employment as $empl)
<button data-toggle="modal" data-target="#edit-empl" href="#edit-empl" class="btn btn-default editbtn-modal" value="{{ $empl->id }}" type="button" name="editbtn">Edit</button>
<h3 class="profile-subtitle">{{ $empl->company }}</h3>
<p class="profile-text subtitle-desc">{{ $empl->parseDate($empl->from) }} - {{ $empl->parseDate($empl->to) }}</p>
#endforeach
As you can see here, I have an edit button with an id attached.
When I click edit I open a modal window to edit the fields and later on submit the form.
The thing is, I'm not sure how to get that id from the button into the modal window so I can compare the values and display the correct fields..
<form class="app-form" action="/profile/employment/edit/{id}" method="POST">
{{ csrf_field() }}
<input class="editID" type="hidden" name="editID" value="">
#foreach ($employment as $empl)
#if ($empl->id == buttonidhere)
<div class="form-group">
<label for="company">Company:</label>
<input type="text" name="company" value="{{ $empl->company }}">
</div>
<div class="form-group">
<label for="month">From:</label>
<input type="date" name="from" value="{{ $empl->from }}">
</div>
<div class="form-group">
<label for="to">To:</label>
<input type="date" name="to" value="{{ $empl->to }}">
</div>
#endif
#endforeach
<div class="row">
<div class="col-sm-6">
<input type="submit" class="btn btn-primary profile-form-btn" value="Save Changes">
</div>
</div>
</form>
I was able to pass the button value into the modal using javascript.. I put it into a hidden input but that doesn't help me at all because I can't get the input value in order to compare the values..
Solution 1: Using ajax
Step 1: Create a route in laravel which will return a JSON object containing employing data of requested employee.
For e.g,
/profile/employment/data/{empl_id}
Will get you employement data of id empl_id.
Step 2: Change your form as below
<form class="app-form" action="/profile/employment/edit/{id}" method="POST">
<input class="editID" type="hidden" name="editID" value="">
<div class="form-group">
<label for="company">Company:</label>
<input type="text" name="company" value="">
</div>
<div class="form-group">
<label for="month">From:</label>
<input type="date" name="from" value="">
</div>
<div class="form-group">
<label for="to">To:</label>
<input type="date" name="to" value="">
</div>
<div class="row">
<div class="col-sm-6">
<input type="submit" class="btn btn-primary profile-form-btn" value="Save Changes">
</div>
</div>
</form>
Step 3: Use javascript(jQuery) to get the data using ajax and load it into the form in modal.
jQuery code:
$(document).on("click", ".editbtn-modal", function() {
var id = $(this).val();
url = "/profile/employment/data/"+id;
$.ajax({
url: url,
method: "get"
}).done(function(response) {
//Setting input values
$("input[name='editID']").val(id);
$("input[name='company']").val(response.company);
$("input[name='to']").val(response.to);
$("input[name='from']").val(response.from);
//Setting submit url
$("modal-form").attr("action","/profile/employment/edit/"+id)
});
});
Solution 2: Using remote modal
Step 1:
Create another blade file for eg. editEmployee.blade.php and add the above form in it.
<form class="app-form" id="modal-form" action="/profile/employment/edit/{{ $empl->id }}" method="POST">
{{ csrf_field() }}
<input class="editID" type="hidden" name="editID" value="{{ $empl->id }}">
<div class="form-group">
<label for="company">Company:</label>
<input type="text" name="company" value="{{ $empl->company }}">
</div>
<div class="form-group">
<label for="month">From:</label>
<input type="date" name="from" value="{{ $empl->from }}">
</div>
<div class="form-group">
<label for="to">To:</label>
<input type="date" name="to" value="{{ $empl->to }}">
</div>
<div class="row">
<div class="col-sm-6">
<input type="submit" class="btn btn-primary profile-form-btn" value="Save Changes">
</div>
</div>
</form>
Step 2: Create a controller which would return the above form as HTML.
Tip: use render() function. example
Step 3: load the form into modal window before showing using javascript(jQuery)
considering your modal id is "emp-modal"
$(document).on("click", ".editbtn-modal", function() {
var id = $(this).val();
url = "/profile/employment/data/"+id;
$('#emp-modal').modal('show').find('.modal-body').load(url);
});
One solution would be to send the details you want the same way you send the id to the modal.
and the proper way to send variables to modal is to include this in the button that opens modal:
data-variablename="{{$your-variable}}"
use this jQuery to get the values of your variables to modal. where edit-empl is the id of your modal and data-target of your button
$('#edit-empl').on('show.bs.modal',function (e) {
var variablename= $(e.relatedTarget).data('variablename');
$(e.currentTarget).find('input[id="yourinputID"]').val(variablename);

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

How to collect form data and convert them json format and send back to server in spring mvc

I have form and I want to grab the data inserted by users and then convert them json format.
So first here is my form—
<form id="patient_form" action="#" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="firstName"> First Name<em>*</em></label>
<div class="controls">
<input type="text" id="firstName" class="required" maxlength="100"
placeholder="First Name" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="middleNameInitial">
Middle Name Initial</label>
<div class="controls">
<input type="text" id="middleNameInitial"
placeholder="Middle Name Initial" class="input-small"
maxlength="1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastName"> Last Name <em>*</em></label>
<div class="controls">
<input type="text" id="lastName" placeholder="Last Name"
class="required" maxlength="100" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="dateOfBirth"> Date Of
Birth</label>
<div class="controls">
<input type="text" id="dateOfBirth" class="required" />
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="button" class="btn btn-primary"
onclick="savePatientInfo()">Save Changes</button>
<button type="button" class="btn"
onclick="cancelPatientInfoForm()">Cancel</button>
</div>
</div>
</form>
And then I want to send back them to server. And for server side code, I’m using spring mvc and client side I’m using JQuery.
Now how can I do it? I need two things basically,
Ajax call (JavaScript function to which will basically do 3 things, one- grab the form data and convert them into json and then ajax call)
Sever side method to consume ajax call (Controller method as I’m
suing spring mvc.)
Any help is much appreciated.
First of all you need to perform ajax call from the JSP as below:
$.post("${pageContext.servletContext.contextPath}/ajaxTestData",
{
firstName:$("#firstName").val(),
middleNameInitial:$("#middleNameInitial").val(),
<other form data>
},
function(j)
{
<j is the string you will return from the controller function.>
});
Now in the controller you need to map the ajax request as below:
#RequestMapping(value="/ajaxTestData", method=RequestMethod.POST)
#ResponseBody
public String calculateTestData(#RequestParam("firstName") String firstName, #RequestParam("middleNameInitial") String middleNameInitial, HttpServletRequest request, HttpServletResponse response){
<perform the task here and return the String result.>
return "xyz";
}
I have not used the JSON input and result in this way but I think if you return the Pojo then it might converts the same in the json format automatically. Just check that.
Hope this helps you. Cheers.

Resources