Is it possible to set the default value for a generated (scaffolded) State dropdown box in Grails? I am hoping that this is something I can do within either the domain class or the controller class:
class State {
String name
String code
static mapping = { sort name: "asc" }
String toString() {
return this.name;
}
}
class Person implements Comparable {
String firstName
String lastName
State state
String toString() {
return this.lastName + ", " + this.firstName;
}
}
I have tried explicitly setting String name="Pennsylvania" and String code="PA" in the State domain class with no luck. I am bootstrapping the State data in Bootstrap.groovy:
def init = { servletContext ->
if (!State.count()) {
new State(name: "Alabama", code:"AL").save(failOnError: true)
new State(name: "Alaska", code:"AK").save(failOnError: true)
new State(name: "Arizona", code:"AZ").save(failOnError: true)
new State(name: "Arkansas", code:"AR").save(failOnError: true)
....
}
}
Updated:
PersonController.groovy:
def create() {
// [personInstance = new Person(params)]
def personInstance = new Person(params)
personInstance.state = new State("Pennsylvania", "PA")
[personInstance: personInstance]
}
State.groovy:
public State(String name, String code) {
this.name = name
this.code = code
}
If you’re trying to set the default value of the state dropdown for the “new Person” page, then you would probably want to make the default value of Person’s ‘state’ member be the ‘Pennsylvania’ state that you create in Bootstrap.
Actually, I think that a better way to do this would be to actually generate the PersonController, and then modify the ‘create’ closure to set the initial value of Person.state