2

I am sending list of grouped fields to Spring controller using Spring form tag. Some of these can be empty. For example

JSP Page has

<form:input path="id" size="30" value=""/>
<form:input path="name" size="30" value=""/>
<c:forEach var="i" begin="0" end="4">
  <form:input path="myLog[${i}].dateOfCall" size="10" value=""/
  <form:input path="myLog[${i}].activity" size="30" value=""/>
</c:forEach>

My Model fields looks like

Class MyModel {
  String name;
  String id;
  List<MyLog> myLog;
  public static class MyLog {
    String dateOfCall;
    String activity;
}

Now event when I don't filled any myLog I am getting all 5 myLog object with empty values.

So my question is there a way to make myLog size depending upon the number of log user input. For example if user input no log info its size should be 0.

1 Answer 1

1

From the JSP code you posted, I assume that it ends up getting rendered like this in the browser:

<input id="myLog[0].dateOfCall" name="myLog[0].dateOfCall" size="10" value="" />
<input id="myLog[0].activity" name="myLog[0].activity" size="30" value="" />
... 1, 2, 3 ...
<input id="myLog[4].dateOfCall" name="myLog[4].dateOfCall" size="10" value="" />
<input id="myLog[4].activity" name="myLog[4].activity" size="30" value="" />

For Spring Forms, this means, even if all of the input fields are left empty, that it should create five (empty) myLog objects.

If you want to work around this behavior, I'd suggest to create the input blocks only on demand (if the user really wants them to be created). You could achieve this i.e. with JavaScript; simply add an "Add log" button and on its click event, create a block

<input id="myLog[xxx].dateOfCall" name="myLog[xxx].dateOfCall" size="10" value=""/>
<input id="myLog[xxx].activity" name="myLog[xxx].activity" size="30" value=""/>

at the correct position inside the form.

Another possibility would be to validate the received myLog object(s), and if empty, either rejecting or silently discarding it.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any validation annotation to test empty myLog object? Or do I have to write my own custom validation for this?
Yes, in case you're using JPA and/or the validation API, the correct annotations would be @ Basic(optional = false) and/or @ NotNull resp. @ NotBlank for each of MyLogs properties. See either the JPA Annotation doc or javax.validation doc. Of course you can also implement your own validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.