+ Start a Discussion
arun kumar.ax887arun kumar.ax887 

How to generate user defined AutoNumber in Apex class

Hi,

 

     I have requirement, where in I have 2 record types, Hardware Record Type and Software Record Type under Opporutnities,  I just want to generate two separate autonumbers for Hardware recordtype and Software recordtype.  I tried  to get this using functionality, but I am not getting the desired output.

 

 

Output

 

HW-0001

HW-0002

HW-0003

SW-0004

SW-0005

SW-0006

 

 

Desired Output

 

HW-0001

HW-0002

HW-0003

SW-0001

SW-0002

SW-0003

 

 

      For the above requirement, I want to generate autonumber in an Apex Class,  could any one please send the solution for the above mentioned requirement.

 

 

 

Regards

 

Arun

 

 

 

 

Shailesh DeshpandeShailesh Deshpande

Adding a "if" condition may solve your problem.

 

eg:

 

if(RecordType== 'Hardware')

{

//increment HW

}

if(RecordType== 'Software')

{

//increment SW

}

 

If this does not work, Kindly post your code.

 

Thanks,

Shailesh. P. Deshpande

 

arun kumar.ax887arun kumar.ax887

 

Hi Shailesh,
    I have created a customobject called  AutoNumberHolder in which i have assigned 0 zero to both software and hardware fields of number type,  Then each time when I create a record in Opportunity, I will get the value of hardware/software from the  AutoNumberHolder increment it by one and save it in Num a cumtom field in Opportunity  and then I will update this value in hardware/software field in the  AutoNumberHolder object, so that when we retrieve the value next time we should get the updated one.
    Actually I tried this method, but it is not working.  So could you please look into the code and send some suggestions for a better solution.
 
Trigger
trigger OppTrigger on Opportunity (before insert, after insert, before update, after update) 
{
    Opportunity [] oppr =  Trigger.new;
    Auto1.display(oppr);
}

Apex Class
public class Auto1
{
    public static void display(Opportunity [] oppr)
    {
         Integer m;
              
       for(Opportunity o : oppr)
       {
        if(o.type=='Hardware')
        {
                  AutoNumberHolder__c n =[select hardware__c from AutoNumberHolder__c  where id =:'a0190000000Vg3t' ];
                  m=n.hardware__c.intValue();
                  m=m+1;
                  o.num__c=m;
                 n.hardware__c=m;
           
                  update n;
        }
        
       if(o.type=='Software')
        {
                  AutoNumberHolder__c n =[select software__c from AutoNumberHolder__c  where id =:'a0190000000Vg3t' ];
                  m=n.software__c.intValue();
                 m=m+1;
                  o.num__c=m;
                 n.software__c=m;
                  
                  update n;
        }
        
     }
   }
}
Regards 
Arun