You need to sign in to do that
Don't have an account?
Ab
append a number for first time and increment it everytime by one
Hello,
I have a usecase where, i get 4 characters of account name and i append a unique 10 digit number after.
i am wondering how can get the last number generated and increment it by one.
thank you for suggestion !
I have a usecase where, i get 4 characters of account name and i append a unique 10 digit number after.
i am wondering how can get the last number generated and increment it by one.
thank you for suggestion !
------------------
trigger AccountTrigger on Account (before insert) {
if(Trigger.isBefore) {
if(Trigger.isInsert) {
AccountTriggerHandler.onBeforeInsert(Trigger.New);
}
}
}
Handler:
------------------
public class AccountTriggerHandler {
public static void onBeforeInsert(List<Account> accounts) {
Integer concatinatedValue = 1234567890;
Integer accountSize = accounts.size();
// To get the Last Inserted Record with 10 digits
Account account = getLatestAccount();
// condition to check for the record
if(account != null) {
// To get the 10 digit number from Name
Integer intValue = getIntFromName(account.Name);
// Condition to check if the 10 digit exists or not
if(intValue != null) {
concatinatedValue = intValue;
} else {
concatinatedValue = concatinatedValue - 1;
}
}
// Condition to check the record count
if(accountSize > 0) {
// Loop to iterate over the List of records
for(Integer i=0; i < accountSize; i++) {
concatinatedValue = concatinatedValue + 1;
accounts[i].Name = accounts[i].Name + concatinatedValue;
}
}
}
// Method to get the Last inserted Record based on created Date for the existing records
private static Account getLatestAccount() {
List<Account> accounts = [SELECT ID, NAME FROM Account ORDER BY CreatedDate Desc];
if(accounts.size() > 0) {
return accounts[0];
}
return null;
}
// Method to spilt the first 4 characters from concatinated number
private static Integer getIntFromName(String Name) {
String phrase = Name;
Integer rephrase = null;
if(phrase != null && phrase.length() > 4) {
phrase = phrase.substring(4, phrase.length());
if(phrase.isNumeric()) {
rephrase = Integer.valueOf(phrase);
}
}
return rephrase;
}
}
Test class:
------------------
@isTest
public class AccountTriggerHandlerTest {
@isTest static void AccountTest() {
Account account = new Account(Name = 'WXYZ');
insert account;
List<Account> accounts = new List<Account>();
for(Integer i = 0; i < 10; i++) {
Account account1 = new Account(Name = 'ABC' + i);
accounts.add(account1);
}
insert accounts;
System.assert(accounts.size() > 0);
}
}