meoww-
meoww-

Reputation: 1892

Grails populate g:select from database

I ran into an issue while populating domain object values on a gsp page by using a g:select tag.

<g:select name="demo" id="demo"
          value="${dm.id}"
          noSelection="${['null':'Select..']}"
          from="${dm}"
          optionValue="${dm.type}"/>

In my controller, I have an object which gathers values from my domain. I tried writing this object in the controller both as:

 def d = Demo.getAll()

and def d = Demo.list()

Both of these returned an exception while trying to use the g:select tag. The error was:

No signature of method: Demo.getAt() is applicable for argument types: (java.util.ArrayList) values: [[One, Two, Three, Four, Five]]

I was able to get my code working by simply removing the g:select tag and writing the following in my gsp:

    <select name="demo" id="dm">
    <option value="">Select!</option>
    <g:each in="${dm}" status="i" var="dm">
        <option value="${dm.id}">${dm.name}</option>
    </g:each>
</select>

However, I would like to know how to make this work with the g:select tag, for my future reference.

Thanks in advance!

Upvotes: 0

Views: 3719

Answers (1)

Gregg
Gregg

Reputation: 35864

I see two issues in your select:

<g:select name="demo" id="demo"
          value="${dm.id}"
          noSelection="${['null':'Select..']}"
          from="${dm}"
          optionValue="${dm.type}"/>
  1. value shouldn't be looking at the collection for the id. I believe this is why you are getting your error. value should be whatever instance's id you've passed into your view.
  2. optionValue doesn't required an expression.

Controller action

def someAction() {
   def dm = Demo.get(params.id)
   def demos = Demo.list()
   [dm: dm, demos: demos]
}

view

<g:select name="demo" id="demo"
          value="${dm.id}"
          noSelection="${['null':'Select..']}"
          from="${demos}"
          optionValue="type"/>

Upvotes: 3

Related Questions