Grails: Sorting Nested Domain Objects - sorting

I've got a one to many relationship in.
I have an Application which has multiple files which can be uploaded into it. The Application view contains the Uploaded file list (the files in the list just contain meta data about the file such as file name, file size etc.). I am having trouble with the ability to sort the nested list.
I am using the sortableColumn to call a sort action in my controller.
How can I retrieve an application and specify that the nested list of uploaded files be sorted by the requested attribute (ex. File Name, File Size etc.)
EDIT:
here are some snippets:
Here is the Application Domain Object
class Application implements Serializable {
private static final long serialVersionUID = 1
Firm firm
static hasMany = [applicationDocumentHolders:ApplicationDocumentHolder]
static belongsTo = [firm:Firm]
static mapping = {firm lazy: false}
}
And here is the Application Document Holder (I am storing the actual documents in MongoDB and the meta data in SQLServer in an applicationDocumentHolder object, so for the sake of simplicity I am leaving out the document file as it does not pertain to this question)
import java.sql.Time
class ApplicationDocumentHolder implements Serializable {
private static final long serialVersionUID = 1
static belongsTo = [application:Application]
static mapping = {application lazy: false}
Application application
ApplicationDocumentType type
ApplicationDocumentStatus status
Date verfiedDate
Long uploadFileId
//Following fields will be null until a file is uploaded
String fileName
Date uploadDate
String uploadUserId
long fileSize
static constraints = {
type blank: false
status blank: false
verfiedDate nullable: true
uploadFileId nullable: true
uploadFile nullable: true
fileName nullable: true
uploadDate nullable: true
uploadUserId nullable: true
fileSize nullable: true
}
}
Here is a snippet from the GSP where I am using the sortableColumn tag to call the sort action in my controller
<g:sortableColumn action="sort" property="type" title="${message(code: 'applicationDocumentHolder.type.label', default: 'Type')}" />
<g:sortableColumn action="sort" property="status" title="${message(code: 'applicationDocumentHolder.status.label', default: 'Status')}" />
<g:sortableColumn action="sort" property="verfiedDate" title="${message(code: 'applicationDocumentHolder.verfiedDate.label', default: 'Verfied Date')}" />
<g:sortableColumn action="sort" property="fileName" title="${message(code: 'applicationDocumentHolder.uploadFileName.label', default: 'Upload File Name')}" />
I am wondering what the best way to do this is.
I can sort the collection of ApplicationDocumentHolders in the controller but I keep getting violations because these are attached objects to the DB.
I can also re-retrieve the list sorted but I am not sure how you specify that you want a dynamically sorted nested object when it is retrieved from the DB (I know there must be a simple way to do this but I am pretty new to grails).
I would like to know how to do it both way just for future reference.

You can create a simple Closure takes the attribute you want to sort by and the file. You can then Closure.curry(attributeName) that Closure to get a new Closure which sorts by that attribute. Then, pass the Closure to Collection.toSorted() to sort the list of files.
def files = [
[name: 'foo.txt', size: 10],
[name: 'bar.txt', size: 30],
[name: 'hello.txt', size: 20]
]
def sorter = { attr, file -> file[attr] }
files.toSorted sorter.curry('size') // sort by size
files.toSorted sorter.curry('name') // sort by name

Related

Validate nested domain class instance in command object

