gospodin
gospodin

Reputation: 1211

preselected option in struts2 (freemarker)

I cannot make my freemarker struts2 select tag to show the default value for the object related list of options.

In my action I have:

private List<CodeLabel> modifRoomTypeOpt; 

inside I have objects CodeLabel with values like S:Single, D:Double,...

<@s.select id="123123"
  name="roomModif[2].type"
  value="${modifiedRoom.type}"
  list="modifRoomTypeOpt" listKey="code" listValue="label"/>

In the generated html, i can see options with values S,D,T,... and labels Single, Double,... so iteration over my CodeLabel object was done. But in my select, 1st option is always preselected. I checked value of ${modifiedRoom.type} and its 'D'. Why option with value D is not preselected?

Upvotes: 0

Views: 844

Answers (2)

fustaki
fustaki

Reputation: 1614

Interesting,

I did a bit of investigation and code-debugging and I discovered that the value attribute is evaluated as an OGNL variable. It means that Struts2 looks into the stack for a variable matching the string you put in the value attribute.

Internally the evaluated result then is put into the list of attributes as nameValue.

So I surprisingly found that using the attribute nameValue instead of value is a good workaround to have a select element preselected with a given value.

In your case:

<@s.select id="123123"
name="roomModif[2].type"
nameValue="${modifiedRoom.type}"
list="modifRoomTypeOpt" listKey="code" listValue="label"/>

or also:

<@s.select id="123123"
name="roomModif[2].type"
nameValue=modifiedRoom.type
list="modifRoomTypeOpt" listKey="code" listValue="label"/>

Upvotes: 1

B10Ha2ard
B10Ha2ard

Reputation: 1

To set the default value you need to set the value attribute of the select tag for instance:

<@s.select id="123123"
name="roomModif[2].type"
value="${modifiedRoom.type}"
list="modifRoomTypeOpt" listKey="code" listValue="label"
value="modifRoomTypeOpt.get(1)"   />

The code has not been tested, but I believe it should work. For reference use http://struts.apache.org/2.0.12/docs/select.html

If you want to set a default header on the select element use the headerKey and headerValue attributes.

Upvotes: 0

Related Questions