views:

195

answers:

1

I have a g:select in my view that displays a list of products:

<g:form name="addproductform" action="saveProductToInventory" method="post">
    <g:select from="${products}" name="product" value="${it?.id}" />
    <g:hiddenField name="inventory.id" value="${inventoryInstance.id}" />
    <input class="save" type="submit" value="Save product" />
</g:form>

${products} is a list of all products. If I print the params variable that is passed to the controller, I get this:

[product:Test Product, inventory:[id:1], inventory.id:1, action:saveProductToInventory, controller:inventory]

The product key contains the name, and not the ID which I thought it would contain when I added value="${it?.id}" to the g:select tag.

How do I need to declare the g:select tag to render the product's name as it is right now, but pass the product's id as value?

+1  A: 

You need to use the optionKey argument to the tag.

e.g.

<g:select from="${products}" name="product" value="${it?.id}" optionKey="id" />

The value arg is used to select the current value of the field.

leebutts
Tried it, and it works. Thanks! But before that I tried with optionKey="${it?.id}" and it gave me the same results as before. I'm not sure I understand how the g:select knows to get the id from each product, instead of trying to get the id from the list itself.
Cesar
g:select is calling it.<optionKey> for you on each row to generate the value of the select option.
leebutts