I try to validate a nested domain class instance on a command object.
Having the following command object
package demo
import grails.databinding.BindingFormat
class SaveEventCommand {
#BindingFormat('yyyy-MM-dd')
Date date
Refreshment refreshment
static constraints = {
date validator: { date -> date > new Date() + 3}
refreshment nullable: true
}
}
And having the following domain class with its own constraints
package demo
class Refreshment {
String food
String drink
Integer quantity
static constraints = {
food inList: ['food1', 'food2', 'food3']
drink nullable: true, inList: ['drink1', 'drink2', 'drink3']
quantity: min: 1
}
}
I need when refreshment is not nullable the command object validates the date property and check the corresponding restrictions in refreshment instance
For now try with this code in the controller:
def save(SaveEventCommand command) {
if (command.hasErrors() || !command.refreshment.validate()) {
respond ([errors: command.errors], view: 'create')
return
}
// Store logic goes here
}
Here through !command.refreshment.validate() I try to validate the refresh instance but I get the result that there are no errors, even when passing data that is not correct.
Thank you any guide and thank you for your time
I typically just include some code that will use a custom validator to kick off validation for any property that is composed of another command object. For example:
thePropertyInQuestion(nullable: true, validator: {val, obj, err ->
if (val == null) return
if (!val.validate()) {
val.errors.allErrors.each { e ->
err.rejectValue(
"thePropertyInQuestion.${e.arguments[0]}",
"${e.objectName}.${e.arguments[0]}.${e.code}",
e.arguments,
"${e.objectName}.${e.arguments[0]}.${e.code}"
)
}
}
})
This way it's pretty clear that I want validation to occur. Plus it moves all the errors up into the root errors collection which makes things super easy for me.
Two things I could think of:
Implement grails.validation.Validateable on your command object
What happens when you provide an invalid date? Can you see errors while validating?

Grails validation on an associated 'hasMany' object

I'm having a validation issue very similar to what is described here
https://schneide.wordpress.com/2010/09/20/gorm-gotchas-validation-and-hasmany/
but with an important difference that I don't have (or want) a List<Element> elements field in my domain. My code is
class Location {
static hasMany = [pocs: LocationPoc]
Integer id
String address
String city
State state
String zip
...
static mapping = {
...
}
static constraints = {
def regEx = new RegEx()
address blank: true, nullable: true, matches: regEx.VALID_ADDRESS_REGEX
city blank: true, nullable: true
state blank: true, nullable: true
zip blank: true, nullable: true
...
}
}
however, if I save/update a location with a bunk POC (point of contact), I get some wild errors. I would like to validate the POC's when I save/update a location, but I'm not exactly sure how. I've tried a few variations of
pocs validator: {
obj -> obj?.pocs?.each {
if (!it.validate()) {
return false
}
}
return true
}
to no avail. Is this possbile without creating a new field on my domain, List<LocationPoc> pocs?
You're close. The issue is you need to target the property you want to validate instead of using the object reference. It should look like this:
pocs validator: { val, obj, err ->
val?.each {
if (!it.validate()) return false
}
}
Validation doesn't automatically cascade through hasMany associations. In order to get free validation, the other side of the relationship needs to belong to Location.
You didn't include your LocationPOC class, but if you modify
Location location
to
static belongsTo = [location: Location]
Then you will get cascading validation when you save your Location object.
If you can't set the belongsTo property on LocationPoc, and need to use the custom validator, the syntax is a bit different than the answer above.
pocs validator: {val, obj ->
val?.inject true, {acc,item -> acc && item.validate()}
}
the three arguement version of validate expects you to add errors to the errorCollection. https://grails.github.io/grails2-doc/2.5.6/ref/Constraints/validator.html
Plus using a return statement inside of .each doesn't work like the above example. It just exits the closure and starts the next iteration. The validator from the other answer was just returning val (the result of val.each is just val)
You need to spin through the entire collection looking for non valid options.

ajax dependency selection plugin

