Search code examples
grails

getting domain names of user created domain classes in Grails


Is there a way to access domain objects metadata of only the domain created by the user (for lack of a better word) as opposed to domain objects that are part are integrated into a project by means of plugins, etc?

What I'm after is getting names of domain objects in gsp file for all sorts of gui related activities ( building menus, etc.)

So if I do something like this:

<%
    for( domain in grailsApplication.domainClasses ){
        print ( '<h3>domain class locgial property name: ' + domain.logicalPropertyName + '</h3>' )
        print ( '<h3>domain  full name: ' + domain.fullName + '</h3>' )
    }
%>

... I can get the names, hack them in JS to determined if they belong my own generated packages ( com.ra for instance ), but that seems very fragile.


Solution

  • Plugin classes have the org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin annotation added to them by the compiler, so you can pass down just the application's domain classes from the controller to the GSP in the model like this:

    import org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin
    
    class MyController {
    
       def myAction = {
          ...
          def appDomainClasses = grailsApplication.domainClasses.findAll {
             !it.clazz.isAnnotationPresent(GrailsPlugin)
          }
          [appDomainClasses: appDomainClasses]
       }
    }
    

    and then loop through them in the GSP:

    <g:each var='dc' in='${appDomainClasses}'>
    <h3>domain class logical property name: ${dc.logicalPropertyName}</h3>
    <h3>domain full name: ${dc.fullName}</h3>
    </g:each>