In Grails, how do I get a list of all discriminator values for all subclasses of a base type?

551 Views Asked by At

Let's say I have the following classes:

class Apple extends Fruit { ... }
class Banana extends Fruit { ... }
class Grape extends Fruit { ... }
class Kiwi extends Fruit { ... }

And so on and so forth. I now need to display a dropdown that contains a list of all the discriminator values of all subclasses that extend Fruit, so for example:

<select name="fruitType">
    <option value="Apple">Apple</option>
    <option value="Apple">Banana</option>
    <option value="Apple">Grape</option>
    <option value="Apple">Kiwi</option>
</select>

This is easy enough to hard-code for 4 of these, but in my actual domain there's the potential for this list to get quite long. Is there any way of getting a list of all the discriminator values for all subclasses that implement a base type? Something like this, for example:

Fruit.class.getAllDiscriminatorValues()
1

There are 1 best solutions below

0
On

You could do this:

def getAllFruitSubclasses() {

   def fruit = []

   grailsApplication.domainClasses.each { 
      if (it.clazz.superclass == 'com.whatever.Fruit') {
         fruit << it.clazz.simpleName
      }
   }
   return fruit
}