I have a trigger which inserts merged record under a custom object called Account_merged__c. The trigger is as follows:
trigger AccountMergeTrigger on Account (after delete) {
List<Account_Merged__c> listAccountBackup = new List<Account_Merged__c>();
for(Account acct : trigger.old) {
if(String.isNotBlank(acct.MasterRecordId)) {
listAccountBackup.add(new Account_Merged__c(
Name = acct.Name,
Policy_Number__c = acct.Policy_Number__c,
Account_Code__c = acct.Account_Code__c,
TaxID__c = acct.TaxID__c
));
}
}
if(listAccountBackup.size() > 0) {
insert listAccountBackup;
}
}
In the above trigger, the name field will be saved as 'Account A Acquired Account B'. Now, I want to separate the value into 2 fields like field 1 will be having Account A and field 2 will be having Account B leaving out acquired keyword.
I already have formula in place to get this done but I want this to be done with the above trigger itself. Below are the formulas used in field 1 and field 2
field 1:
IF(CONTAINS(Name, "acquired"),
LEFT(Name,Find("acquired", Name)-2),
IF(CONTAINS(Name, "Acquired"),
LEFT(Name,Find("Acquired", Name)-2), ""))
The above formula will cut the left part of acquired word.
field 2:
IF(CONTAINS(Name, "acquired"),
RIGHT(Name,LEN(Name)-Find("acquired", Name)-8),
IF(CONTAINS(Name, "Acquired"),
RIGHT(Name,LEN(Name)-Find("Acquired", Name)-8), ""))
The above formula will cut the right part of acquired word.
Update
Below is the updated trigger suggested by @Manish.
trigger AccountMergeTrigger on Account (after delete) {
List<Account_Merged__c> listAccountBackup = new List<Account_Merged__c>();
for(Account acct : trigger.old) {
if(String.isNotBlank(acct.MasterRecordId)) {
Account_Merged__c ma = new Account_Merged__c();
ma.Name = acct.Name;
ma.Policy_Number__c = acct.Policy_Number__c;
ma.Account_Code__c = acct.Account_Code__c;
string s = Acct.Name;
integer i = s.indexof('Acquired');
string account2 = s.substring(i+9);
string account1 = s.substring(0,i-1);
system.debug('account2 '+account2);
system.debug('account1 '+account1);
ma.Field_1__c = account1;
ma.Field_2__c = account2;
listAccountBackup.add(ma);
}
}
if(listAccountBackup.size() > 0) {
insert listAccountBackup;
}
}
While merging the duplicate records, I am getting the error as
AccountMergeTrigger: execution of AfterDelete caused by: System.StringException: Ending position out of bounds: -2 Trigger.AccountMergeTrigger: line 12, column 1
Can anyone suggest the changes in my trigger to divide the name string and save it using the trigger itself.