You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by Andrew Boyko <ab...@fabgear.com> on 2000/12/08 04:26:22 UTC

PATCH: allow java.util.Map in form:options

>   Add a new mechanism for specifying labels and values in the
> <form:options>
>   tag.  You can now specify a collection of beans, along with the property
>   names to be used to extract a label and value from each bean.
> The example
>   application has been modified to use this new approach.
>
>   Previous approaches of specifying parallel collections will continue to
>   work, because that approach is more appropriate in application
>   environments.

I had submitted a small patch to OptionsTag earlier, that
allowed a java.util.Map to be correctly iterated over to supply
labels and values to <form:options>. I *think* this new scheme
renders that patch obsolete, in that if the Map is supplied as
the collection and getKey() and getValue() are indicated as the
properties of the Map.Entry to be examined, then it does the
right thing, albeit more verbosely than being able to just say:
    <form:options name="someMapVar" />

Since the tag's javadoc alludes to that capability, and the
getIterator() call goes to the trouble to identify the
collection as a Map, it only takes a small change to
add that feature; the current version of my earlier patch
follows.  Robert Leland pointed out that the instanceof
call could be optimized out if we identify the propertied
collection as a Map in getIterator(), but that's not done
here, in the interest of minimizing change.

Andy Boyko   aboyko@fabgear.com

RCS file:
/home/cvspublic/jakarta-struts/src/share/org/apache/struts/taglib/form/Optio
nsTag.java,v
retrieving revision 1.4
diff -u -r1.4 OptionsTag.java
--- OptionsTag.java     2000/12/08 02:42:31     1.4
+++ OptionsTag.java     2000/12/08 03:14:11
@@ -236,10 +236,20 @@

               // Render the options tags for each element of the values
coll.
               while (valuesIterator.hasNext()) {
-                  String value = (String) valuesIterator.next();
-                  String label = value;
-                  if (labelsIterator.hasNext())
-                      label = (String) labelsIterator.next();
+
+                  Object next = valuesIterator.next();
+
+                  String label, value;
+                  if ( next instanceof Map.Entry ) {
+                      Map.Entry entry = (Map.Entry) next;
+                      value = (String) entry.getKey();
+                      label = (String) entry.getValue();
+                  } else {
+                     value = (String) next;
+                     label = value;
+                     if (labelsIterator.hasNext())
+                         label = (String) labelsIterator.next();
+                  }
                   addOption(sb, value, label, match);
               }
        }