Generate Criteria based Autonumber in Salesforce


 In this blog I will create a criteria based auto number field in Salesforce. Please follow below steps to generate the autonumber based on criteria.

Step 1 : Create a custom number field in your object, in below example the field name is numberfield__c and it is in contact object.

Step 2 : Create a trigger as shown below : 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
trigger contacttrigger on Contact (before insert) {
    if(Trigger.isBefore){
        double autonumber = 0;
        List<Contact> conList = [SELECT Id, numberfield__c, CreatedDate FROM Contact where numberfield__c != null
                                 order by CreatedDate desc limit 1];
        if(conList != null && conList.size()>0){
            autonumber = conList[0].numberfield__c;
        }
        else{
            autonumber = 0;
        }
        for(Contact c : Trigger.New){
            if(c.Status__c == 'new'){
                autonumber++;
                c.numberfield__c = autonumber;
            }
        }
        
    }
}

Checkout complete tutorial below 

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 


Post a Comment

0 Comments