• Flywheel Strategic
  • NEWBIE
  • 10 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
Hi there,

I have created an Apex trigger for my organization and deployed it to production and it seems to be conflicting with my attempts to update a bunch of records in Data Loader.

We have a custom object that governs a special form, which I will call Forms__c (it is not actually named Form), and we have put on this object a trigger to prevent duplicates from being created. On create or update, the trigger checks the name of a given record, which will always be a 4-digit number, and returns an error if the number/name is already in use.
 
trigger FormNumberDuplicate on Form__c (before insert, before update) {
    list<id> formId = new list<id>();
    list<string> formNumber = new list<string>();
    
    if (Trigger.isInsert || Trigger.isUpdate) {
        for (Form__c t : Trigger.New) {
            System.debug(t);
            formId.add(t.Id);
            formNumber.add(t.Name);
        }
        
        List<Form__c> allForms = [SELECT Id, Name FROM Form__c WHERE IsDeleted = false];
        Integer flag = 0;
        for(Form__c t : allForms) {
            System.debug(t);
            if(!formId.contains(t.Id)) {
                if(formNumber.contains(t.Name)) {
                   flag = flag+1; 
                }
            }
        }
        System.debug(flag);
        if(flag > 0) {
            for(Form__c t : Trigger.New) {
                t.Name.addError('This Form number is already in use.');
            }
        }    
    }
    
    
}

The trigger works as intended: if a user tries to create a Form and uses the same number, it prevents them from entering a duplicate of the form and it tells them the form number is already in use.

However, I was trying to bulk update these Form__c records today with data from an external source, and ran into the issue where every single Form__c record would not update and threw the error in this trigger.

What am I missing here?

Thanks.