0

I have a domain class:

class MyUser {

 ..

int sex
int qualification
int occupation

..
}

Suppose I want to constraint these integer categories, for example:

occupation : [0:"not occupied", 1:"architect", 2:"student", 3:"policeman" and so on..]

I would like to have on database the integer values and have displayed on my views the string representation of the integer (can this behaviour be scaffoilded automatically?).

is there a way to do this quickly in the grails way?

thanks!

Michael J. Lee
  • 12,278
  • 3
  • 23
  • 39
Giuseppe
  • 41
  • 4

2 Answers2

0

I suggest using an object to represent the occupation like so...

class MyUser {
...
    int sex
    int qualification
    Occupation occupation
...
}

Then your occupation class would look like this...

class Occupation {
    ...
    String name
    ...
}

However, if you insist on using a enum type you could do something like this...

    public enum Occupation {
        GEEK(0, 'Geek'),
        NERD(1, 'Nerd'),

        final int id;
        final String name;

        Occupation (int id, String name) {
          this.id = id;
          this.name = name;
       }
    }

Your MyUser class would like like this...

   class MyUser {
    ...
        int sex
        int qualification
        int occupation
    ...
    }

And you gsp would like something like this...

 <g:select name="occupation" id="occupation"
                        from="${Occupation.values()}" 
                        value="${fieldValue(bean: user, field: 'occupation')}" 
                        optionKey="id"
                        optionValue="name"/>

This is untested but should work. Enjoy.

Michael J. Lee
  • 12,278
  • 3
  • 23
  • 39
  • Yes that is right; but for sex: should I model a class for that too? I think is better to have an integer direclty on database (for performance reason) and display MALE or FEMALE on the view.. – Giuseppe Jun 01 '12 at 09:54
  • Performance at this level isn't an issue and your thinking WAY to far into it. Caching will take care of a lot of your performance concerns and a Map could actually be slower because it might not be controlled by the cache. DEAL WITH PERFORMANCE ISSUES WHEN THEY COME UP. – Michael J. Lee Jun 01 '12 at 10:03
0

if you want, you can use map also and passed it through controller to view....

sanghavi7
  • 758
  • 1
  • 15
  • 38