Set Option Key and Value on Grails select list?
Asked Answered
C

1

5

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???

Chardin answered 6/11, 2012 at 15:26 Comment(0)
E
8

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).

Evensong answered 6/11, 2012 at 16:16 Comment(3)
Yup... optionKey and optionValue should both be strings.Derisive
How that worked :), however now I need to create a label that shows the KEY value of the selected item whenever the select list is changed, any ideas? I was thinking JavaScript?Chardin
Yeah, Javascript is your best choice I guess. New question though.Evensong

© 2022 - 2024 — McMap. All rights reserved.