'Validation Form thymeleaf for save product request para
hello i'm begginner in spring boot MVC, i want to vaidate my addProduct form which has a method save with request param ,the errors are showing in the error page not in the div error in the view //View
<form method="post" th:action="@{/addP}" th:object="${product}" enctype="multipart/form-data">
<div class="row">
<div class="input-control">
<label for="name">name</label>
<input id="name" th:field="*{name}" name="name" type="text">
<div class="error"></div>
</div>
<div class="col-md-6 mb-3">
<label for="email">description :</label> <textarea th:field="*{description}" placeholder="Ecrire quelques choses..." class="form-control" id="description" rows="3"></textarea> <br />
<p th:if="${#fields.hasErrors('description')}" th:errors="*{description}"
class="alert alert-danger"></p>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<label class="floating-label" for="Text">Prix Unitaire :</label>
<input type="text" name="price" th:field="*{price}" class="form-control" id="price" placeholder="Prix" value="" required>
<div class="alert alert-danger error-alert" th:if="${#fields.hasErrors('price')}" th:errors="*{price}"></div>
</div>
<div class="col-sm-4">
<label class="floating-label" for="Text">Stock:</label>
<input type="text" th:field="*{stock}" class="form-control" id="stock" placeholder="Prix" value="" required>
<div class="alert alert-danger error-alert" th:if="${#fields.hasErrors('stock')}" th:errors="*{stock}"></div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="floating-label" for="Email">Stock Min</label>
<input type="text" class="form-control" id="text" aria-describedby="emailHelp" placeholder="Stock Min...">
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputState">Catégorie</label>
<select id="category" th:field="*{category}"class="form-control">
<option value="0">Sélectionner catégorie</option>
<option th:each="category :${categories}"
th:value="${category.id}"
th:text="${category.name}" >
</select>
<span th:if="${#fields.hasErrors('category')}" th:errors="*{category}" class="alert alert-danger"></span>
</div>
<div class="form-group col-md-6">
<label for="inputState">Marque</label>
<select th:field="*{brand}" id="brand" class="form-control">
<option value="0">Sélectionner marque</option>
<option th:each="brand :${brands}"
th:value="${brand.id}"
th:text="${brand.name}" >
</select>
<span th:if="${#fields.hasErrors('brand')}" th:errors="*{brand}" class="alert alert-danger"></span>
</div>
</div>
<div class="custom-file mb-4">
<input type="file" name="file" class="custom-file-input"
id="customFile"> <label class="custom-file-label"
for="customFile">Product Image</label>
</div>
<button type="submit" class="btn btn-primary" >Ajouter</button>
</form>
//Model
@Entity@Table(name = "produit")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "Le nom ne doit pas être vide !!!")
private String name;
@Min(value = 1, message = "Le stock doit être superieur à 0")
@NotNull(message = "Stock cannot be empty")
private int stock;
@NotNull(message = "Attention !! Sélectionnez la marque..")
@ManyToOne(fetch = FetchType.LAZY)
private Brand brand;
@NotNull(message = "Attention !! Sélectionnez la catègorie..")
@ManyToOne(fetch = FetchType.LAZY)
private Category category;
@NotNull(message = "Price cannot be empty")
@Min(value = 1, message = "Le prix doit être superieur à 0")
private double price;
private double weight;
@NotEmpty(message = "Attention !! Remplir la description..")
private String description;
@Lob
@Column(columnDefinition = "MEDIUMBLOB")
private String content;}
// ProductService
public void saveProductToDB(MultipartFile file,String name,String description
,int price,int stock,Category category,Brand brand)
{
Product p = new Product();
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
if(fileName.contains(".."))
{
System.out.println("not a a valid file");
}
try {
p.setContent(Base64.getEncoder().encodeToString(file.getBytes()));
System.out.println("aaaaaaa");
} catch (IOException e) {
e.printStackTrace();
}
p.setDescription(description);
p.setName(name);
p.setPrice(price);
p.setStock(stock);
p.setCategory(category);
p.setBrand(brand);
productRepo.save(p);}
}
//controller
@GetMapping(value = "/addP")
public String createUserView(Model model) {
model.addAttribute("product",new Product());
model.addAttribute("categories", categoryService.getAllCategory());
model.addAttribute("brands", marqueService.getAllMarque());
return "addProduct";
}
@PostMapping("/addP")
public String saveProduct(@Valid Product article,BindingResult result,@RequestParam("file") MultipartFile file,
@Valid @RequestParam("name") String name,
@RequestParam("price") int price,
@RequestParam("stock") int stock,
@RequestParam("description") String desc
,@RequestParam("category") Category category,
@RequestParam("brand") Brand brand)
{
if(result.hasErrors()){
return "addProduct";
}
productService.saveProductToDB(file, name, desc, price,stock,category,brand);
return "redirect:article/article-list";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
