1

I wonder how to remove an item from insertion.

I want to avoid the insertion of contact with lastName = 'B' but insert the others, How can I do it?, adding an error with

record.addError

is a "all or none" so there are no way to avoid the insertion of a single record,

Trigger.New.remove(1);

doesn't work because it is a only read collection (and it makes very sense because there is also a Trigger.NewMap referencing the same item)

I will place some code because I think is the best way to explain:

Trigger on Contact

trigger AvoidB on Contact (before insert) {

    for(Contact c : Trigger.new){

        if(c.lastName == 'B'){
            //c.addError('Is a B');

            Trigger.New.remove(1);
        }

    }
}

Execute console

List<Contact> c = new List<Contact>();
c.add(new Contact(lastName = 'A'));
c.add(new Contact(lastName = 'B'));
c.add(new Contact(lastName = 'A'));
c.add(new Contact(lastName = 'A'));
c.add(new Contact(lastName = 'A'));

insert c;
2

The problem isn't with addError() as much as it is with insert.

That all or nothing behavior that is causing the entire batch to fail can be avoided by using Database.insert(c,false); instead of insert c;

The SaveResult class page in the documentation has a good overview of this pattern.

4
  • But I want to allow the items to be inserted and avoid the ones that doesn't match, all from the trigger , Are there any way? – David Marciel Apr 5 '17 at 9:32
  • I'm pretty sure the all or nothing behavior of a DML operation can only be determined when the call is initiated. – martin Apr 5 '17 at 9:52
  • Ok, so in response to my question there are no way to avoid the insertion of a single item once in the trigger. – David Marciel Apr 5 '17 at 10:23
  • Right, all the trigger can do is mark a record as having an error, it can't remove the record from the list of records being inserted. – martin Apr 5 '17 at 11:21

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.