I am currently working on a Grails application and I am looking place a select list on the page and have its Key set to one value and the Value set to another. The code of all related elements is below:
Domain Object:
class Cars {
String carType
String car
}
Controller:
def create() {
List cars = Cars.list()
[dealerInstance: new Dealer(params), cars: cars]
render(text:"This site in curently under Maintainence!")
}
View:
<g:select name="cars.id" from="${cars}" optionKey="${carType}" optionValue="${car}"/>
Now when I run this code the list does get populated however data looks like below:
<select id="cars.id" name="cars.id">
<option value="com.app.Cars : 1">com.app.Cars : 1</option>
<option value="com.app.Cars : 2">com.app.Cars : 2</option>
<option value="com.app.Cars : 3">com.app.Cars : 3</option>
</select>
and then when I try this:
View:
<g:select name="cars.id" from="${cars.car}" optionKey="${carType}" optionValue="${car}"/>
I get the following:
<select id="cars.id" name="cars.id">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Scoda">Scoda</option>
</select>
This is not what I want at all I want to be able to set a different Key Value pair on this select list so that I can use that data within my application, I would want the following to be generated:
<select id="cars.id" name="cars.id">
<option value="Saloon">Audi</option>
<option value="Hatch Back">BMW</option>
<option value="Estate">Scoda</option>
</select>
Can someone please tell me how I achieve this within Grails???
Try this:
<g:select id="cars.id" name="cars.id" from="${cars}" optionKey="carType" optionValue="car"/>
What basically happens:
When you use the from attribute, the tag iterates over the list you passed as an argument. optionKey and optionValue should be strings representing the attributes you want to access in the current object (being accessed by the iterator).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With