Skip to content

Instantly share code, notes, and snippets.

@ykurnia
Created November 28, 2012 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ykurnia/4162169 to your computer and use it in GitHub Desktop.
Save ykurnia/4162169 to your computer and use it in GitHub Desktop.
Salesforce trigger to generate invoice number, reset each year
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