views:

43

answers:

1

Hi,

I'm writing a tag that essentially needs to dump an arbitrary domain class for the fields requested via parameters to the tag. This works fine if the field is a normal attribute. But, if it's a "hasMany" relationship, what are my options?

In other words, how do I check if a string passed as a parameter to the tag corresponds to a "hasMany" relationship, and get the corresponding domain name?

Note that I can instantiate the domain class and do a getClass on it - maybe it's in the properties? I'll check, but any input is much appreciated.

To be more specific, in the following code, I need to check in if any of the names is a "hasMany" relationship as opposed to an attribute, access that domain, and print all the instances of it.

Here's the code as it exists nos:

/* * Tag to ouput domain level information * */

def get_domain_info = { attrs, body ->


    // get the domain name for lookup on the Misc Fields XML table
    def id = attrs['id']


    def domainName = attrs['domain_name']

    // get the domainInstance
    def domainInstance = grailsApplication.getArtefact("Domain",domainName)?.
    getClazz()?.get(id)


    def dataNames = attrs['data_names']

    def dataNameArray = dataNames.split(",")

    out << "<div class=\"dialog\">"

    for(dataName in dataNameArray) {
        out << "<tr class=\"prop\">"
        out << "<td valign=\"top\" class=\"name\">"  + dataName + "</td>"
        def dataValue = domainInstance[dataName.trim()]
        if (dataValue == null){
            dataValue = ""
        }
        def valueLine
        if ( dataValue.class == java.sql.Timestamp){
            valueLine = "<td valign=\"top\" class=\"value\">"  +
            dataValue.format("d MMM yyyy") +  "</td>"
        }
        else {
            valueLine = "<td valign=\"top\" class=\"value\">"  + dataValue + "</td>"
        }
        out << valueLine
        out << "</tr>"

    }
A: 

The domain class should always have a Set or List property defined for the hasMany, e.g.,:

class Author {
   static hasMany = [books:Book]
   List books
}

So in that case, domainInstance[dataName] will return a List of Books. All you really need to do is see if the property is a Collection:

 if(dataValue instanceof Collection) {
     // handle hasMany
 }

Is some weird cases, a hasMany can also be a Map. See http://www.grails.org/GORM+-+Collection+Types

noah