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
AtroxyAtroxy 

Adding a prefix to a counting string on a trigger

I've wrote a working trigger for my bills, as you can see below .It gives out a number whenever a new bill is created.

I'd like to now adapt that code, to not only have a 5 string number, but have a prefix. I'm having a trouble with the prefix, as I run into errors while counting up. Anybody have an idea how I could add a three letter prefix while counting the 5 digit string?

 

trigger onBill on Bill__c (before insert) {
    list<Bill__c> Bill = new list<Bill__c>([select Number__c from Bill__c order by Number__c desc limit 1]);

    String startNumber = '00000';
    if(!Bill.isEmpty()) {
        startNumber = Bill.get(0).Number__c;
    }

    for(Bill__c re:trigger.new) {
        startNumber = String.valueOf(Integer.valueOf(startNumber) + 1);
        startNumber = '00000'.substring(0, 5-startNumber.length()) + startNumber;
        re.Number__c = startNumber;
    }  
}

 

Best Answer chosen by Admin (Salesforce Developers) 
AtroxyAtroxy

I feel rather stupid figuring out the solution to my problem, but since nobody shared, here is the solution for those who'll find this in the future. I found the right place to add the substring :-)

 

startNumber = Bill.get(0).Number__c;
startNumber = startNumber.substring(3,8);

All Answers

AtroxyAtroxy

I've found quite a few posts about the same problem as mine, however none contain a real solution. There even is an idea on the boards. Anyone implemented a working Apex solution? :-)

 

http://success.salesforce.com/ideaView?id=08730000000BrGLAA0

 

http://boards.developerforce.com/t5/General-Development/Different-Auto-Number-for-Different-Branches-for-Purchase-Orders/td-p/228591

AtroxyAtroxy

I feel rather stupid figuring out the solution to my problem, but since nobody shared, here is the solution for those who'll find this in the future. I found the right place to add the substring :-)

 

startNumber = Bill.get(0).Number__c;
startNumber = startNumber.substring(3,8);
This was selected as the best answer