So i have created div with static data from controller and model.Now when i click on ADD button a new item should be added to list and div should automatically be dispalyed to page. Hope i am clear :)
Please guide me how do i achieve it?? Thanks
It should work before but I guess you changed the html , Okay Try This one
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var i=y=0;
var newarr = new Array();
var divContent = '';
#foreach (var job in Model)
{
divContent = '<div class="panel panel-default" id="panel2"><div class="panel-heading-new"><h4 class="panel-title" id="newpanel1"><a data-toggle="collapse" data-target="#collapseTwo" href="#collapseTwo">';
divContent += '#Html.DisplayFor(modelItem => job.Header, new { job.Id })';
divContent += '</a></h4></div><div id="collapseTwo" class="panel-collapse collapse in"><div class="panel-body"><p class="lead justified">';
divContent += 'Qualifications and Skills:';
divContent += '</p><ul class="fa-ul">';
divContent += '<li><i class="fa-li fa fa-hand-o-right pad-icon"></i><span class="lead justified">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>';
divContent += '</ul><br /></div></div></div>';
newarr[i] = $(divContent);
i = i +1;
}
$(document).ready(function(){
$("a#add").click(function(){
if (y<i) {
var content = newarr[y];
$('#maincontainer').append(content);
y++;
} else {
alert('No other Job!');
}
return false;
});
});
</script>
ADD
<div class="container">
<div class="col-lg-12" id="maincontainer">
</div>
</div>
<script>
</script>
#model IEnumerable<Nexcentus.UI.Models.JobOpening>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var i=0;
var y=0;
var newarr = new Array();
</script>
<script>
#foreach (var job in Model)
{
newarr[i] = $( "<li><i class=\"fa-li fa fa-hand-o-right pad-icon\"></i><span class=\"lead justified\">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>");
i = i +1;
}
</script>
<div class="container">
ADD
<div class="col-lg-12">
#foreach (var job in Model)
{
<div class="panel panel-default" id="panel2">
<div class="panel-heading-new">
<h4 class="panel-title-new" id="newpanel1">
<a data-toggle="collapse" data-target="#collapseTwo" href="#collapseTwo">
#Html.DisplayFor(modelItem => job.Header, new { job.Id })
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse in">
<div class="panel-body">
<p class="lead justified">
Qualifications and Skills:
</p>
<ul class="fa-ul">
<li><i class="fa-li fa fa-hand-o-right pad-icon"></i><span class="lead justified">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>
</ul>
<br />
</div>
</div>
</div>
<script>
$("a#add").click(function(){
if (y<i) {
var content = newarr[y];
$('ul.fa-ul').append(content);
y = y+1;
}
return false;
});
</script>
Try this one
Related
I want to receive the date through the date picker and put it in an object that stores reservation information(RentalPlacesVo).
I received the date from the reservation form and also confirmed that the controller fits the vo object well (even the datatype in rental_date was java.sql.Date)
After making the payment, I sent it to Ajax to include it with other information, and in the process of processing Ajax, I confirmed that 2022-07-23 was changed to 1992. It seems that the date has not been properly stored in the date type column of the db since the date has been changed to 1992.
I need to store data of DATE type on vo object, how can I get it?
Details of the error are as follows.
WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.sql.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#org.springframework.web.bind.annotation.RequestParam java.sql.Date] for value '1992'; nested exception is java.lang.IllegalArgumentException
RentalPlacesVo
package com.joinus.domain;
import java.sql.Date;
import lombok.Data;
#Data
public class RentalPlacesVo {
private int rental_places_no;
private String reservation_no;
private int club_no;
private int member_no;
private int partner_place_no;
private int payment_no;
private Date rental_date;
private int rental_time_no;
private int rental_status;
}
reservationForm.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# include file="../include/header.jsp"%>
<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey="appkey"&libraries=services"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.6.0/dist/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
// Calendar
var config = {
dateFormat : 'yy-mm-dd',
showOn : "button",
buttonText : "선택",
prevText : '이전 달',
nextText : '다음 달',
monthNames : ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
monthNamesShort : ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
dayNames : ['일','월','화','수','목','금','토'],
dayNamesShort : ['일','월','화','수','목','금','토'],
dayNamesMin : ['일','월','화','수','목','금','토'],
yearSuffix : '년',
minDate : 1
}
$(function(){
$("input[name='rental_date']").datepicker(config);
});
$(document).ready(function(){
$(':button').attr('class','btn btn-primary');
$('#subBtn').click(function(){
// var date = $('#rental_date').val(); // 2022-07-23
if($('#rental_date').val() == ''){
$('#rental_date').focus();
return false;
}
if($('#rental_time_no').val() == ''){
$('#rental_time_no').focus();
return false;
}
if($('#memberCnt').val() == ''){
$('#memberCnt').focus();
return false;
}
if($('#memberCnt').val() > 20){
alert('Max MemberCnt : 20');
$('#memberCnt').focus();
return false;
}
});
});
</script>
<div class="container-xxl py-5">
<div class="container" style="color: black;">
<div class="row g-5">
<h1 id="partnerPlaceName">${partnerPlace.partner_place_name }</h1>
<div style="width: 70%;">
<img style="width: 95%; max-height: 550px;" src="${PageContext.request.contextPath }/resources/upload/partner_place/${partnerPlace.partner_place_image}">
<div style="margin-top: 3em;">
<pre class="boardContent">${partnerPlace.partner_place_content }</pre>
</div>
<div style="margin-bottom: 16px;">
<i class="fa fa-phone-alt me-3" aria-hidden="true"></i>${partnerPlace.partner_place_tel }
</div>
<div id="partnerPlaceAddr" style="margin-bottom: 16px;">
${partnerPlace.partner_place_address }
</div>
</div>
<div style="width: 30%; border: 1px solid #32C36C; padding-top: 1em; height: 70%;">
<form name="fr" action="" method="post">
<input type="hidden" name="partner_place_no" value="${partner_place_no }">
<input type="hidden" name="partner_place_name" value="${partnerPlace.partner_place_name }">
<input type="hidden" name="partner_place_price" value="${partnerPlace.partner_place_price }">
<div>
<div style="font-size: x-large; float: left;">
${partnerPlace.partner_place_name }
</div>
<div style="color: #32C36C; text-align: right; margin-bottom: 2em;">
<span style="font-size: x-large;">
<fmt:setLocale value="ko_KR"/><fmt:formatNumber type="currency" value="${partnerPlace.partner_place_price }" />
<br>
</span>
<span style="color: #9B9B9B;"> /hour</span>
</div>
</div>
<div>
MemberCnt <input type="number" class="form-control" id="memberCnt" name="memberCnt" max="20" required>
</div>
<script type="text/javascript">
var memberCnt = 0;
var totalPrice = 0;
$('#memberCnt').blur(function(){
memberCnt = $('#memberCnt').val();
totalPrice = memberCnt * ${partnerPlace.partner_place_price} * 2
document.getElementById("seePrice").innerHTML = totalPrice.toLocaleString();
$('#payment_price').val(totalPrice);
});
</script>
<!-- Date -->
<div style="margin-bottom: 2em;">
Select Date (Click button)
<input class="form-control" id="rental_date" name="rental_date" autocomplete="off" readonly style="background-color: white;">
</div>
<!-- Time -->
<div style="margin-bottom: 2em;">
Time
<select class="form-select" id="rental_time_no" name="rental_time_no">
<option value="">Select Time</option>
<option value="1">10:00~12:00</option>
<option value="2">12:00~14:00</option>
<option value="3">14:00~16:00</option>
<option value="4">16:00~18:00</option>
<option value="5">18:00~20:00</option>
<option value="6">20:00~22:00</option>
</select>
</div>
<!-- TotalPrice -->
<div>
TotalPrice<br>
<span id="seePrice"></span>
<input type="hidden" id="payment_price" name="payment_price">
</div>
<div class="payBtn">
<input type="submit" class="btn btn-primary rounded-pill py-3 px-5" id="subBtn" value="pay">
</div>
</form>
</div>
</div>
</div>
</div>
<%# include file="../include/footer.jsp"%>
Controller
#RequestMapping(value = "/partnerPlaces/{partner_place_no}", method = RequestMethod.POST)
public String partnerPlaceContentPost(PartnerPlacesVo partnerplacevo ,PaymentsVo paymentvo,
RentalPlacesVo rentalplacevo, Model model, #RequestParam("rental_time_no") int rentaltimeno,
HttpSession session,#RequestParam("payment_price") int payment_price) {
log.info(" partnerPlaceContentPost() 호출");
// log.info("#####rental_date : "+rental_date); // 2022-07-23
log.info("rentalplacevo : "+rentalplacevo.getRental_date());
log.info("rental_date type: "+rentalplacevo.getRental_date().getClass().getName()); // java.sql.Date
String ppname = partnerplacevo.getPartner_place_name();
model.addAttribute("ppname", ppname);
model.addAttribute("payment_price", payment_price);
log.info("ppname, totalprice: "+ppname+payment_price);
MembersVo vo = (MembersVo)session.getAttribute("member");
model.addAttribute("members", vo);
model.addAttribute("rental_time_no", rentaltimeno);
model.addAttribute("payment", paymentvo);
model.addAttribute("rentalplacevo", rentalplacevo);
return "/rental/payment";
}
payment.jsp (use API)
if(rsp.success){
$.ajax({ //verify
type : 'POST',
url : '${PageContext.request.contextPath }/rental/verifyIamport/'+rsp.imp_uid
}).done(function(result){
// rsp.paid_amount와 result.response.amount(서버 검증) 비교 후 로직 실행
if(rsp.paid_amount === result.response.amount){
alert("success pay varify"); console.log("success pay varify");
var rental_date = ${rentalplacevo.rental_date};
alert("rental_date : "+rental_date); // 1992
$.ajax({
url : '${PageContext.request.contextPath }/rental/partnerPlaces/'+${payment.partner_place_no}+'/payment',
type :'POST',
data :{'partner_place_price':${payment.partner_place_price},
'rental_date':${rentalplacevo.rental_date},
'payment_price':${payment_price},
'rental_time_no':${rental_time_no}},
dataType: 'json',
success: function(paymentvo){
alert('Success store all data');
setTimeout(function(){
location.href="${PageContext.request.contextPath }/"
},5000);
}
});
}
}).fail(function(error){
console.log("fail to store data");
});
}else{
alert('fail'+'errorCode : '+rsp.error_code+'errMsg : '+rsp.error_message);
}
Controller - I can't get over here.
#ResponseBody
#RequestMapping(value="/verifyIamport/{imp_uid}")
public IamportResponse<Payment> paymentByImpUid(
Model model, Locale locale, HttpSession session
, #PathVariable("imp_uid") String imp_uid ) throws IamportResponseException, IOException{
log.info("paymentByImpUid");
return api.paymentByImpUid(imp_uid);
}
#ResponseBody
#RequestMapping(value ="/partnerPlaces/{partner_place_no}/payment",method=RequestMethod.POST)
public PaymentsVo payment( Model model,
#RequestParam("partner_place_price") int partner_place_price,
#RequestParam("rental_date") Date rental_date,
#RequestParam("payment_price") int payment_price,
#RequestParam("rental_time_no") int rental_time_no,
#PathVariable("partner_place_no") int partner_place_no,
RentalPlacesVo rentalplacevo, PaymentsVo paymentvo,HttpSession session){
log.info("Vo Info . paymentvo : "+paymentvo);
log.info("Vo Info . RentalPlacesVo : "+rentalplacevo);
log.info("rental_date : "+rental_date);
// log.info("rentdate dataType : "+rentdate.getClass().getName());
// reservationNum (Date-place_no)
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
java.util.Date date = cal.getTime();
String rsNum = sdf.format(date)+"-"+partner_place_no;
log.info(reservationNum"+rsNum);
paymentvo.setReservation_no(rsNum);
MembersVo mvo = (MembersVo)session.getAttribute("member");
paymentvo.setMember_no(mvo.getMember_no());
paymentvo.setPartner_place_no(partner_place_no);
paymentvo.setPartner_place_price(partner_place_price);
paymentvo.setPayment_status(1);
Integer pay = rentalService.pay(paymentvo);
rentalplacevo.setPayment_no(paymentvo.getPayment_no());
if(pay == 1) {
log.info("success");
}else {
log.info("fail");
}
rentalplacevo.setClub_no(46);
rentalplacevo.setMember_no(mvo.getMember_no());
rentalplacevo.setRental_places_no(partner_place_no);
rentalplacevo.setReservation_no(rsNum);
rentalplacevo.setRental_date(rental_date); // date
rentalplacevo.setRental_time_no(rental_time_no); // time
rentalplacevo.setRental_status(1);
rentalService.place(rentalplacevo);
log.info("rentalPlace : "+rentalplacevo);
return paymentvo;
}
Use date related annotations on the date field.
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy/MM/dd")
private Date rental_date;
Best practice:
Also it is recommended to use camel case standard for pojo entity class variables like rentalDate.
I have added image column to my existing table where I want to add image but after changing code in controller class, it didn't add the image instead I get : org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'fileImage' is not present.
should I change java script code on html form ?
1.Controller Class
#PostMapping("/employees")
public String saveEmployee(#Valid #ModelAttribute("employee") Employee employee,
BindingResult bindingResult, #RequestParam("fileImage") MultipartFile multipartFile) throws IOException
{
//Here, we r using ModelAttribute to directly bind form data to the employee object.
if (bindingResult.hasErrors())
{
return "create_employee";
}
else
{
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
employee.setImage(fileName);
Employee savEmployee = employeeService.saveEmployee(employee);
String uploadDir = "/employee-images/" + savEmployee.getId();
Path uploadPath = Paths.get(uploadDir);
if(!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IOException("Could not save uploaded file: " + fileName);
}
employeeService.saveEmployee(employee);
return "redirect:/employees";
}
}
2.HTML Form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee Management System</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<style type="text/css">
span {
color: red;
font-style: italic;
}
option {
margin: 0.5em;
}
</style>
<style type="text/css">
/* a:active {
color: white;
}
a:visited {
color: blue;
} */
a {
display: blue;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Employee Management System</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="changeable" th:href = "#{/employees}">Employee Management</a>
</li>
</ul>
</div>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" th:href="#{/employeesproject}">Employee Project</a>
</li>
</ul>
</div>
</nav>
<br>
<br>
<div class = "container">
<div class = "row">
<div class = "col-lg-6 col-md-6 col-sm-6 container justify-content-center-center card">
<h1 class = "text-center"> Create New Employee </h1>
<div class = "card-body" >
<form th:action="#{/employees}" th:object = "${employee}" method="POST"
enctype="multipart/form-data"
style="max-width: 400px; margin: 0 auto;">
<div class = "form-group">
<label> Employee Image </label>
<input
type = "file"
name = "fileImage"
th:field = "*{image}"
class = "form-control"
id = "fileImage"
accept="image/png, image/jpeg"
/>
<img id="thumbnail" alt="Logo Preview">
</div>
<div>
<script type="text/javascript">
$(document).ready(function() {
$('#fileImage').change(function() {
showImageThumbnail(this);
});
function showImageThumbnail(fileInput) {
file = fileInput.files[0];
reader = new FileReader();
reader.onload = function(e) {
$('#thumbnail').attr('src', e.target.result);
};
reader.readAsDataURL(file);
}
</script>
</div>
<div class = "form-group">
<label> Employee First Name </label>
<input
type = "text"
name = "firstName"
th:field = "*{firstName}"
class = "form-control"
placeholder = "Enter Employee First Name"
/>
<span th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">Name error</span>
</div>
<div class = "form-group">
<label> Employee Last Name </label>
<input
type = "text"
name = "lastName"
th:field = "*{lastName}"
class = "form-control"
placeholder = "Enter Employee Last Name"
/>
<span th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">Name error</span>
</div>
<div class = "form-group">
<label> Employee Email </label>
<input
type = "text"
name = "email"
th:field = "*{email}"
class = "form-control"
placeholder = "Enter Employee Email"
/>
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email error</span>
</div>
<div class = "form-group">
<label> Employee Skills </label> <br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Java" />Java <br>
<input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Python" />Python <br>
<input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value=".Net" />.Net <br>
<input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Kotlin" />Kotlin <br>
<input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="C" />C <br>
<input type="checkbox" th:field = "*{skills}" class = "selectupto3" name = "skills" value="Ruby" />Ruby <br>
<script type="text/javascript">
var limit = 3;
var checked = 0;
$('.selectupto3').on('change', function() {
if($(this).is(':checked'))
checked = checked+1;
if($(this).is(':checked') == false)
checked = checked-1;
if(checked > limit) {
this.checked = false;
checked = limit;
}
});
</script>
<span th:if="${#fields.hasErrors('skills')}" th:errors="*{skills}">skill error</span>
</div>
<div class = "form-group">
<label> Employee Gender </label>
<input type="radio" th:field = "*{gender}" name = "gender" value="Male" />Male
<input type="radio" th:field = "*{gender}" name = "gender" value="Female" />Female
<span th:if="${#fields.hasErrors('gender')}" th:errors="*{gender}">gender error</span>
</div>
<div class = "form-group">
<label> Employee Married? </label>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<input type="checkbox" th:field = "*{marriage}" class = "selectOnly" name = "marriage" value="Married" />Married
<input type="checkbox" th:field = "*{marriage}" class = "selectOnly" name = "marriage" value="Un-Married" />Un-Married
<script type="text/javascript">
$('.selectOnly').on('change', function() {
$('.selectOnly').not(this).prop('checked', false);
});
</script>
<span th:if="${#fields.hasErrors('marriage')}" th:errors="*{marriage}">Marriage status error</span>
</div>
<div class = "form-group">
<label> Employee Birthday </label>
<input type="date" th:field = "*{birthday}" name = "birthday" />
<span th:if="${#fields.hasErrors('birthday')}" th:errors="*{birthday}">Birthday error</span>
</div>
<div class = "container">
<div class = "form-group">
<label for=""> Employee Works at </label>
<select th:field = "*{workat}" class = "form-control" name="workat" id="select1" onchange="populate(this.id,'select2')">
<option th:field = "*{workat}" value="">--SELECT COMAPNY--</option>
<option th:field = "*{workat}" value="NIC-Hyderabad">NIC-Hyderabad</option>
<option th:field = "*{workat}" value="NIC-Bangalore">NIC-Bangalore</option>
</select>
<span th:if="${#fields.hasErrors('workat')}" th:errors="*{workat}">Work at error</span>
<div class = "form-group">
<label for="">Department</label>
<select th:field = "*{workat}" class = "form-control" name="workat" id="select2"></select>
</div>
</div>
</div>
<script type="text/javascript">
function populate(s1,s2)
{
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "NIC-Hyderabad")
{
var optionArray = ['dep-01|Dep-01','dep-02|Dep-02','dep-03|Dep-03',
'dep-04|Dep-04'];
}
else if(s1.value == "NIC-Bangalore")
{
var optionArray = ['dep-01|Dep-01','dep-02|Dep-02','dep-03|Dep-03'];
}
for(var option in optionArray)
{
var pair = optionArray[option].split("|");
var newoption = document.createElement("option");
newoption.value = pair[0];
newoption.innerHTML=pair[1];
s2.options.add(newoption);
}
}
</script>
<div class = "box-footer">
<button type="submit" class = "btn btn-primary">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
I have upload file excel function that run normally in Websphere server 8.5 with JAX-RS 1.1. But when I update to Websphere 9.0 using JAX_RS 2.0, I cannot use #FormParam to upload file, I tried using #MultiPart to replace but it can read .csv file right only, with .xls and .xlsx file it create wrong temp file, so HSSFWorkbook of Apache Poi cannot read inputstream of file normally.
This is my code:
Controller:
#POST
#Path("class/import")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
#RolesAllowed(Role.TRAINING_ADMIN)
public Response importClass(#FormParam("file") File file) {
InputStream is = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(is);
if (checkTokenAndRole(new int[] {1, 11}).getStatus() != Response.Status.OK.getStatusCode()) {
return LoginError(checkToken().getStatus());
} else {
String token = request.getHeader(HttpHeaders.AUTHORIZATION);
String fileExtension = request.getHeader("FileExtension");
return ClassService.getInstance().importClass(file, fileExtension,
token);
}
}
HTML and Js file:
<form data-bind="submit: cancel">
<div class="modal-dialog dialog-class">
<div class="modal-content dialog-class">
<div class="modal-header layout-dialog-header">
<div class="layout-float-left dialog-close-icon">
<span class="glyphicon doc-icon-close-nav" data-bind="click: cancel"></span>
</div>
<div>
<h5 data-bind="text: title" data-i18n="modules.class.uploadSchedule"></h5>
</div>
</div>
<div class=" docs-margin-top-s">
<div>
<div class="form-group marginBot35">
<div class="class-browse">
<div class="col-md-12">
<div>
<label class="label-md search-class-header" for="">
<span class="search-class-header" data-i18n="modules.class.uploadClasslist" data-bind="text: listClass"></span>
</label>
</div>
<div id="" class="col-md-8 control-upload no-padding-left">
<input readonly="true" tabindex="3" class="col-md-12" id='uploadFile' type="text" name="" style="min-height: 40px" data-bind="value: name, attr: {'title': name()}"/>
</div>
<div clas="col-md-4">
<label for="input-file-upload" tabindex="3" class="pull-right btn btn-secondary-aia btn-cancel font-size20" data-dismiss="modal"
data-i18n="buttons.buttonBrowse" >Browse
</label>
</div>
</div>
<div class="class-center-align">
<label class="label-md search-class-header " for="">
<span class="search-class-header" data-i18n="modules.class.downloadThe">Download the</span>
<!-- <a class="class-highlight" tabindex="3" data-i18n="modules.class.trainingSchedule" data-bind="attr: {href: template}, text: textTemplate" download>Training Schedule Template</a> -->
<a class="class-highlight" tabindex="3" data-i18n="modules.class.trainingSchedule" data-bind="click: $root.download, text: textTemplate" >Training Schedule Template</a>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 footer-class" style="padding-bottom:40px">
<button tabindex="3" type="button" class="btn btn-secondary-aia btn-cancel font-size20" data-dismiss="modal" data-i18n="buttons.buttonCancel" data-bind="click: cancel"></button>
<button tabindex="3" type="submit" class="btn btn-primary-aia btn-save font-size20 " style=" cursor: pointer; word-spacing: normal !important" data-bind="click: upload, disable: !readyUpload(),text: buttonUpload" data-dismiss="modal" data-i18n="buttons.buttonUploadSchedule"></button>
</div>
</div>
</div>
</form>
<form id="form-input-file-upload" action="" method="post" enctype="multipart/form-data" style="display:none">
<input id="input-file-upload" type="file" style="" name="file" size="45" accept=".xls,.xlsx" style="display:none" data-bind="attr: {accept: acceptedFiles},event: {change: addFile}" >
</form>
define([
'durandal/app',
'durandal/events',
'plugins/dialog',
'plugins/http',
'knockout',
'jquery',
'config',
'services/utils',
'i18next',
'services/document'
], function (app, Events, dialog, http, ko, $, Config, Utils, i18next, DocumentService) {
'use strict';
return function UploadBulkSchedule(mode) {
var self = this;
Events.includeIn(self);
if(mode === 1){
self.title = ko.observable( i18next.t("modules.bulkAttendee.title") ? i18next.t("modules.bulkAttendee.title") : "");
self.listClass = ko.observable( i18next.t("modules.bulkAttendee.listClass") ? i18next.t("modules.bulkAttendee.listClass") : "");
self.textTemplate = ko.observable( i18next.t("modules.bulkAttendee.template") ? i18next.t("modules.bulkAttendee.template") : "");
self.buttonUpload = ko.observable( i18next.t("modules.bulkAttendee.buttonUpload") ? i18next.t("modules.bulkAttendee.buttonUpload") : "");
}else{
self.title = ko.observable( i18next.t("modules.class.uploadSchedule") ? i18next.t("modules.class.uploadSchedule") : "");
self.listClass = ko.observable( i18next.t("modules.class.uploadClasslist") ? i18next.t("modules.class.uploadClasslist") : "");
self.textTemplate = ko.observable( i18next.t("modules.class.trainingSchedule") ? i18next.t("modules.class.trainingSchedule") : "");
self.buttonUpload = ko.observable( i18next.t("buttons.buttonUploadSchedule") ? i18next.t("buttons.buttonUploadSchedule") : "");
}
self.name = ko.observable();
var acceptedFileArr = [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/csv',
'.xls','.xlsx', '.csv'];
var acceptedExtension = ['xls', 'xlsx', 'csv'];
self.mode = mode;
self.acceptedFiles = ko.observable(acceptedFileArr.join(','));
self.readyUpload = ko.computed(function(){
return self.name() ? true : false;
});
var maxSize = 5242880;
self.template = (self.mode === 1) ? Config.getBackendBaseUrl('/temp/excel/AttendanceImportTemplate/AttendeeListTemplate.xls') :Config.getBackendBaseUrl('/temp/excel/ClassImportTemplate/ClassImportTemplate.zip');
self.templateCSV = Config.getBackendBaseUrl('/temp/excel/ClassImportTemplate/ClassImportTemplate.csv');
var filesArray = [];
self.cancel = function(){
dialog.close(self);
};
self.active = function(){
};
self.upload = function(data, e){
e.preventDefault();
app.showLoading();
var inputTag = $('#form-input-file-upload :input')[0];
var fileName = $(inputTag).val().replace(/^.*[\\\/]/, '');
var extension = fileName.split('.').pop();
var headers = {
FileExtension: extension,
FileName: encodeURIComponent(fileName),
'Authorization': app.user().get('token'),
'isCourseImage': 0
};
if (self.mode === 1) {
self.trigger('uploadSuccess', [ $('#form-input-file-upload :input')[0] ]);
} else {
Utils
.uploadFile(
'class/import',
new FormData(
$('#form-input-file-upload')[0]),
headers)
.then(
function() {
app.hideLoading();
},
function(response) {
var title = i18next
.t('modules.class.errorTitle');
var options = [{
text : i18next
.t('buttons.buttonOk'),
value: Config.Events.DialogMessage.OK
}];
if(response.status === 200){
app.hideLoading();
} else if(response.status === 500){
var errorMessage = Utils
.getErrorMessage(response);
var errorCode = '';
var developerMessage = '';
try{
errorCode = JSON
.parse(response.responseText).errorCode;
developerMessage = JSON
.parse(response.responseText).message;
} catch(e){
}
if (errorCode === 1007
&& developerMessage) {
var messageContent = '<br></br><b>'
+ i18next
.t(
'message.error.importClassSuccess')
.format(
developerMessage)
+ '</b><br></br>';
title = i18next
.t('message.error.importSuccess');
app
.showMessageConfirmTitle(
messageContent,
title,
options,
false,
{
class : 'success-class'
})
.then(
function() {
self
.trigger('uploadSuccess');
dialog
.close(self);
});
} else if(errorMessage){
app.showMessageError(
errorMessage,
title, options,
false, null);
}
} else if(response.status === 0) {
var errorMessage = i18next
.t('message.error.notSaveClassList');
app.showMessageError(
errorMessage, title,
options, false, null);
}
app.hideLoading();
});
}
};
self.browse = function(){
filesArray = [];
document.getElementById("uploadFile").click();
};
self.addFile = function(data, event){
var inputFile = document.getElementById("input-file-upload");
var path = inputFile.value.toString();
var uploadFile = event.currentTarget;
var file = uploadFile.files[0];
var fsize = file.size;
var name, extension;
name = path.replace(/^.*[\\\/]/, '');
extension = name.split('.').pop();
if( fsize > maxSize){
self.name('');
$('#input-file-upload').replaceWith($('#input-file-upload').clone(true));
showUploadMessageWithData(file);
$('#input-file-upload')[0].value = '';
} else if(acceptedExtension.indexOf(extension.toLowerCase()) < 0){
self.name('');
$('#input-file-upload').replaceWith($('#input-file-upload').clone(true));
var messageContent = '<br/><b>'+i18next.t('modules.class.wrongFileExtension')+' </b><br/>';
var options = [{
text: i18next.t('buttons.buttonClose'),
value: Config.Constants.MessageBox.DialogResult.BUTTON_INDEX_0
}];
var title = i18next.t('modules.class.errorTitle');
app.showMessageError(messageContent, title, options, false, null);
$('#input-file-upload')[0].value = '';
} else {
self.name(name);
}
};
function showUploadMessageWithData (file) {
var messageContent = '<p style="white-space: pre-wrap">'+i18next.t('modules.course.editPage.fileName')+': ' + file.name + '</p>';
messageContent += '</br><p><b>'+i18next.t('modules.course.editPage.warnUploadFile')+' </b></p>'; messageContent += '<p><b>'+i18next.t('modules.course.editPage.requireUploadFile')+ ' </b></p>';
var options = [{
text: i18next.t('buttons.buttonOk'),
value: Config.Constants.MessageBox.DialogResult.BUTTON_INDEX_0
}];
var title = i18next.t('modules.class.errorTitle');
return app.showMessageError(messageContent, title, options, false, {class: 'confirm-class'}).then(function () {
});
}
//download Material
self.download = function(fileDownload){
app.showLoading();
DocumentService.downloadTemplate(fileDownload.template).then(function (response) {
app.hideLoading();
var extension = fileDownload.template.split('.').pop();
var ctType = '';
switch(extension) {
case 'jpg':
case 'jpeg':
ctType = 'image/jpeg';
break;
case 'png':
ctType = 'image/png';
break;
case 'doc':
ctType = 'application/msword';
break;
case 'docx':
ctType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'xls':
ctType = 'application/vnd.ms-excel';
break;
case 'xlsx':
ctType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'ppt':
ctType = 'application/vnd.ms-powerpoint';
break;
case 'pptx':
ctType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'pdf':
ctType = 'application/pdf';
break;
default:
break;
}
var byteArray = new Uint8Array(response.data);
var a = window.document.createElement('a');
a.setAttribute("id", "tmpHref");
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: ctType }));
a.download = fileDownload.template.split("/")[fileDownload.template.split("/").length - 1];
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}, function (response) {
app.hideLoading();
Utils.downloadMaterial(response);
});
};
};
});
Anyone can help me give a solution?
Thanks.
I had the solution. I change use IMultipartBody instead using #FormParam,changing ImultipartBody to byte array and use it instead a file.
I'm trying update project and i'm facing with this problem "ERROR TypeError: Cannot set property 'name' of undefined"
Here's update-project.thml:
<!doctype html>
<html class="no-js" lang="en">
<head>
...
</head>
<body ng-app="dateInputExample">
...
<div class="container custom-container">
<form [formGroup]="updateProjectForm" (ngSubmit)="updateProject(updateProjectForm.value)" class="ui form"
style="margin-left: 3%; width: 30%;">
<h1 id="projectTitle">Update Project</h1>
<div style="margin: 0 auto;">
<div style="margin-top: 100px;">
<div class="field">
<label>Project Name</label>
<input type="text" formControlName="projectName" class="form-control" name="projectName"
[(ngModel)]="projectData.name" placeholder="Your project name"
[ngClass]="{'is-invalid' : submitted && updateProjectForm.controls.projectName.errors}"/>
<div *ngIf="submitted && updateProjectForm.controls.projectName.errors" class="err_msg form-text">
<p class="err-msg">Project Name is required</p>
</div>
</div>
<div class="field" style="margin-top: 5%;">
<label>Project Description</label>
<textarea rows="4" cols="50" formControlName="projectDescription" [(ngModel)]="projectData.description"
class="form-control"
placeholder="Your project description"></textarea>
</div>
<label>Expiry Date</label>
<div>
<input type="date" formControlName="expiryDate" class="form-control" [(ngModel)]="dateInForm"
placeholder="expiryDate"
min="2019-08-07" max="2020-12-31" required/>
</div>
<div class="form-panel ui-helper-hidden">
<label>Budget</label>
<input type="number" formControlName="budget" maxlength="16" placeholder="Budget"
[(ngModel)]="projectData.budget">
</div>
<div class="field" style="margin-top: 5%;" *ngIf="showSkills">
<label>Skills</label>
<div class="ui segment">
<app-skills-multiselect>
</app-skills-multiselect>
</div>
</div>
<div class="field" style="margin-top: 5%;" *ngIf="showProjectType">
<label>Project Type</label>
<div class="ui segment">
<app-pt-multiselect></app-pt-multiselect>
</div>
</div>
<div class="field" style="margin-top: 5%;">
<button type="submit" class="ui primary button">Update</button>
<a routerLink="/back" class="ui button">Cancel</a>
</div>
</div>
</div>
</form>
</div>
...
</body>
</html>
Here's update-project.ts
...
export class UpdateProjectComponent implements OnInit {
constructor(private formBuilder: FormBuilder, private projectService: ProjectService, private activatedRoute: ActivatedRoute,
private rout: Router, private datePipe: DatePipe) {
this.submitted = false;
this.router = rout;
this.updateProjectForm = this.formBuilder.group({
projectName: ['', [Validators.required]],
...
});
}
saved = false;
submitted: boolean;
projectName: string;
router: Router;
project: Project;
projectData: any = {};
dateInForm: string;
showMsg = false;
showErrMsg = false;
showSkills = false;
showProjectType = false;
skill = [];
selectedType = [];
#ViewChild(PrMultiselectComponent, { static: false })
private prMultiselectComponent: PrMultiselectComponent;
#ViewChild(SkillsMultiselectComponent, { static: false })
private skillMultiselectComponent: SkillsMultiselectComponent;
id = this.activatedRoute.snapshot.params.id;
updateProjectForm: any;
save() {
this.saved = true;
}
ngOnInit() {
this.projectService.getProjectById(this.id).subscribe(data => {
this.projectData = data;
console.log(this.projectData);
// Show selected skills
this.skillMultiselectComponent.selectedItems = this.projectData.skillSet.map(this.skillMultiselectComponent.parseSkillsList);
console.log(this.skillMultiselectComponent);
// Show selected Type
this.selectedType.push({ id: this.projectData.projectType.id,
itemName: this.projectData.projectType.name });
this.prMultiselectComponent.selectedTypeItems = this.selectedType;
// TODO don't show expiry date
// this.dateInForm = this.datePipe.transform(this.projectData.expiryDate, 'MM-dd-yyyy');
// console.log(this.dateInForm);
});
this.showSkills = true;
this.showProjectType = true;
}
canDeactivate(): boolean | Observable<boolean> {
if (!this.saved) {
return confirm('Are yo sure you want to left this page without saving information?');
} else {
return true;
}
}
updateProject(projectDataFromForm) {
if (window.confirm('Are you sure, you want to update?')) {
console.log('in updateProject()');
console.log(projectDataFromForm);
this.submitted = true;
this.project.name = projectDataFromForm.projectName;
this.project.description = projectDataFromForm.projectDescription;
this.project.expiryDate = projectDataFromForm.expiryDate;
this.project.budget = projectDataFromForm.budget;
// this.project.projectTypeId = this.idprojecttype;
this.project.projectTypeId = this.prMultiselectComponent.getSelectedItems();
this.project.skills = this.skillMultiselectComponent.getSelectedItems();
// var data = this.selectedItems.map(t=>t.id);
this.projectService.updateProject(this.id, this.project).subscribe(
data => {
this.updateProjectForm.reset();
this.showMsg = true;
// this.router.navigate(['/home']);
console.log('Successfully updated!');
},
err => {
this.showErrMsg = true;
console.log('Update failed!');
});
}
}
}
ng:///AppModule/UpdateProjectComponent.ngfactory.js:94 ERROR TypeError: Cannot set property 'name' of undefined
at UpdateProjectComponent.updateProject (:4200/main.js:2678)
at Object.eval [as handleEvent] (ng:///AppModule/UpdateProjectComponent.ngfactory.js:111)
at handleEvent (:4200/vendor.js:101276)
at callWithDebugContext (:4200/vendor.js:102894)
at Object.debugHandleEvent [as handleEvent] (:4200/vendor.js:102530)
at dispatchEvent (:4200/vendor.js:88996)
at :4200/vendor.js:90893
at SafeSubscriber.schedulerFn [as _next] (:4200/vendor.js:94272)
at SafeSubscriber.__tryOrUnsub (:4200/vendor.js:193518)
at SafeSubscriber.next (:4200/vendor.js:193457)
If I deleted 'name' field showed the same problem with description....
Thanks for the help!
Reason for Error :
[(ngModel)]="projectData.name" , if you are using [(ngModel)] 2-way data binding it will need some initial values, but it gets undefined
1st Solution *ngIf='projectData':
<div class="container custom-container">
<form [formGroup]="updateProjectForm" (ngSubmit)="updateProject(updateProjectForm.value)" class="ui form"
style="margin-left: 3%; width: 30%;">
<h1 id="projectTitle">Update Project</h1>
<div style="margin: 0 auto;" *ngIf='projectData'> <!-- HERE -->
<div style="margin-top: 100px;">
<div class="field">
<label>Project Name</label>
<input type="text" formControlName="projectName" class="form-control" name="projectName"
[(ngModel)]="projectData.name" placeholder="Your project name"
[ngClass]="{'is-invalid' : submitted && updateProjectForm.controls.projectName.errors}" />
<div *ngIf="submitted && updateProjectForm.controls.projectName.errors" class="err_msg form-text">
<p class="err-msg">Project Name is required</p>
</div>
</div>
...
</div>
</div>
</form>
</div>
2nd Soltuion (Provide some initial value):
project: Project = {
..., // other values too
name : ''
};
3rd option, remove [(ngModel)] 2-way data binding from all:
this.project.name = projectDataFromForm.projectName;
this.project.description = projectDataFromForm.projectDescription;
this.project.expiryDate = projectDataFromForm.expiryDate;
this.project.budget = projectDataFromForm.budget;
// this.project.projectTypeId = this.idprojecttype;
this.project.projectTypeId = this.prMultiselectComponent.getSelectedItems();
this.project.skills = this.skillMultiselectComponent.getSelectedItems();
// --- Patch value will set values in your form ---
this.updateProjectForm.patchValue(this.project); // <---- HERE
I think your problem is caused by this line:
this.project.name = projectDataFromForm.projectName;
because as far as I can see, you don't instantiate your Project object.
In ngOnInit, try adding
this.project = new Project(/* include any necessary data here for the Project constructor */);
I want to direct the button to another page
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit"
onclick="location.href = "addnewcustomer.php";" id ="newcust"
class="btnRegister" value = "New Customer">';
}
I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.
There are no errors. Just the button didn't function the way i want it to
You have to escape quotes in element. Try following code
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
}
<a onclick="showInput()" >Add New Buton</a>
<div id="demo"></div>
You can use following code to redirect page.
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" id ="newcust" class="btnRegister" value = "New Customer" />';
}
document.getElementById("newcust").onclick = function () {
location.href = "addnewcustomer.php";
}
<div id="demo"></div>
<a onclick="showInput()" >Click To Get Button</a>
Try this
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'https://www.youtube.com/\';" class="btnRegister" value = "New Customer">';
}
showInput()
<p id="demo">click</p>
It is because you didn’t close your input tag
Try this...
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit"
onclick="location.href = "addnewcustomer.php";" id ="newcust"
class="btnRegister" value = "New Customer"/>';
}
If you don’t close it the button will not work.
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = "yourpage.php";" id ="newcust" class="btnRegister" value = "New Customer">';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="showInput()" >Click To Get Button</a>
<p id="demo"></p>
Right Click And inspect Button.
Try the code below, the inner html text is missing with escape string. Call window.onload to trigger your method and display your button. HTH.
<head>
<script type="text/javascript">
function showInput() {
document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
}
window.onload = showInput;
</script>
</head>
<body>
<p id="demo"></p>
</body>