function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
David OvellaDavid Ovella 

is it possible to create a trigger that allow a custom number field go in only consecutive order?

Hello,
I want to know if it's possible to create a trigger that let a number field goes only in a consecutive order,
this custome field must not be Auto-Number field because it has to be entered

Example:
the user entered a value in the number field PRE_IMPRESO__c between 001 to 100

PreImpreso: 001
PreImpreso: 002
If I try to enter 004 and 003 was not entered yet, I get the error "Pre-Impreso isn't going in consecutive order"


I would really appreciate any kind of example
thanks
Best Answer chosen by David Ovella
Ravi Dutt SharmaRavi Dutt Sharma
This is not completely bulkified, but you can build something around this approach. Thanks.
 
trigger LeadTrigger on Lead(before insert,before update){

	AggregateResult[] groupedResults = [SELECT Max(PRE_IMPRESO__c ) FROM Lead];
	Decimal maxCount = (Decimal)groupedResults[0].get('expr0');
	
	for(Lead ld : Trigger.new){
		if(maxCount - ld.PRE_IMPRESO__c  != 1){
			ld.addError('Not a consecutive number');
		}
	}
}

 

All Answers

Ashish DevAshish Dev
You can do this simply through validation rule.
Put rule like below.
 
(custom_num_field__c <>  PRIORVALUE(custom_num_field__c ) + 1)  ||  ( ISNEW() || custom_num_field__c  <> 1)

 
AshlekhAshlekh
Hi,

You can use Auto Number type for this type of requirement.

-Thanks
Ashlekh 
Ravi Dutt SharmaRavi Dutt Sharma
This is not completely bulkified, but you can build something around this approach. Thanks.
 
trigger LeadTrigger on Lead(before insert,before update){

	AggregateResult[] groupedResults = [SELECT Max(PRE_IMPRESO__c ) FROM Lead];
	Decimal maxCount = (Decimal)groupedResults[0].get('expr0');
	
	for(Lead ld : Trigger.new){
		if(maxCount - ld.PRE_IMPRESO__c  != 1){
			ld.addError('Not a consecutive number');
		}
	}
}

 
This was selected as the best answer
David OvellaDavid Ovella
thanks everyone for answer

ravi your code works perfect =)
Ravi Dutt SharmaRavi Dutt Sharma
Hi David, 

This may not work if you are inserting records in bulk using data loader. Please test it for bulk mode once. Thanks.