Red Viper
Red Viper

Reputation: 507

Two sorting rules in Grails

With the following code:

<g:each in="${books.sort{it.date}}" status="i" var="book"> 
    ${book}
</g:each>

I want to display the books to be sorted by date; additionally, I want the books authored by the person currently logged in to show up first.

Is that possible?

Upvotes: 1

Views: 45

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

Not sure what you want to achieve but you can do this. Before passing your books list to your GSP, you can write like this:

def myAction() {
     List books = Book.list()  // Get your book list

     User loggedInUser = User.first()  // Get your currently logged in user

     // First get all the books of current user sorted by the date
     List currentUsersBooks = books.findAll { it.author.id == loggedInUser.id }.sort{ it.date }

     // Then get other books sorted by date
     List otherBooks = books.findAll { it.author.id != loggedInUser.id }.sort{ it.date }

     // Now merge all of them (as `List` will maintain insertion order)
     // So current user's book will be listed first and then others
     List allBooks = currentUsersBooks + otherBooks

     [books: allBooks]
}

Now, modify your GSP to do not sort again:

<g:each in="${books}" status="i" var="book"> 
   ${book}
</g:each>

Considering, the Book and User domain class like this:

class User {
     String email
}

class Book {
     Strig title
     User author
}

Upvotes: 1

Related Questions