Additionally options can be added dynamically
authorKai Moritz <kai@juplo.de>
Tue, 21 Jan 2020 23:38:43 +0000 (00:38 +0100)
committerKai Moritz <kai@juplo.de>
Fri, 7 Apr 2023 11:15:40 +0000 (13:15 +0200)
src/main/java/de/juplo/demo/DemoController.java
src/main/java/de/juplo/demo/Form.java
src/main/resources/templates/form.html

index b841780..c74a6e9 100644 (file)
@@ -6,6 +6,8 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.thymeleaf.util.StringUtils;
 
 
 /**
@@ -30,4 +32,19 @@ public class DemoController
             .collect(Collectors.joining(", ", ", ", "")));
     return "form";
   }
+
+  @RequestMapping(path = "/", params = "add")
+  public String add(@ModelAttribute Form form, @RequestParam String name)
+  {
+    if (!StringUtils.isEmptyOrWhitespace(name))
+    {
+      form.map.put(name.trim(), Boolean.FALSE);
+      log.info("Added option \"{}\" to the map", name.trim());
+    }
+    else
+    {
+      log.info("Ignoring empty option-name");
+    }
+    return display(form);
+  }
 }
index c44eb6c..b6e933b 100644 (file)
@@ -1,6 +1,7 @@
 package de.juplo.demo;
 
 
+import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
@@ -17,7 +18,8 @@ public class Form
   Boolean option;
   Inner inner = new Inner();
   Map<String, Boolean> map =
-      Stream.of( "foo", "bar" ).collect(Collectors.toMap(a -> a, a -> false));
+      new LinkedHashMap<>(
+          Stream.of( "foo", "bar" ).collect(Collectors.toMap(a -> a, a -> false)));
 }
 
 @Data
index b8b5158..70841c9 100644 (file)
                 <input type="checkbox" class="form-check-label" th:field="*{map[__${key}__]}" />
                 <label class="form-check-label" th:for="|map${key}1|" th:text='|Option "${key}" From The Map|'>Option "KEY" From The Map</label>
               </div>
+              <div class="input-group">
+                <span class="input-group-prepend"><span class="input-group-text">New Option</span></span>
+                <input type="input" class="form-control" name="name" />
+                <span class="input-group-append"><button type="submit" class="btn btn-primary" name="add">Add</button></span>
+              </div>
             </div>
           </div>
           <div class="card-footer">