Given the following
class MyDomain {
enum State {
PRIMORDIAL,
INITIAL,
EXTENDED,
TERMINAL
}
State state
}
I'd like the 'state' property to be persisted so that:
How can this be achieved?
Thanks
Pretty sure the answer is... not very easily. Enums currently only store 1 value in the DB, so if you want the string in the DB, then that's the only data it'll have to issue an ORDER BY against. That said... once you load the data into Gorm Domain objects, you could then sort it, but that won't get your pagination correct (if you need that).
You COULD create your own enum-like class to contain both an order and a string, and map it to two fields in your table, then order by one or the other as appropriate. I do this a lot with what I call "Possible Values" or "Menu Values"; something like:
class MenuValue {
String text
String description // used for mouseover, or some such
int sort_order
String group // used to retrieve all values for a menu/pulldown, etc.
}
I then usually put code in my Fixtures for creating menu options when needed by tests, etc.
The benefit of this over enum's is an ability to change the contents of a menu/select on the fly using an admin-type crud screen. You can still "iterate" over them kind of like an enum via:
MenuValue.findAllByGroup( "groupname" ).sort { it.sort_order }.each { it -> iteration code }
So, if you had a class where someone had to select from a menu, you could do:
class SomeObject {
String something
MenuValue selectedValue
}
And you could retrieve all the SomeObjects, sorted by the sort_value of the MenuValue like:
params.sort = "selectedValue.sort_order"
params.order = "asc"
SomeObject.findAllBySomethingLike( search_term, params )
And during editing of your SomeObject, you could have a select with the list of possible values, and have the name of that select be "selectedValue.id", and Grails will autopopulate the selectedValue field in the SomeObject during data binding with a reference to the selected MenuValue.
Hope this is helpful