I want ro concate some things in thymeleaf but concate symbol throws
unexcepted '+' error, I define ctotal in my common.kt class and want
to use the reference of the ctotal in cart.html but ctotal shows under
redline error I donot know which type of error it
cart.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/head.html">
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<nav th:replace="/fragments/nav :: nav-front"></nav>
<div class="container-fluid mt-5">
<div class="row">
<div th:replace="/fragments/categories"></div>
<div class="col"></div>
<div class="col-7">
<div class="overlay text-center d-none">
<h4 class="display-4">You are being redirected to paypal...</h4>
<img src="/images/ajax-loader.gif" alt="">
</div>
<h2 class="display-4">Cart Overview</h2>
<table class="table">
<tr>
<th>Product</th>
<th>Image</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr th:each="el: ${cart}">
<td th:text="${el.value.name}"></td>
<td>
<img style="width: 100px;" th:src="#{'/media/' + ${el.value.image}}" />
</td>
<td>
<span th:text="${el.value.quantity}"></span>
<a th:href="#{'/cart/add/'+${el.value.id}} + '?cartPage=true'"
class="btn btn-success btn-sm">+</a>
<a th:href="#{'/cart/subtract/'+${el.value.id}}" class="btn btn-primary btn-sm">-</a>
<a th:href="#{'/cart/remove/'+${el.value.id}}" class="btn btn-danger btn-sm">remove</a>
</td>
<td th:text="'$' + ${el.value.price}"></td>
<td th:with="formattedTotal=${el.value.price} * ${el.value.quantity}" th:text="'$' + ${#numbers.formatDecimal(formattedTotal, 0, 'COMMA', 2, 'POINT')}"
>
</td>
</tr>
<tr>
<td class="text-right" colspan="4"><b>Grand Total:</b></td>
<td colspan="1" th:text="'$' + ${#numbers.formatDecimal(ctotal, 0, 'COMMA', 2, 'POINT')}"></td>
</tr>
<tr>
<td>
Clear Cart
</td>
<td colspan="4" class="text-right">
Checkout
</td>
</tr>
</table>
</div>
<div class="col"></div>
</div>
</div>
<form id="paypalform" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="zennil1305014666#gmail.com">
<th:block th:each="el, iter : ${cart}">
<input type="hidden" th:name="'item_name_'+${iter.count}" th:value="${el.value.name}">
<input type="hidden" th:name="'amount_'+${iter.count}" th:value="${el.value.price}">
<input type="hidden" th:name="'quantity_'+${iter.count}" th:value="${el.value.quantity}">
</th:block>
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
<div th:replace="/fragments/footer"></div>
<script>
$(function () {
$("a.checkout").click(function (e) {
e.preventDefault();
$("div.overlay").removeClass("d-none");
$.get("/cart/clear", {}, function () {});
$("form#paypalform").submit();
});
});
</script>
</body>
</html>
i got error exact line 33 on the '+' symbol
<a th:href="#{'/cart/add/'+${el.value.id}} + '?cartPage=true'"
class="btn btn-success btn-sm">+</a>
And got red underlined error below line
<td colspan="1" th:text="'$' + ${#numbers.formatDecimal(ctotal, 0, 'COMMA', 2, 'POINT')}"></td>
at ctotal i got redline error .ctotal i defined in my common class
common.kt
package com.nilmani.cmsshopingcart
import com.nilmani.cmsshopingcart.model.Cart
import com.nilmani.cmsshopingcart.model.Category
import com.nilmani.cmsshopingcart.model.Page
import com.nilmani.cmsshopingcart.repository.CategoryRepository
import com.nilmani.cmsshopingcart.repository.PageRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ModelAttribute
import java.security.Principal
import javax.servlet.http.HttpSession
#ControllerAdvice
class Common {
#Autowired
private lateinit var pageRepo: PageRepository
#Autowired
private lateinit var categoryRepo: CategoryRepository
#ModelAttribute
fun sharedData(model: Model, session: HttpSession, principal: Principal?) {
if (principal != null) {
model.addAttribute("principal", principal.name)
}
val pages: List<Page> = pageRepo.findAllByOrderBySortingAsc()
val categories: List<Category> = categoryRepo.findAllByOrderBySortingAsc()
var cartActive = false
if (session.getAttribute("cart") != null) {
val cart: HashMap<Int, Cart> = session.getAttribute("cart") as HashMap<Int, Cart>
var size = 0
var total = 0.0
for (value in cart.values) {
size += value.quantity
total += value.quantity * value.price.toDouble()
}
model.addAttribute("csize", size)
model.addAttribute("ctotal", total)
cartActive = true
}
model.addAttribute("cpages", pages)
model.addAttribute("ccategories", categories)
model.addAttribute("cartActive", cartActive)
}
}
Related
i use livewire defer loading for load data after rendering page.
After opening the page, the information is successfully received and displayed in the table
But the problem is that I use datatable and when the received information is displayed, datatable becomes a simple table. As if I did not use datatable at all.
This is the livewire component code
class Cryptolist extends Component
{
public bool $loadData = false;
public function init()
{
$this->loadData = true;
}
public function render()
{
try {
if ($this->loadData) {
$api = new \Binance\API('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins);
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
And this is the component view where the table is located and displays the received information
<div wire:init="init">
#if ($loadData)
<div id="loadesh1" wire:ignore>
<table class="datatable-init nk-tb-list nk-tb-ulist" data-auto-responsive="false">
<thead>
<tr class="nk-tb-item nk-tb-head">
<th class="nk-tb-col"><span class="sub-text">name</span></th>
<th class="nk-tb-col tb-col-mb"><span class="sub-text">balance</span></th>
</tr>
</thead>
<tbody>
#foreach ($coins as $item => $value)
<tr class="nk-tb-item">
<td class="nk-tb-col">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0"
src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid"
alt="">
#else
<img style="border-radius: 0"
src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png"
class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</td>
<td class="nk-tb-col tb-col-mb" data-order="{{$value['coin']}}">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light"
wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</td>
</tr><!-- .nk-tb-item -->
#endforeach
</tbody>
</table>
</div>
#else
Loading data...
#endif
</div>
What do you think is the problem, what code is written incorrectly?
I made a shopping cart, where a product item gets added to the cart. When I click the product, it gets stored in a cart, but not local storage. I set it local-storage. When I click a product that already exists in the cart, I want to increment its quantity, but that's not happening. It adds another row instead, which I want to prevent.
Here is my component:
<template>
<div class="row">
<div class="col-md-8">
<div v-for="(product, id) in products" :key="id" class="col-xl-3 col-sm-6 mb-3 float-left">
<div class="card o-hidden h-100">
<div class="card-body">
<div class="card-body-icon">
<i class="fas fa-fw fa-comments"></i>
</div>
<div class="mr-5">{{product.name}}</div>
</div>
<div class="card-footer clearfix small z-1 form-group row" href="#">
<span class="float-left"><input type="text" v-model="product.qty" class="form-control form-control-sm mb-2"></span>
<strong class="float-right col-sm-6">
{{product.price}} TK
</strong>
<button class="btn btn-sm btn-info float-right col-sm-6" #click="addToCart(product)">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<table class="table table-sm">
<thead>
<tr>
<th>#SL</th>
<th>Name</th>
<th>Qty</th>
<th>Price</th>
<th>L/T</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(cart, i) in carts" :key="i">
<td>{{cart.id}}</td>
<td>{{cart.name}} </td>
<td class="text-right">{{cart.qty}}</td>
<td class="text-right">{{cart.price}}</td>
<td class="text-right">{{cart.price*cart.qty}}</td>
<td><button type="button" #click="removeProduct(i)" class="btn btn-sm btn-danger">x</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" class="text-right font-weight-bold">Total</td>
<td class="text-right"> {{total}}/-</td>
</tr>
</tfoot>
</table>
<div>
<button class="btn btn-sm btn-info float-right">Checkout</button>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
products:[],
carts:[],
}
},
computed:{
total(){
var total = 0
this.carts.forEach(cart => {
total += parseFloat(cart.price * cart.qty)
})
return total
},
},
mounted(){
this.showProduct()
},
methods:{
showProduct(){
axios.get('api/pos')
.then(res=>{
this.products = res.data.data
});
},
addToCart(product){
this.carts.push(product)
},
removeProduct(i){
this.carts.splice(i,1)
}
}
}
</script>
Here is the screenshot:
The problem is addToCart() just pushes another product into the cart without checking if it already exists.
To fix the problem, update that method to find the item, and increment the item's quantity if found. Otherwise, push another item into the cart:
addToCart(product) {
if (this.carts.find(p => p.id === product.id)) {
product.qty++
} else {
this.carts.push(product)
}
}
Im new to Angular and My Requirement is
A component includes a form with the field name call "Brand" and a button to add the same record to database through angular service and there should be a datatable which is fetching all brand data from database to data table.
so by using fetchall method in ts file, i am assigning values to data table. im calling fetchall method to ngoninit() which helps me to show the data in table while component get initialized. to add record, i am using a method call addyear() and calling the same method to onSumbit(). my problem is when i add the record to database, i should be able to load newly added record to angular data table! since that method in ngoninit(), i have to refresh the browser to get the record in data table kindly give me a solution. for the back end, im using Spring boot with Postgres database
My Component TS file
constructor(private brandService:BrandService,private toastyService: ToastyService) { }
ngOnInit() {
this.findbrand();
}
onSubmit()
{
this.saveBrand();
this.submitted=true;
}
saveBrand()
{
this.brandService.addbrand(this.brand).subscribe
(data=>this.addToast({title:'Record Has been added Successfully', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'success'}),
error=>this.addToast({title:'Record Not Added! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
this.brand=new Brand();
}
findbrand()
{
this.brandService.findbrand().subscribe(data=>this.data=data,error=>this.addToast({title:'Record Cannot be found! Sorry', msg:'', timeout: 5000, theme:'default', position:'top-right', type:'error'}));
}
My Service.TS file
export class BrandService {
constructor(private http:HttpClient) { }
private baseUrl='http://localhost:8080/snazzy-engine/brand';
addbrand(brand:object):Observable<any>
{
return this.http.post(`${this.baseUrl}` + `/insert`, brand,{
headers: {'schemaName':'test.'}
});
}
findbrand():Observable<any>
{
return this.http.get(`${this.baseUrl}` + `/find-all`,{
headers: {'schemaName':'test.'}
});
}
getbrandid(id: number): Observable<Object> {
return this.http.get(`${this.baseUrl}/find-one/${id}`, {headers:
{'schemaName':'test.'}});
}
}
My HTML File
<div class="table-content crm-table">
<div class="project-table">
<div id="crm-contact" class="dt-responsive">
<div class="row">
<div class="col-xs-12 col-sm-12 col-sm-12 col-md-6">
<div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-6">
<div style="text-align: right;">
<label>Search:
<input type="search" [(ngModel)]="filterQuery" class="form-control input-sm full-data-search" placeholder="Search name">
</label>
</div>
</div>
</div>
<!-- <div class="panel-heading">User information</div>-->
<div class="table-responsive">
<table class="table table-bordered table-hover table-sm" [mfData]="data | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy"
[(mfSortOrder)]="sortOrder">
<thead class="thead-dark text-center">
<tr>
<th style="width:10%">
<mfDefaultSorter by="brandId">Brand ID</mfDefaultSorter>
</th>
<th style="width:70%">
<mfDefaultSorter by="name">Brand Name</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="more">More</mfDefaultSorter>
</th>
<th style="width:10%">
<mfDefaultSorter by="checkbox">Delete</mfDefaultSorter>
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of mf.data; let i = index;">
<td>{{item.brandId}}</td>
<td>{{item.brand}}</td>
<td class="action-icon">
<button type="button" class="btn btn-sm btn-primary" (click)="findybrandid(item.brandId);modalDefault.show();">
edit
</button>
</td>
<td>
<div class="checkbox text-center">
<label><input type="checkbox" value=""></label>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="10">
<mfBootstrapPaginator class="pagination-main f-right"></mfBootstrapPaginator>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<div style="text-align:center;">
<button class="btn btn-out btn-danger ripple light"><i class="icofont icofont-check-circled"></i>Delete</button>
</div>
</div>
</div>
</div>
try this
saveBrand()
{
this.brandService.addbrand(this.brand)
.subscribe(
data => this.addToast(
{
title:'Record Has been added Successfully',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'success'
}),
error => this.addToast(
{
title:'Record Not Added! Sorry',
msg:'',
timeout: 5000,
theme:'default',
position:'top-right',
type:'error'
})
);
this.data.push(this.brand); /*change: push new data into an array*/
this.brand=new Brand();
}
I have an HQL query from my repository and I want to get information from my class where condition class type = string. The error is field is not present.
View:
<div layout:fragment="content">
<div class="col-sm-12">
<div class="panel panel-primary">
<div class="panel-heading">Mes demandes</div>
<div class="panel-body">
<form th:action="#{/demande}" method="post">
<div>
<label>Type de la demandes:</label>
<select name="field">
<option th:value="Demande_absence">Demande d'absence</option>
<option th:value="Demande_conge">Demande de congé</option>
<option th:value="Demande_document">Demande de documtents</option>
<option th:value="Demande_pret">Demande de prĂȘt</option>
</select>
<button type="submit" class="btn btn-primary">Chercher</button>
</div>
</form>
<form th:action="#{/AddDemande}" method="post">
<button type="submit" class="btn btn-primary">Ajouter une demande</button>
</form>
<div class="container-fluid spacer50">
<h3 class="text-danger">Liste des demandes</h3>
<table class="table">
<thead>
<tr>
<th>Code</th><th>date</th><th>TYPE_DEM</th>
</tr>
</thead>
<tbody>
<tr th:each="p:${listdemandes}">
<td th:text="${p.codeDemande}"></td>
<td th:text="${p.dateDemande}"></td>
<td th:text="${p.class.simpleName}"></td>
<td><a th:href="#{/afficher(id=${p.codeDemande})}">Informations sur la demande</a></td>
</tr>
</tbody>
</table>
</div>
<div class="text-danger" th:if="${exception}" th:text="${exception.message}">
</div>
<div class="container col-sm-8">
<ul class="nav nav-pills">
<li th:class="${pageCourante}==${status.index}?'active':''" th:each="pa,status:${pages}" >
<a th:href="#{demande(page=${status.index},size=${size})}" th:text="${status.index}"></a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
Controller :
#RequestMapping(value="/demande")
public String dem(Model model,
#RequestParam(name="page",defaultValue="0")int p,
#RequestParam(name="size",defaultValue="4")int s,
#RequestParam(name="field",defaultValue="4")String type) {
String pr_emp;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Long matricule =Long.parseLong(auth.getName());
pr_emp=employeRepository.prenom(matricule);
Page<Demande> PageDemande=demandeRepository.listdemande(matricule,"valide",type,new PageRequest(p,s));
int[] pages = new int[PageDemande.getTotalPages()];
model.addAttribute("pages", pages);
model.addAttribute("size", s);
model.addAttribute("pagecourante", p);
model.addAttribute("prenom", pr_emp);
model.addAttribute("matricule", matricule);
model.addAttribute("listdemandes",PageDemande.getContent());
return "demandes";
}
Repository Query:
#Query("select d from Demande d where d.employe.matricule=:x and d.valide=:isvalide and d.class=:type order by dateDemande")
public Page<Demande> listdemande(#Param("x") Long matricule,
#Param("isvalide") String isvalide,
#Param("type") String type,
Pageable pageable);
I created a web page displays users information and register a new user. If we try to enter existing user it is showing the error message. when I refresh the page the error is still exist. How to clear the error message when we refresh or when we click reset button.I am using spring Boot Here is my code.
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Registration </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
th:href="#{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}"
rel="stylesheet" media="screen" />
</head>
<body>
<div class="container">
<div class="page-header" id="banner">
<div class="row">
<div class="col-lg-8 col-md-7 col-sm-6">
<h1>Users</h1>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>UserId</th>
<th>USerName</th>
</tr>
</thead>
<tbody border="0">
<tr th:each="user :${users>
<td th:text="${user.userId}"></td>
<td th:text="${user.userName}" > </td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-7 col-sm-6">
<h1>Register USer</h1>
<form th:action="#{/registerUser}" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="col-lg-3 control-label">Enter UserId</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="userId" value=""/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Enter UserName</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="userName" value=""/>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-lg-offset-3">
<button type="submit" class="btn btn-primary" name="button">registerUSer</button>
<button type="reset" class="btn">Reset</button>
</div>
</div>
<div th:if="*{errorMessage != null}" class="alert alert-danger" th:text="*{errorMessage}">
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here is my controller:
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public String registrationForNewUSer(#RequestParam Long userId, #RequestParam String userName, Model model)
throws Exception {
//checking whether user already exist
UserModel userInfo = userInfo.findOne(userId);
if (userInfo != null) {
String str = "user already exist" + userId;
model.addAttribute("errorMessage", str);
return usersList(model);
} else {
//
return "redirect:/registerUser/" + userId + "/" + userName;
}
}
#RequestMapping(value = "/usersList", method = RequestMethod.GET)
public String usersList(Model model) {
model.addAttribute("users", userInfo.findAll());
return "usersview";
}
#RequestMapping("/registerUser/{userId}/{userName}")
public ResponseEntity<Object> authentication{
// it does authenticationprocess and add user user in database and redirect to usersview.
}