开发者

Spring form:options title from String

开发者 https://www.devze.com 2023-03-14 20:37 出处:网络
Pretty simple question. If I have a list of strings, which I render in a dropdown through Springs form:options tag, how do I set the value of the title property to be the strings value?

Pretty simple question. If I have a list of strings, which I render in a dropdown through Springs form:options tag, how do I set the value of the title property to be the strings value?

<form:options items="${listOfString}" title=" ?? "/>

Alternatively I would do a forEach, but can it be done with a form:options tag?

Thank开发者_StackOverflow社区s!


You just omit the 'title' attribute:

<form:options items="${listOfString}"/>


I'm assuming you mean that there are the itemLabel and itemValue params and that you would also like to have an itemTitle param so you can specify the field name on the object that contains the string to become a title="" attribute.

So relating to this issue: https://jira.springsource.org/browse/SPR-7648

If that's the case, I found that I had to roll my own solution. Here's the .tag file that I wrote to do it:

<%@ tag language="java" pageEncoding="ISO-8859-1"%>
<%@ attribute name="items" type="java.util.Collection" required="true" %>
<%@ attribute name="itemLabel" type="java.lang.String" required="true" %>
<%@ attribute name="itemValue" type="java.lang.String" required="true" %>
<%@ attribute name="itemTitle" type="java.lang.String" required="true" %>
<%@ attribute name="selectedValue" type="java.lang.String" required="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach var="entry" items="${items}">
    <c:set var="selectedAttrString" value="${entry[itemValue] == selectedValue ? 'selected=\"selected\"' : ''}" />
    <option value="${entry[itemValue]}" label="${entry[itemLabel]}" title="${entry[itemTitle]}" ${selectedAttrString} />
</c:forEach>

I've also included capability to set the selected item. I've left out the htmlEscape and css related params because I didn't require them but you could easily add them if required.

Note: the cool part is that SPeL lets you address a field name using a string (much like Javascript) so if we assume itemValue = "id" then entry[itemValue] evaluates to entry.id. Neat hey?

You can find the code behind the form:options tag here btw: https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/OptionsTag.java

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号