Search code examples
jspstruts2ognlstruts-tags

Struts2 textfield dynamic key attribute


i am trying to refactor my code and i am searching for a possibility to set the key attribute of a <s:textfield> dynamically.

So my code looks like this:

<s:set name="type" value="%{process.commands[%{#counter}].type}"/>
<s:if test="%{#type.getLabel() == 'Start'}">
    <s:textfield name="process.commands[%{#counter}].statement" 
                  key="lbl.commandType.start"/>
</s:if>
<s:if test="%{#type.getLabel() == 'Stop'}">
    <s:textfield name="process.commands[%{#counter}].statement" 
                  key="lbl.commandType.stop"/>
</s:if>
<s:if test="%{#type.getLabel() == 'Check'}">
    <s:textfield name="process.commands[%{#counter}].statement" 
                  key="lbl.commandType.check"/>
</s:if>  

but what I actually looking for is something like this so it will be in one line:

key="lbl.commandType.'%{#type.getLabel()}'"

or

key="lbl.commandType.<s:property value='#type.getLabel()'/>"/>

but none of this works and I didn't found anything about a dynamic key attribute. Do anyone know a solution ?


Solution

  • If you want to get the field label from i18n resources then use the label attribute and getText method to actually retrieve value from resources.

    <s:textfield name="process.commands[%{#counter}].statement" 
                 label="%{getText('lbl.commandType.' + #type.getLabel())}" />
    

    Or using <s:text> instead of getText.

    <s:text var="labelText" name="%{'lbl.commandType.' + #type.getLabel()}" />
    
    <s:textfield name="process.commands[%{#counter}].statement" label="%{#labelText}" />
    

    Note that if you have property label in your type with proper getter and setter then you can use #type.label instead of #type.getLabel().