Search code examples
grailsmodel-view-controllergrails-orm

How can I return the property of a domain object in a Grails search?


I am writing my own search for a rather small project. The search page consists of g:selects populated by domain object fields like so:

<g:form action="list" method="GET">
Last Name <g:select id="lastName" name="searchedLName" from="${StudentEntry.list(sort:lastName, order:desc)}"
        noSelection="['null':'None']" optionValue="lastName" value="${params.searchedLName}"/><br/> 
Submitted By <g:select id="submitter" name="searchedSubmitter" from="${UserAuth.list(sort:userName, order:desc)}"
        noSelection="['null':'None']" optionValue="userName" value="${params.searchedSubmitter}"/><br/>
<button id="submitIt" type="submit">Search</button>

Here is a snippet of the domain object

class StudentEntry {
     String firstName
     String lastName
     String submittedBy

String toString() {
    lastName + ", " + firstName
}

Here is some bootstrap data

def entry1 = new StudentEntry {
     firstName: "John"
     lastName: "Smith"
     submittedBy: "Jane Doe"
}

def entry2 = new StudentEntry {
     firstName: "James"
     lastName: "Jones"
     submittedBy: "Jane Doe"
}

Here is the code for list from the StudentEntryController

def list(params) {
    def result

    println "Searched Last Name: " + params?.searchedLName
    def theLastName = params?.searchedLName
    println "Searched Last Name: " + theLastName

    println "Searched Submitter: " + params?.searchedSubmitter
    def theSubmitter = params?.searchedSubmitter
    println "Searched Submitter: " + theSubmitter

    if(params) {
       result = StudentEntry.findAllWhere(lastName: theLastName, submitter: theSubmitter)
//render...

When I run the search, the println statements are outputting the toString method of the StudentEntry class of the domain object associated with the selected value. For example, if I search for lastName="Jones", the println will output Searched Last Name: Jones, James. My render method returns an empty list when I want to see the entry of James Jones.

What is the correct way to pass the property of the object instead of the object itself to the findAllWhere method?


Solution

  • It appears that I neglected to specify the field that I want to search on as the optionKeyattribute in the g:select. The println statements are now outputting the desired data.