class Person { String firstName String lastName int age }And this inserted data:
class BootStrap { def init = { servletContext -> if (Person.count()==0) { new Person(firstName: 'John', lastName: 'Doe', age: 10).save() new Person(firstName: 'Jane', lastName: 'Doe', age: 10).save() new Person(firstName: 'Jesse', lastName: 'Doe', age: 10).save() new Person(firstName: 'Rex', lastName: 'Smith', age: 12).save() new Person(firstName: 'Roy', lastName: 'Smith', age: 12).save() new Person(firstName: 'Amy', lastName: 'Johnson', age: 8).save() } } }
And this controller code that returns all records in the Person domain class:
class PersonController { def list() { [people:Person.listOrderByLastName()] } }
By default, in and expr attributes are required when using Grails findAll tag.
<g:findAll in="${people}" expr="true"> <p>${it.lastName}, ${it.firstName}</p> </g:findAll>Since the expr is always evaluated to true, this will in fact render the body over all the items of the list. The output will be this:
Doe, John Doe, Jane Doe, Jesse Johnson, Amy Smith, Rex Smith, Roy
We can change the expr to something meaningful for our Grails findAll tag code to process:
<g:findAll in="${people}" expr="it.lastName == 'Doe'"> <p>${it.lastName}, ${it.firstName}</p> </g:findAll>This will only execute the body when lastName is Doe. Hence, this is the expected result:
Doe, John Doe, Jane Doe, Jesse
Here is another sample that only process records for people who has age greater than 10.
<g:findAll in="${people}" expr=" ${it.age > 10} "> <p>${it.lastName}, ${it.firstName}</p> </g:findAll>Notice that we can enclose our expression inside ${}. Here is the expected output:
Smith, Rex Smith, Roy
<g:findAll in="${people}" expr="${it.age == 10}" var="person"> <p>${person.lastName}, ${person.firstName}</p> </g:findAll>
The code will display these records:
Doe, John Doe, Jane Doe, JesseSpecifying the var attribute makes the Grails findAll tag code easy to read at quick glance because of the logical variable name.
<g:findAll in="${people}" expr="${it.age == 10}" var="person" status="ctr"> <p>${ctr+1}. ${person.lastName}, ${person.firstName}</p> </g:findAll>
The code will display this output. As you can see, the index is zero-based - meaning it will start from the value 0. Hence we add 1 to the number before rendering:
1. Doe, John 2. Doe, Jane 3. Doe, Jesse