Search code examples
grailsgrails-orm

How to display subcategories under category in grails?


I want to display subcategories under related categories. For example:

 Category
 SubCategory
 SubCategory
 SubCategory

 Category
 SubCategory
 SubCategory
 SubCategory

Category
 SubCategory
 SubCategory
 SubCategory

Followings are domain classed related to category and SubCategory:

Category.groovy

class Category {

    String name
    String description
    static constraints = {
    }
    static hasMany = [ subCategories: SubCategory ]

}

SubCategory.groovy

class SubCategory {

        String name

        static hasMany = [requirements: Enquiry]
        static belongsTo = [ category: Category]
        static constraints = {
            requirements nullable:true
        }
    }

ShowCreateEnquiry Where I tried to write logic for getting category and related subcategories.

def showCreateEnquiry() {
        def reqCode = Util.generateUniqueReqCode()
        EnquiryCommand enquiryInstance = new EnquiryCommand();
        enquiryInstance.setReqCode(reqCode) ;
        def marketlist = Category.list(params.id)
        def subCategoryList = marketlist?.subCategories
        render ( view: "showCreateEnquiry" , model:[ "enquiryInstance": enquiryInstance, "marketlist": marketlist] )
    }

Now I want something like this: Someone told me that I can create groovy list in above action, where I can pass parameter of category and subcategories and use those variable in GSP and use 2 for or each loop to iterate category and subcategory. Could anyone help me achieving this.


Solution

  • Below is the solution according to what I understand :)

    showCreateEnquiry.gsp

    <g:each in="${marketlist}" var="category">
        <p>${category.name}</p>
        <g:each in="${category.subCategories}" var="subCategory">
          <p>${subCategory.name}</p>
        </g:each>
    </g:each>
    

    In addition you don't need to include enquiryInstance in model for rendering. And use css for styling your view.