Reputation: 2660
Is there a way to dynamically add an attribute to a struts 2, tag UI tag such as a textfield?
The reason is that I want to add a readOnly
form field attribute to an <s:textfield/>
, depending on an action's method result. I cannot use readOnly="%{isReadOnly()}"
since once the attribute is defined, the form element is read-only, no matter what value it has. And wrapping each form field into an <s:if/>
tag is pretty cumbersome and results in a lot of code duplication.
I would also like to avoid JavaScript for interoperability reasons and for not relying on the browser's scripting settings.
Upvotes: 3
Views: 3290
Reputation: 10458
If the issue is to use the built in struts2 functionality then one easy option is to render your view with freemarker, which readily supports the dynamic addition of attributes.
If you are using conventions, it is VERY trivial you just need to create a file with a ".ftl" extension, if you are using xml it is also very easy just use the freemarker result type (see here for greater description):
<action name="test" class="package.Test">
<result name="success" type="freemarker">/WEB-INF/content/testView.ftl</result>
</action>
Here is example view using a map to dynamically add attributes (example also taken from liked page):
<@s.textfield name="test" dynamicAttributes={"placeholder":"input","foo":"bar"}/>
The dynamicAttributes would be extremely useful in all JSP UI tags but alas it is not currently implemented.
NOTE: There is one error/omission in the above link. It tells you to add the following line which causes an error in my environment (simply the line is not needed).
<#assign s=JspTaglibs["/WEB-INF/struts.tld"] />
That is, this line in a file all by it self is sufficient for rendering a text element, no explicit tag library declaration needed!
<@s.textfield name="test" dynamicAttributes={"placeholder":"input","foo":"bar"}/>
There are a number of advantages to using freemarker over plain JSPs, so taking a moment to explore the syntax and using it for this one case may prove useful later.
Upvotes: 2