I have a form where the user can add as much as he want of Table object that also can contains as much as he want of Columns object (like building tables in SQL).. I've tried the code bellow but nothing works and the form dosnt appear anymore when I've tried to bind the two lists.
Controller
@ModelAttribute("page")
public Page getTable() {
TableColumn column = new TableColumn();
List<TableColumn> columns = new ArrayList<>();
columns.add(column);
Table table = new Table();
table.setColumns(columns);
List<Table> tables = new ArrayList<>();
tables.add(table);
Page page = new Page();
page.setTables(tables);
return page;
}
@GetMapping("/scriptsqlgenerator")
public String viewForm(@ModelAttribute("page") Page page) {
return "ScriptSqlNext";
}
@PostMapping("/scriptsqlgenerator")
public String generateScript(@ModelAttribute("page") Page page) {
page.tables.forEach((t) ->{
System.out.println(t.getName());
t.getColumns().forEach((c) -> {
System.out.println(c.getName());
System.out.println(c.getType());
System.out.println(c.getIndex());
System.out.println(c.getNotnull());
});
});
}
For the JS part I was using some codes to implement the addRow() method which will add more Columns to the Table and addTable() method that would add another Table object, but nothing was working for my case
This is my view is looking like:
*PLEASE CAN ANYONE HELP ME TO SOLVE THAT .. I REALLY NEED IT .... *
解决方案
Your approach is okay. But you need to fix a few things.
In the getTable method, you are setting empty lists for tables and columns. So there is nothing to iterate over in the view layer to show the form. Change to:
@ModelAttribute("page")
public Page getTable() {
Column column = new Column();
List<Column> columns = new ArrayList<>();
columns.add(column);
Table table = new Table();
table.setColumns(columns);
List<Table> tables = new ArrayList<>();
tables.add(table);
Page page = new Page();
page.setTables(tables);
return page;
}
And
Add missing } for th:field="*{tables[__${i.index}__].name" and close this input tag.
NOTE:
I am not sure how you wanted to handle the three select inputs. I tested omitting them, meaning, keeping only Columnid and name in the form, data bind without any issue in that case.
Also I didn't check your JS, as you have mentioned that you haven't tested it yet.
Suggestions:
I see you are returning a view name from your POST handler. Take a look at the following article on Wikipedia.