Search code examples
grailsgrails-orm

GORM: populate list into select dropdown


I am working on a Grails form item that just populates a list of FaqCategories from an FaqCategory domain class. All I want the select dropdown to do is display the list. So far, this sort of works, but I'm not sure how to generate the list or what to put in the Value section if anything.

Form item:

    <div class="col-sm-9">
        <g:select name="Category" from="${FaqCategory.list()}" required="" class="form-control" aria-labelledby="faqCategory-label" value=""/>
    </div>

Domain class #1

class Faq {

    String question
    String answer
    FaqCategory faqCategory

    static constraints ={
        question nullable:false, maxSize:1000
        answer nullable:false, maxSize:1000
        faqCategory nullable:false
    }
}

Domain class #2

class FaqCategory {

String categoryType

String toString(){
    "$categoryType" 
}

static constraints = {
    categoryType nullable:true, maxSize:100, unique:true
}

}

Controller snippet

@Transactional(readOnly = true)
def create() {
    respond new Faq(params)
}

Solution

  • Controller code :

    yourAction(int id){
    
      //do some 
       def faqInstance = Faq.get(id)
       render[view:"form",model:[faqInstance:faqInstance]]
    }
    

    View code :

    <g:select name="faqCategory"
              from="${FaqCategory.list()}"
              value="${faqInstance?.faqCategory?.categoryType}"
              optionKey="id" />
    

    Hope it helps..