How can I achieve the following:
I have a boolean stored in my Domain, by default Grails creates a checkbox as a control. I want a select control with values : Active/Inactive.
On selecting Active
the value True
should be passed
and
On selecting InActive
the value False
should be passed.
How can I achieve this using
<g:select name="status" from="" optionKey="" value="" />
Much appreciated.
I don't know if this is the best approach, but you could have an enum to do the work:
public enum SelectOptions{
ACTIVE(true, 'Active'),
INACTIVE(false, 'InActive')
Boolean optionValue
String name
SelectOptions(boolean optionValue, String name){
this.optionValue = optionValue
this.name = name
}
static getByName(String name){
for(SelectOptions so : SelectOptions.values()){
if(so.name.equals(name)){
return so;
}
}
return null;
}
static list(){
[ACTIVE, INACTIVE]
}
public String toString(){
return name
}
}
Add an instance of the SelectOptions enum to your domain:
class MyDomain {
SelectOptions selectOptions = SelectOptions.ACTIVE
//Other properties go here
static constraints = {
selectOptions(inList:SelectOptions.list())
//other constraints
}
}
Then in your GSP view:
<g:select
name="status"
from="${myDomainInstance.constraints.selectOptions.inList}"
value="${myDomainInstance.selectOptions}" />
In your controller's save method, you need to get the correct enum from the String value submitted by the view:
def save = {
SelectOptions selectOption = SelectOptions.getByName(params.status)
def myDomainInstance = new MyDomain(params)
myDomainInstance.selectOptions = selectOption
// proceed to save your domain instance
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With