-1

Its working fine if the account name contains 'test' but if it contains 'TEST' or any other uppercase/lowercase combination other than 'test', its showing 'maximum trigger depth exceeded account trigger event afterupdate'

trigger changeAccountName on Account (after update) {

Set<ID> accountIDs = new Set<ID>();

for(Account acc : Trigger.new){
    if(acc.Name.containsIgnoreCase('test')){
        accountIDs.add(acc.Id);
    }
}

List<Account> listOfAccounts = [SELECT id, name from Account where ID in : accountIDs];
Map<Id,Account> mapOfAccounts = new Map<Id,Account>();
List<Account> listOfAccountsUpdated = new List<Account>();

for(Account acc : listOfAccounts){
    mapOfAccounts.put(acc.ID,acc);
    if(!acc.Name.containsIgnoreCase('test1')){
        String accountName = mapOfAccounts.get(acc.ID).Name.replace('test','test1');
        acc.Name = accountName;
        listOfAccountsUpdated.add(acc);
    }
}

if(!listOfAccountsUpdated.isEmpty()){
    update listOfAccountsUpdated;
}   

}

  • Is there any reason you should perform update on after update trigger? Because, on after update you update Account and it calls trigger once more. You should consider using before update trigger, then you don't need to do dml update. Before triggers automatically handles updates on records of Trigger.New. – BlackCat Jul 29 at 10:34
2

Try to perform update in Before Update trigger.

The option to replace case insensitive regex in java is Pattern.CASE_INSENSITIVE, which can also be specified as (?i).

trigger changeAccountName on Account (before insert, before update) {
    String replaceToken = '(?i)\\test\\}';
    for (Account acc : Trigger.new) {
        if (acc.Name.containsIgnoreCase('test') && !acc.Name.containsIgnoreCase('test1')) {
            acc.Name = acc.Name.replace(replaceToken, 'test1');
        }
    }
}

Or you can try to implement it using Process Builder or workflow rule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.