peech peech - 29 days ago 8
Java Question

Weird results of form:option in form:select

I am trying to preselect some values from a

form:select
tag. So, let's take a look at my sample class below:

public class Post
{
private boolean anonymize;
private boolean videoRequired;

/* getters, setters */
}


As you can see, there are two boolean fields. I'm using the first one in JSP like this:

<label>Anonymize</label>
<form:select path="anonymize" id="anonymize" class="form-control">
<form:option value="true" label="Yes" selected="${ (post.anonymize) ? true : ''}" />
<form:option value="false" label="No" selected="${ (!post.anonymize) ? true : ''}" />
</form:select>


which, when I inspect that element, results in (let's say that
anonymize
is
true
):

<select id="anonymize" name="anonymize" class="form-control">
<option selected="true" value="true">Yes</option>
<option value="false">No</option>
</select>


So far so good.

Now I do the EXACT same thing with my other boolean field
videoRequired
. First the JSP:

<label>Video required</label>
<form:select path="videoRequired" id="videoRequired" class="form-control">
<form:option value="true" label="Yes" selected="${ (post.videoRequired) ? true : '' }" />
<form:option value="false" label="No" selected="${ (!post.videoRequired) ? true : '' }" />
</form:select>


Which, results in (again, let's say that
videoRequired
is also
true
):

<label>Video required</label>
<select id="videoRequired" name="videoRequired" class="form-control">
<option selected="true" value="true">Yes</option>
<option value="false" selected="selected">No</option>
</select>


Take a look at this line:
<option value="false" selected="selected">No</option>


How can this even happen? I'm stuck with this for a few hours now, I have even tried with
<c:choose>
tag and then hardcoding the
selected
attribute - it gave me the exact same weird result. Can anyone please explain where have I gone wrong? I'm pulling my brains out since I'm doing the same thing on both fields, but still one works, the other one doesn't. Btw, when I take a look at mysql, both fields are properly set.

Answer

In order to pre-select a form:select element, you can set the corresponding variable anonymize to true in your controller method that returns your view.

@Controller
public String getForm(ModelMap model, Post post){
    post.setVideoRequired(true);
    return "view-name";
}
Comments