5

I'm creating a form in which user will be able to choose (among the others) the factory of a product.

Each factory is identified by and ID and has specific address.

I want to use custom label in following code:

<form:select items="${factories}" path="factory" itemValue="id" itemLabel="..."/>

At first i tried using Spring Formatter functionality (org.springframework.format.Formatter interface), but when I did this, and when I removed "itemLabel" attribute to have it displayed automatically via Formatter):

<form:select items="${factories}" path="factory" itemValue="id"/>

But then It wasn't selecting proper value if it was set (in case of editing).

Then I tried to:

<form:select path="factory" itemValue="id">
    <c:forEach ...>
         <form:option value="${factory.id}" label="${factory.address.city} ${factory.address.street}"
    </c:foreach>
</form:select>

But as in earlier solution spring was not selecting proper value that was set in model.

My question is:

Is it possible to format entity in a way, that form:select works properly, when a value of select field is not the same as its label.

2 Answers 2

7

I had the same problem, the trouble is the form:option value and label maps directly to a property rather than having the flexibility to specify jstl.

So you have to hand crank the html, to something like:

<select name="factory">
    <c:forEach var="factory" items="${factories}" >
        <option value="${factory.id}" label="${factory.address.city} ${factory.address.street}"/>
    </c:forEach>
</select>

Spring will pick up the 'path' based on the name attribute('factory' in this case), as it will try and map to the model object you are using automatically.

Another way is to add another field to the model to concatenate and format label as you wish. And if its an @Entity object then make the field @Transient.

-1

You can also override toString() method in Factory class

 @Override
    public String toString() {
        return "desired string"; 
}

Then in your jsp

<form:select items="${factories}" itemValue="id" path="factory"/>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.