how can I read values from groovy g:select in my controller - grails

I have several g:selects in my gsp that I want to use for filtering a query. How can I access their values in the controller? Here is a select that I have:
<td><g:select name="accts" from="${accountSelection}"/></td>
Here is how I populate the list
def filter() {
def allaccts = getAccountSelection()
[accountInstanceList:allaccts.accountInstanceList]
}
def getAccountSelection() {
params.max = 10
def accts = []
accts.add("all")
Account.list().each { item -> accts.add(item) }
[accountInstanceList: accts, accountInstanceTotal: Account.count()]
}

In your controller it's just another parameter. You can access it like this:
params?.accts?.each {
println it
}

Related

How to compare collection item using createCriteria?

Registration domain has a collection of discounts.
static hasMany = [ discounts: Discount]
I want to extract all Registrations that have a particular discount applied.
In the following code i want to get all registrations whose collection has the discount of id disid. How can i achieve that? I appreciate any help!
def disid = Discount.get(1).id
def regs = Registration.createCriteria().list(){
eq('compositeEvent', cod.compositeEvent)
}
Try this:
def disid = Discount.get(1).id
def regs = Registration.withCriteria() {
discounts {
eq 'id', disid
}
}
See http://emmanuelrosa.com/articles/gorm-for-sqladdicts-where-clause/

why is groovy skipping the each statement

I have the following controller action in grails to determine if an item is in my shopping cart
def itemInCart(){
def cartHasItem = false
def product = Product.findOrCreateByPartNumberAndColor(params.partNumber, params.color)
def cart = shoppingCartItems()
cart.each() { item ->
if (item['partInfo']['partNumber'] == params.partNumber && item['partInfo']['color']==params.color){
cartHasItem = true
}
}
render(cartHasItem)
}
I added an item to the cart
cart at the time of cart.each() is
[{partInfo={partNumber=69874, color=BLACK}, qty=1, price=16.99}]
params.partNumber = 69874
params.color = BLACK
The issue is that my code is completely skipping over the each() block. debug hits cart.each() { item -> and then goes streight to render
Looks like you want to use any instead of each here:
def cartHasItem = cart.any{ item ->
item['partInfo']['partNumber'] == params.partNumber && item['partInfo']['color']==params.color
}
I wanted to expand on #Dónal's comment on the question, to find out why each() vs each is different.
I've never used object.each() {}, instead I always use this form:
cart.each { item ->
// do work
}
However, I couldn't actually get each() to fail in this simple test:
def myfn() {
def items = [1,2,3]
def ret = false
items.each() {item -> if (item == 2) { ret = true }}
return ret
}
myfn()
==> true
I tried a more complicated version using a map to represent the data you are using, and a simple version just using
[[a:1, b:2, c:3]].each() { println it }
which always renders the item.
What version of groovy are you using?
I'm assuming your data is actually a list of maps here, your syntax for the item was more clojure, than groovy.

Grails Criteria querying a list with ilike

I want to query a list in criteria like this:
def patterns = ["abc%", "cde%"]
def criteria = MyEntity.createCriteria();
def results = criteria.list {
and {
patterns.collect {
not { ilike(name, it) }
}
}
is this basically possible? What do I have to do to get this query working?
Instead of collecting which will create a collection of the contents you need to simply iterate.
def patterns = ["abc%", "cde%"]
def criteria = MyEntity.createCriteria();
def results = criteria.list {
and {
patterns.each {
not { ilike('name', it) }
}
}

Grails CRUD list order by a field

I have a domain class Project as below
class Project {
String projectName
String projectCode
String techLead
String projectManager
Date deliveryDate
String currentPhase
Integer priority
}
I have controller as below
class ProjectController {
def scaffold = Project
def index = {
redirect(action:list,params:params)
}
def list = {
// displays only 10 records per page
if (!params.max) params.max = 10
[ projectList: Project.list( params ) ]
}
}
I would like to display the list of projects in the sorting order or priority. How can I implement that ?
change your list action to the below
def list = {
// displays only 10 records per page
if (!params.max) {
params.max = 10
}
params.sort = "priority"
params.order = "asc" // change to "desc" to sort in the opposite direction
[projectList: Project.list(params)]
}
A much shorter and more idiomatic way of doing this would be to use the dynamic methods on list that provide ordering:
def list = {
[projectList: Project.listOrderByPriority(max: params.max ?: 10)]
}

How to sort Domain-Objects with attribute with type JodaTime / DateTime in grails 1.3.7?

I'm working on a small event calendar and i want to sort the events by start time!
I'm using JodaTime Plugin in grails for the startTime attribute. ( http://www.grails.org/JodaTime+Plugin )
So, how can i sort with this datatype? This does not work:
def sortedEvents = events.asList().sort({ a, b -> a.startTime <=> b.startTime } as Comparator)
I hope you can help me!
Thanks,
whitenexx
/EDIT/
This is the code where i'm getting the events:
def getEventsNext(Location location) {
def events = location.events.findAll { it.endTime >= new DateTime() }
def sortedEvents = events.sort{it.startTime}
System.out.println(sortedEvents); //test
return sortedEvents
}
In /event/list action everything works fine with g:sortableColumn (sorting by startTime):
Try this:
def sortedEvents = events.asList().sort{it.startTime}
To reverse the sorting order, use:
def sortedEvents = events.asList().sort{-it.startTime}
FYI, Groovy adds this sort() method to Collection so you can remove asList() from the code above if events is already a Collection.
Try overriding the compareTo method in your domain classes.
For example,
int compareTo(obj) {
startTime.compareTo(obj.startTime)
}
Edit
Sort your events like so:
def sortedEvents = events.sort{e1,e2-> e1.startTime.compareTo(2.startTime)}
Or as suggested by #Don, the groovier equivalent
def sortedEvents = events.sort{e1,e2-> e1.startTime <=> e2.startTime}
Try
def events = location.events.findAll { it.endTime.isAfterNow() }
def sortedEvents = events.sort{it.startTime.toDate()}
JavaDoc for isAfterNow()

Resources