0

I have an external application inserting Contact records into the Salesforce (SFDC) instance. Within the external application there is no way to conditionally remove any records from the list so they don't create specific Contacts. If the external application needs to create 100 contacts, they will currently create 100 contacts (we can assume all required fields are set).

As a result, I have to conditionally remove the records as they come into SFDC, but before they get inserted into SFDC.

Question:

How do I conditionally remove records from the beforeInsert event when the external application attempts to insert records?

Goal(s):

  1. Any Contact where myField__c=false comes in from the external application then do not insert them.

What I tried, but didn't work

trigger ContactTrigger on Contact (Before insert) {
  if(Trigger.isInsert) {
     Integer numOfRecords = Trigger.new.size();
     for(Integer i = 0; i < Trigger.new.size(); i++) {
         if(Trigger.new[i].myField == false) {
              Trigger.new.remove(i);
         }
     }
  }
}
3

You can't "remove" these records; you'll specifically get a System.FinalException error for trying to modify Trigger.new's size in any way. By the time your trigger runs, the system has already started the DML, and it cannot be cancelled aside from setting an error.

You can prevent their creation using addError(msg), but the external application must also set the allOrNone flag to false or the entire transaction will roll back.

trigger ContactTrigger on Contact (Before insert) {
 Integer numOfRecords = Trigger.new.size();
 for(Integer i = 0; i < Trigger.new.size(); i++) {
     if(Trigger.new[i].myField == false) {
          Trigger.new[i].addError('Do not insert this record.');
     }
 }

}
| improve this answer | |

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.