function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
itayfitayf 

Can I avoid whole trigger rollback on unsuccessful insertion?

Hello,

 

Is there any way (a supported way or a tricky workaround) to make Salesforce not to rollback changes done in the trigger eventhough the insertion failed?

 

Sometimes I want to fail the insertion (addError on the sObject) but I want other changes done in the trigger to still happen.

 

For example:

trigger triggerName on Contact (before insert) {
    Contact newContact = Trigger.new[0];
    Contact existingContact = [Select FirstName From Contact Where Id = 'someId'];
    existingContact.FirstName = newContact.FirstName;
    update existingContact;
    insert new Account(Name='newAccount');
    newContact.addError('errorName');
}

In this case, when adding a contact, the update of exisitingContact and the insertion of newAccount will be rolled back...

I do want those changes to occur, eventhough I want the newContact not to be inserted.

 

Playning with opt_allOrNone didn't seem to have any effect.

 

Thanks in advance!

Itay

LegendLegend

Hi,

 

Have you tried using 'try-catch-finally' block?

Put all your statments which you want to execute even after the exception in finally block.

itayfitayf

Thanks for you response!

 

I tried both:

Database.DMLOptions dlo = new Database.DMLOptions();
dlo.optAllOrNone = false;
Contact newContact = new Contact(LastName='newLast', FirstName='newFirst');
newContact.setOptions(dlo);
List<Account> accList;
try{
	insert newContact;
}catch(DMLException e){
	// nothing
}finally{
	accList = [Select Name from Account Where Name = 'newAccount'];
	system.debug(accList.size()); // print 0
}
accList = [Select Name from Account Where Name = 'newAccount'];
system.debug(accList.size()); // print 0

 and:

Contact newContact = new Contact(LastName='newLast', FirstName='newFirst');
List<Account> accList;
Database.SaveResult sr = Database.insert(newContact, false);
accList = [Select Name from Account Where Name = 'newAccount'];
system.debug(accList.size()); // print 0

 

Any other thoughts?

 

Thanks!

Itay