Based on a previous post and some suggestions received there I have modified my application to use the ajax dependency selection plugin for some chained select lists that I have.
The select lists are Consultant -> Contract -> Project
I have a create page and edit page for an evaluation that use the same form template. On the create page my chained selects are working correctly and saving to the database. However when I open up an existing evaluation only the select primary select box is populated. Do I need to do something special with this plugin to get the secondary select box values and lists populated as desired on the edit page?
Here is the code from my domain classes
Consultant domain class
class CdeConsultant {
String ccf_consultant_firm
static hasMany=[contracts:Contract]
static mapping = {
table name: 'cde_consultant'
version false
id column: 'ccf_consultant_id', generator: "assigned"
}
}
Here is the code for my contract domain class
class Contract {
String contractName
int conId
String phone
String projectManagerName
CdeConsultant cdeConsultant
static hasMany=[projectLists:ProjectList]
static mapping = {
table name: 'contract'
version false
id column: 'contracts_id', generator: "assigned"
}
}
Here is the code from my ProjectList domain class
class ProjectList {
String project
Contract contract
static mapping = {
table name: 'project_list'
version false
id column: 'dpp_project_phase_id', generator: "assigned"
contract column: 'contracts_id'
}
}
Here is my code for the evaluation class which is where these fields are being saved
import java.util.Date
class CdeEvaluation extends Base {
String consultant
String consultantName
String project
String projectManager
String projectManagerPhone
String evalStatus
String cdeComment
Date evalBeginDate
Date evalEndDate
String submitApproval
int workCategory
int contract
String contractName
List<CdeEvalQuestion> questions
static hasMany = [questions: CdeEvalQuestion]
static constraints = {
consultant(nullable:true)
consultantName(nullable:true)
project(nullable:true)
contract(nullable:true)
contractName(nullable:true)
projectManager(nullable:true)
projectManagerPhone(nullable:true)
evalStatus(nullable:true)
workCategory(nullable:true)
evalEndDate validator: {value, cdeEvaluation -> value >= cdeEvaluation.evalBeginDate}
cdeComment(nullable:true, maxSize:2000)
submitApproval(nullable:true)
evalBeginDate(blank: false, nullable:true)
evalEndDate(blank: false, nullable:true)
createdBy(blank: false, nullable:true, maxSize:13)
dateCreated(blank: false, nullable:true)
lastUpdatedBy(blank: false, nullable:true, maxSize:13)
lastUpdated(blank: false, nullable:true)
}
static mapping = {
table name: 'CDE_EVALUATION'
id column: 'ceval_id_seq'
id generator: 'sequence', params: [sequence: 'ceval_id_seq']
}
#Override
public String toString() {
"${project}"
}
class EvaluationController {
static scaffold=true
}
}
And finally here is the code for my form template that is used in both the create and edit pages.
<g:selectPrimary class="form-select-list" id="consultant" name="consultant" label="Consultant"
domain='gov.mt.mdt.cde.domain.evaluation.CdeConsultant'
searchField="ccf_consultant_firm"
collectField='id'
domain2='gov.mt.mdt.cde.domain.evaluation.Contract'
bindid="cdeConsultant.id"
searchField2='contractName'
collectField2='id'
noSelection="['': 'Select A Consultant']"
setId="contract"
value="${cdeEvaluationInstance?.consultant}"
appendValue=''
appendName='Select a Contract' />
<g:selectSecondary class="form-select-list" id="contract" name="contract"
domain2='gov.mt.mdt.cde.domain.evaluation.ProjectList'
bindid="contract.id"
searchField2='project'
collectField2='project'
noSelection="['': 'Select A Contract']"
setId="project"
appendValue=''
appendName='Select a Project'
value="${cdeEvaluationInstance?.contract}"
required="false"/>
<g:select class="form-control" name="project" id="project" optionKey="project" optionValue="project"
from="[]" noSelection="['': 'Select A Project']" value="${cdeEvaluationInstance?.project}" />
Sorry a little late to answer your question here, edit I don't think has much documentation :). Although current situation gives me ideas to expand on the plugin for sure...
The problem being the secondary selection is reliant on primary being selected, the selection on primary itself triggers the gathered list for secondary box to be populated. Since primary is already defined not selected - well there you see the issue.
Let me have a think, if you had raised it as issue/suggestion on github I would have got to it earlier.
UPDATE
Ok I have rolled out 0.40 which should hopefully address edit mode :
Please take a look at this page :
https://github.com/vahidhedayati/ajaxdependancyselectexample/blob/master/grails-app/views/myContinent/testedit.gsp
In theory assuming the hardcoded values are returned as dynamic variables from the db an additional definition is required per primary/secondary call:
so in the
value='4'
secondaryValue='10'
Value is its own value and secondaryValue is what you expect to set the next selectSecondary
Please note I had to also remove appendName and appendValue from selectPrimary/selectSecondary calls. I think there was some form of a conflict in the edit mode....
Anyhow that testedit appeared to be working.

