Exercise 20: Building Forms - jkneal/spring-angular-train GitHub Wiki
Learn how to build forms using Spring and Thymeleaf. Learn how to add items.
-
In
src/main/resources/templates/shop, create a new file named 'add-product.html' -
Like you did in exercise 18, add the HTML 5 doctype and the html tag importing thymeleaf, then add the following content:
<head th:replace="home :: head">
</head>
<body>
<header th:replace="home :: header">
</header>
<main class="container">
</main>
<footer th:replace="home :: footer">
</footer>
<div th:replace="home :: scripts">
</div>
</body>- Now within the main container, add the following content:
- An
h4header with the text 'Add Product' - A
formtag that posts to '/shop/add' and works with the model object 'product' - Within the form, add an
inputof type 'text' that points to the fieldname. Before the input, add alabelwith text 'Product Name' - After the input, add a
textareathat points to the fielddescription. Before the textarea, add alabelwith text 'Product Description' - After the textarea, add a
selectthat points to the fieldcategory. Add the CSS class 'browser-default' to the select tag. Before the select, add alabelwith text 'Product Category' - Now using the model attribute
categories, generate options for the select just created. Use the categoryidproperty as theoptionvalue, and thecodeproperty as the option text - After the select, add an
inputof type 'text' that points to the fieldprice. Before the input, add alabelwith the text 'Product Price' - Finally add a paragraph (
p) tag. Within the paragraph, add abuttontag with type 'submit' and CSS class 'btn'. For the button text use 'Add'
-
Now open
edu.train.shop.ShopController. Add a method named 'getAddProduct' that maps to the path '/add' and accepts Http Get methods. The method should accept an argument with name 'model' and typeorg.springframework.ui.Model. Add a new edu.train.product.Product instance as a model attribute with name 'product'. Finally, return the logical view for the html file you created in step 1 -
In the same controller, add a method named 'addProduct' that maps to the path '/add' and accepts Http Post methods. The method should accept an argument with name 'product' and type
edu.train.product.Product. Save the product argument using the `productRepository'. Finally, redirect to the path '/shop' -
Again in the ShopController, add a method that will populate the model attribute 'categories' by invoking the
edu.train.category.CategoryRepositorymethod 'findAll'
- Start the training application and go to the app home page
- Click on the link 'Exercise 20'. Verify the returned page looks like the following:

-
Verify you have five items available in the product category select
-
Now complete each of the fields on the add product page and click 'Add'. Verify you are returned to the shop page and the item you added appears in the products table (should be last item)