7
votes

I'm new to Grails. I have a field in my domain object which I define as an String.

String ponum

When i click first time on create page ,the "ponum" field has to display 0001 and later it has to save in database.And When i click on second time the "ponum" field has to display 0002 and later it has to save in database.Everytime i click on create page "ponum" field has to autoincrement and save it database.I google ,but i did not get any document. thanks

2
The version field (which is automatically added by grails) also tells you how many times the row has been updated. Grails automatically increments it each time the row is updated, so if that's all you're looking for, it might work for you. - Todd

2 Answers

6
votes

As things get an id anyway (assuming your using a regular rdbms with standard id genaerator), why not just pretend there's a variable ponum which is based on the id?

Just add a getter to your domain class:

class Page {
  String getPonum() {
    String.format( "%04d", id )
  }
}
1
votes

According to this answer, it is not possible to use hibernate generators (those used for ids) to do that. If you really need to use Hibernate generators, a workaround is described in the answer as well.

In your case, you could use an interceptor to generator your ponum property when inserting a new object:

class Yours {
  int ponum

  def beforeInsert() {
    def lastPonum = Book.list([sort: 'ponum', order:'desc', max: 1])
    if(lastPonum)
      ponum = (lastPonum.pop().ponum as int) + 1 as String
    else
      ponum = '0'
  }
}