How to auto increment any field based on other field?

Hi,

Suppose I have two fields i.e., User and Order. Now based on each User I want to auto increment ‘Order’ field.
For ex: For User1, Order should be 1,2,3,4… so on. And for User2, Order should be again 1,2,3,4… so on

Thanks in advance
Saurabh

Hi @saurabh60292,

Unique Numbers is the answer to your question. Just call the UniqueNumbersService#getNextNumber("orderSeq_" + userLogin) and get the number you are looking for.

Regards,
Aleksey

1 Like

Hi @stukalov ,

what would be “orderSeq_” here. In my case its not working.

    @Inject
	private UniqueNumbersService unService;
	@Override
	protected void initNewItem(Order item) {
	    item.setOrder(unService.getNextNumber("order"));
	}

“order” here is my field in entity which I want to auto increase.

Hi @saurabh60292,

As per documentation that I sent you earlier, no matter what field you would like to increment, you just should pass some unique name per sequence. So, in my example for each user you will have different sequences:
for admin it will be orderSeq_admin, for guest it will be orderSeq_guest. Each of them will return next value independently. Isn’t it the thing you were looking for?

Regards,
Aleksey

Hi @stukalov,

Ok it working as expected now with below code:

newObject.setOrder((int) unService.getNextNumber(object.getType()));

but if I dont save the record , the number still increment every time.

Thanks,
Saurabh

Hi @saurabh60292,

Then just make this happen before commit. There are two ways:

  1. To override preCommit method in an editor
  2. Define before commit entity listener

Choose one that fits you best.

Regards,
Aleksey