I submit this data to add a Child entity via Ajax (POST):
(See the bottom of this question for entity classes definition)
name = "Child Name"
parent.id = 3
Everything is OK. The new Child entity is saved successfully.
But If don't include the parent.id
(only name
is set) (submitted using POST method)
name = "Child Name"
The validation result return this JSON:
"errors":{"parent":"may not be null"}
Note the "parent"
property in that JSON. It's supposed to return parent.id
not parent
.
It causes problem as the field on client-side script (HTML) has the name "parent.id"
not "parent"
.
Any suggestion How to return parent.id
instead of parent
??
Here is the handler method:
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Map<String, ?> add(@Valid Child child, BindingResult result) {
Map<String, ?> out = new LinkedHashMap<String, ?>();
if(result.hasErrors()){
Map<String, String> errors = new LinkedHashMap<String, String>();
for (FieldError error : result.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
out.put("success", false);
out.put("errors", errors);
return out;
} else {
out.put("success", true);
}
return out;
}
And here are the entity classes:
class Child {
private int id;
@NotNull
@Size(min = 5)
private String name;
@NotNull
private Parent parent;
//getter and setter methods
}
class Parent {
private int id;
@NotNull
private String name;
//getter and setter methods
}
Thank you.