+ Start a Discussion
❤Code❤Code 

autonumber trigger not working

Hi All,

I have an custom autonumber field in an custom object. Below is my trigger. But on record insert the trigger is not firing and field is not getting updated.

The requirement is - 

Every time the record is inserted , it should check the last digit and then the sequence should continue. Please help.
 
trigger Childrfpautonumber on ChildRFP__c (before insert) {
    
    List<ChildRFP__c> lstNum  = [SELECT Id,AutoNumber__c FROM ChildRFP__c Order BY Createddate DESC LIMIT 1];
    Integer intCounter = 0;
    for(ChildRFP__c obj: lstNum)
    {
        intCounter ++;
        obj.AutoNumber__c = intCounter;
    }

}

 
srlawr uksrlawr uk
I don't think you intend to "for" loop over your list lstNum? That only contains one element - the newest record.... surely you want to iterate over Trigger.new?
 
trigger Childrfpautonumber on ChildRFP__c (before insert) {
    
    List<ChildRFP__c> lstNum  = [SELECT Id,AutoNumber__c FROM ChildRFP__c Order BY Createddate DESC LIMIT 1];
    Integer intCounter = 0;
    for(ChildRFP__c obj: Trigger.New)
    {
        intCounter ++;
        obj.AutoNumber__c = intCounter;
    }

}


Also - and I don't want to critise the work - I'm not sure this is the best way to increment an auto-number. If you insert 50 records at once (from a dataload, or such) they are all going to get the same createdDate - and be numbered somewhere in that range of 50 values... then, when the trigger next runs, I wouldn't be 100% sure that the value you get back is going to be the "largest" autonumber__c for that moment in time, could it not be any one of the 50 inserted in the same batch? It just seems... potentially flawed to me!
 
❤Code❤Code
Thnx srlawr,

The above code is generating everytime autonumber = 1 and inserting it for all records. But i want each time record is created it should increment.

Can u help.

Regards
srlawr uksrlawr uk
Out of interest, why don't you just use an auto-number field? That is a field type in Salesforce.
❤Code❤Code
Why i cant use is - 

I have two custom objects Product and childproduct. childproduct is a related list (lookup) to Product . When i will create a childproduct i want the name should be appended with an autonumber.

Example -
Product1
childproduct1--0
childproduct2--1
childproduct3--2

Product2
childproduct1--0
childproduct2--1
childproduct3--2

If i create a childproduct of any existing Product, the autonumber should start where the number is ended. For Ex - from above it should start with
childproduct4--3
 
ArmouryArmoury
How about ordering by AutoNumber__c instead of CreatedDate in the query?
srlawr uksrlawr uk
haha! thats such a goof idea Armoury.. would solve the created date problem I described. Not sure how I didnt think of that!