+ Start a Discussion
❤Code❤Code 

Autonumber issue in apex trigger

I have a class which assigns Name field by appending two other fields -

Ex -

Name = Name + '-' + Market__c;

I have a trigger which appends the name with autonumber -

Name = Name + '-' + Market__c + '-' + autonumber;

Below is the problem which i am facing -

On insert it creates the name like -

Name = X-A-1

When i insert another record it creates the name like -

Name = X-A-1-1
Name = X-B-2

But i want the on insert it should continue the autonumber, Not start it again from 1st record.
 
trigger childrfptest on ChildRFP__c (after insert) {
    integer auto=1;
    set<id> uatid = new set<id>();

    for(ChildRFP__c r:trigger.new){
        uatid.add(r.id); 
    }

    List<ChildRFP__c> cp = new List<ChildRFP__c>();
    List<ChildRFP__c> cp1 = new List<ChildRFP__c>();
    cp = [select Parent_RFP__c from ChildRFP__c where id =:uatid];

    for(ChildRFP__c cd: cp)
    {    
       cp1=  [select Id,Name from ChildRFP__c where Parent_RFP__c =:cd.Parent_RFP__c];

    }
    auto=1;
    for( ChildRFP__c cd1: cp1)
    {

        cd1.Name= cd1.Name + '-'+ auto;
        update cd1;

        auto++;
    }

}

Regards
 
Sean McMickleSean McMickle

I highly recommend taking your select statements and update statements out of your loops. They are eating up a ton of your very limited SOQL statements. 
 

Instead of selecting inside the loop, loop through cp and create a list or set of strings or ids that contain cd.Parent_RFP__c.

Then, you can use that list to select what you need.

For instance :
 

Set<Id> parentRFPs = new Set<Id>();

for(ChildRFP__c cd: cp) {
      parentRFPs.add(cd.Parent_RFP__c);
}

List<ChildRFP__c> childRFPList =  [select Id,Name from ChildRFP__c where Parent_RFP__c in : parentRFPs];

for(ChildRPF__c childRFP : childRFPList) {
     childRFP.Name = childRFP.Name + '-' + auto;
     auto++;
}

update childRFPList;
 

This will also have the added bonus of correctly naming your childRFPs. Be warned, though.. This will only work if you are inserting many records at the same time. Once you start a new insertion command, the counter will start over at 1 again. To get around this, you can always have a record somewhere that you query to keep track of the number that it is currently on.

Good luck! Let me know if you have any other questions!

-Sean