Grails default nullable constraints

In my Grails app I have the following command object
#Validateable
class CalendarEventCommand {
#BindingFormat('FestivalType')
Collection<FestivalType> types
Date start
Date end
MapFocalPoint location
boolean freeOnly = false
}
which is used as the argument to a controller action
def getCalendarEvents(CalendarEventCommand calendarEventCommand) {
if (calendarEventCommand.validate()) {
log.error "Command errors $calendarEventCommand.errors"
} else {
log.warn "Everything is fine"
}
}
In Config.groovy I've specified the following as the default constraints
grails.gorm.default.constraints = {
// apply a max size of 191 chars to String columns to support utf8mb4
// http://mathiasbynens.be/notes/mysql-utf8mb4
'*'(maxSize: 191)
// this shared constraint provides a way to override the default above for long text properties
unlimitedSize(maxSize: Integer.MAX_VALUE)
}
If an instance is created with a null value for start and end validation passes, but I wouldn't expect it to because AFAIK a default constraint of nullable: false should be applied to all properties. I've tried adding this explicitly, by changing the first default constraint to
'*'(maxSize: 191, nullable: false)
But validate() still returns true when start and/or end are null. If I add these constraints to CalendarEventCommand
static constraints = {
start nullable: false
end nullable: false
}
then validate() returns false, but AFAIK it shouldn't be necessary for me to add these constraints.
I think this is an expected behavior. There are couple of JIRA defects regarding this functionality out of which GRAILS-7431 and GRAILS-8583 seems more focused towards the behavior.
I was going through DefaultConstraintEvaluator.java which takes care of global constraints only for domain classes. I think we have to end up using the way mentioned later.
static constraints = {
start nullable: false
end nullable: false
}

How do I sort by a property on a nullable association in Grails?

I'm trying to sort a table of data. I have the following domain (paraphrased and example-ified):
class Car {
Engine engine
static constraints = {
engine nullable: true // poor example, I know
}
}
class Engine {
String name
}
Here's the controller action that's handling the sort:
def myAction = {
def list = Car.findAll(params)
render(view: 'list', model: [list: list])
}
I provision some data such that there are several Cars, some with null engines and others with engines that are not null.
I attempt the following query:
http://www.example.com/myController/myAction?sort=engine.name&order=asc
The results from the query only return Car entries whose engine is not null. This is different from the results that would be returned if I only queried the association (without its property):
http://www.example.com/myController/myAction?sort=engine&order=asc
which would return all of the Car results, grouping the ones with null engines together.
Is there any way that:
I can get the query that sorts by the association property to return the same results as the one that sorts by only the association (with the null associations grouped together)?
I can achieve those results using the built-in sorting passed to list() (i.e. without using a Criteria or HQL query)
You need to specify LEFT_JOIN in the query, try this:
import org.hibernate.criterion.CriteriaSpecification
...
def list = Car.createCriteria().list ([max:params.max?:10, offset: params.offset?:0 ]){
if (params.sort == 'engine.name') {
createAlias("engine","e", CriteriaSpecification.LEFT_JOIN)
order( "e.name",params.order)
} else {
order(params.sort, params.order)
}
}
Remember to put engine.name as the property to order by in your list.gsp
<g:sortableColumn property="engine.name" title="Engine Name" />

Resources