cancel
Showing results for 
Search instead for 
Did you mean: 

How to auto generate ID column on CAP Entity Projects?

Yella1260
Associate
Associate
0 Kudos
91

As part of our project requirement we want to use generated number with prefix of 'S' and few leading zeros '0000' and number in the end like 1 etc. The expected generated value is like below where there is any insert in to:

entity BPM : cuid, managed {
     publish_status     : String(500);
     retry_count : Integer default 0;
     internalId: String(10); // generated string
}
 
generated string should be like
S000000001
S000000002
S000000003
S000000004
S000000005
....
S000000015 etc.
 
 
If this is not possible at least generated integer and auto increment on insert like below:
entity BPM : cuid, managed {
     publish_status     : String(500);
     retry_count : Integer default 0;
     internalId: Integer auto generated increment by 1 // generated number...
}
 
We have already UUID generated value, but still we are looking the internal ID in readable format like 10 character string. I got some example with sequence, but we want to avoid call to sequence and set the text before insert. please help if any one is aware of that.
 

Accepted Solutions (0)

Answers (1)

Answers (1)

dev-hirsbrunnerm
Explorer
0 Kudos

Hello,

the only way i am aware of that would be to implement a custom handler on application level, so in Javascript it could look like this:

 

 

this.before("CREATE", "Your entity here", async (req) => {
  let newId = 'S00000001;
  const { maxID } = await cds.tx(req).run(SELECT.one.from("Your entity").columns("max(internalId) as maxID");

  if (maxID) {
     const coutner = Number(maxID.substr(1,maxID.length -1));
     newId = `S${(counter + 1).toString().padStart(9, '0')}`;
  }
  req.data.internalId = newId;
});

 

The above code is just a rough idea, i didn't actually let it run, but something similar to this should probably work.

 

Cheers
Marco