using Grails 2.43 currently. I have two domain classes (State and County), and two Select dropdowns for State and County.
Is there a way with a GORM finder to have a dynamic query that will return the specific counties in a state, when that state is selected. Thereby excluding all other counties that are not in the selected State?
Form elements:
<g:select name="locationState" class="form-control" from="${....State.list().sort{it.orderNumber}}">
<g:select name="locationCounty" class="form-control" from="${...State.FindByName(it.orderNumber).counties}">
Here are the example classes:
class State {
static hasMany = [county:County]
String name
String value
int orderNumber = 0
static constraints = {
name nullable:false, maxSize:50, blank:false
value nullable:false, maxSize:100, blank:false
}
String toString(){
"$value"
}
static mapping = {
table 'state'
cache: 'read-write'
columns{
id column:'id'
name column:'name'
value column:'value'
orderNumber column:'order_number'
}
id generator: 'assigned'
}
}
class County {
State state
String county
static constraints = {
state nullable:false
county nullable:false, maxSize:100, blank:false
}
String toString(){
"${state.name} - $county"
}
static mapping = {
table 'county'
cache: 'read-write'
columns{
id column:'id'
county column:'county'
state column:'state_id'
}
id generator: 'assigned'
}
}
It depends on how you've associated your domain classes. If State hasMany County(ies) and/or County belongs to State, you can use the dynamic finders. For example:
// All Counties
County.list()
// All States
State.list()
//All Counties in State Vermont
State.findByName("Vermont").counties
//State for a county
County.findByName("Chittenden").state
If you're trying to make a somewhat dynamic form, you could show your State dropdown first and have the County dropdown inactive until the State is chosen. Then you can make an asynchronous call to get the counties for the State or if the full objects are already loaded, you could just populate the County select box with selectedState.counties
.
See GORM Object Relational Mapping: http://grails.org/doc/latest/guide/GORM.html#domainClasses