Created
November 28, 2012 15:59
Salesforce trigger to generate invoice number, reset each year
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trigger InvoiceTrigger on Invoice__c (before insert) { | |
if (trigger.isBefore && trigger.isInsert) | |
{ | |
// ---- GENERATE INVOICE NUMBER, AUTO RUNNING NUMBER, RESET EVERY YEAR BASED ON CREATED DATE --- // | |
// ---- INVOICE NUMBER FORMAT : {0000} --// | |
Integer iCharLen = 4; // character length for number | |
Integer iLastNo = 0; // information last running number this year | |
Integer iThisYear = Date.Today().year(); | |
// search latest invoice number | |
String strTemp = '0'; | |
String strZero = '0'; | |
List<Invoice__c> lsInvoice = new List<Invoice__c>([SELECT Id, Name FROM Invoice__c WHERE CALENDAR_YEAR(CreatedDate) = :iThisYear LIMIT 1 ]); | |
if (lsInvoice.size() > 0) strTemp = lsInvoice[0].Name; // in this case, invoice number only contains numeric value : 001, 003, etc | |
iLastNo = Integer.valueOf(strTemp); | |
// start generate number | |
for(Invoice__c Inv: trigger.new) | |
{ | |
iLastNo++; | |
strTemp = String.valueOf(iLastNo); | |
if (strTemp.length() < iCharLen) strTemp = strZero.repeat(iCharLen - strTemp.length()) + strTemp; // add 0 prefix | |
Inv.Name = strTemp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment