Grails: <g: select

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 to select a control with the values: Active / Inactive. If you select Active you must pass the value True and If you select InActive you must pass the value False .

How can I achieve this using

 <g:select name="status" from="" optionKey="" value="" /> 

Great importance.

+4
source share
2 answers

I don't know if this is the best approach, but you can do an enumeration to do the job:

 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 enumeration 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 save method, you need to get the correct enumeration from the String value represented 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 } 
+8
source

Ok After a big brainstorm I could figure it out

My code is simpler and looks something like this:

 package exproj.masters public enum ExamDurationTypes{ FULL_EXAM(1, 'For Whole Exam'), PER_QUESTION(2, 'Per Question') Integer optionValue String name ExamDurationTypes(Integer optionValue, String name){ this.optionValue = optionValue this.name = name } static getByName(String name){ for(ExamDurationTypes edt : ExamDurationTypes.values()){ if(edt.name.equals(name)){ return edt; } } return null; } static list(){ [FULL_EXAM, PER_QUESTION] } public String toString(){ return optionValue } } 

Then I added it to the Domain class

 class Exam { . . . Integer durationType static constraints = { durationType(inList: ExamDurationTypes.list()) } } 

On my GSP page, I hacked it like this

 <g:select name="durationType" from="${exproj.masters.ExamDurationTypes.values()*.getName()}" keys="${exproj.masters.ExamDurationTypes.values()*.getOptionValue()}" value="${examInstance.durationType}" /> 

Finally, you get the following:

 <select name="durationType" id="durationType"> <option value="1">For Whole Exam</option> <option value="2">Per Question</option> </select> 

Enjoy coding

0
source

Source: https://habr.com/ru/post/1305127/


All Articles