Hi everyone.
I have been posting to the user list for some time now regarding creating
indexed names within an iterate tag. From feedback from that list, this seems
to be an important addition to the current tags.
While looking to write my own additional tags which would do this (eg
html:indexedText etc), I discovered that this functionality could easily be
added to the current tags, now that the getIndex() method is available, by
creating an extra parameter 'indexed' which when set to true would create the
indexed names. The necessary additions to current code were small and quite
clean, as follows:
- added 'indexed' as a parameter in BaseHandlerTag, with appropriate
setter/getter
- added if statement which checks for 'indexed=true', and if so, appends "[x]"
to the name, before appending property eg myProperty[x].value.
This was added to BaseFieldTag (to cover tags which extend this) and
CheckBoxTag, & SelectTag
as follows:
//if "indexed=true" parameter, create indexed name for this tag eg
name="myCollection[x].myproperty"
if ("true".equals(indexed))
{
// look for outer iterate tag
IterateTag iterateTag = (IterateTag) findAncestorWithClass(this,
IterateTag.class);
if (iterateTag == null)
{
// this tag should only be nested in iteratetag, if it's not, don't do
anything
return EVAL_PAGE;
}
results.append(getName());
results.append("[");
results.append(iterateTag.getIndex());
results.append("].");
}
- Slight variations were added to SubmitTag and ButtonTag to simply add index to
it's name ie mySubmit[x].
- linkTag was somewhat different due to its nature. I added if statement to add
"index=x" as a parameter to the link's querystring ie myAction.do?index=1 or
myAction.do?param1=37&index=1, as follows:
//if "indexed=true", add "index=x" parameter to query string
if ("true".equals(indexed))
{
// look for outer iterate tag
IterateTag iterateTag = (IterateTag) findAncestorWithClass(this,
IterateTag.class);
if (iterateTag == null)
{
// this tag should only be nested in iteratetag, if it's not,
don't do anything
System.out.println("couldn't find enclosing iterate tag");
return EVAL_PAGE;
}
//calculate index, and add as a parameter
if (params == null)
{
params = new HashMap(); //create new HashMap if no
other params
}
params.put("index", "" + iterateTag.getIndex());
}
- minimal changes to struts-html.tld to add 'indexed' as param.
All of this code has been available at Ted's site for a while, and I would like
to suggest it is added to the Struts source. Numerous people are already using
it, and I believe many more would if it was part of the build.
Would appreciate your feedback, and not sure what happens next (just joined this
list)!
Cheers,
Dave
PS code attached(See attached file: struts indexed files.ZIP)
.ZIP File