Skip to main content
edited title
Link
Egypte
  • 31
  • 1
  • 8

Prevent Duplicates Using Wrapper Class in Apex TriggerClass

Source Link
Egypte
  • 31
  • 1
  • 8

Prevent Duplicates Using Wrapper Class in Apex Trigger

Note* I am a beginner attempting to jump from level 1 to level 10 coding because there is no easy way to accomplish the task.

I need to prevent users from inserting duplicates of a custom object based on two related object lookup fields. The best way to accomplish this is to wrap them into a class so apex is not mixing up the values during batches. I have successfully created a wrapper class but I cannot seem to pass and evaluate the list properly. I am getting the following errors:

  1. Error:Constructor not defined: [ChangeOrderTriggerHandler.ChangeOrderWrapper].()
  • From my understanding, I do not have a constructor set up for this type but I cannot find documentation to help guide me into creating this?
  1. Error:Comparison arguments must be compatible types: Id, Object
  • I don't quite understand this as the comparisons are both using id.field

If this is all incorrect I wouldn't be surprised, just let me know. Thanks in advance!

public with sharing class ChangeOrderTriggerHandler {
    public class ChangeOrderWrapper{
        public Asset ast {
            get ; private set;
        }
        public Opportunity opp {
            get ; private set;
        }

        public ChangeOrderWrapper(Asset a, Opportunity o) {
            this.ast = a;
            this.opp = o;
        }
    }

    public List<ChangeOrderWrapper> wrapperList {
        get ; private set;
    }

    public ChangeOrderTriggerHandler() {
        Map<Id, Asset> astMap = new Map<Id, Asset>
            ([SELECT Id FROM Asset WHERE Id IN (SELECT Asset__c FROM Change_Order__c WHERE Status__c = 'Open' )]);
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>
            ([SELECT Id FROM Opportunity WHERE Id IN (SELECT Opportunity__c FROM Change_Order__c WHERE Status__c = 'Open' )]);
        List<Change_Order__c> cOrders = [SELECT Asset__c, Opportunity__c FROM Change_Order__c WHERE Status__c = 'Open'];

        this.wrapperList = new List<ChangeOrderWrapper>();

        for(Change_Order__c co : cOrders)
        {
            this.wrapperList.add(new ChangeOrderWrapper(astMap.get(co.Asset__c),oppMap.get(co.Opportunity__c)));
        }
        system.debug('wrapperListSize-->'+this.wrapperList.size());
        system.debug('wrapperList-->'+this.wrapperList);

    }
    public static void ChangeOrderDuplicateChecker(List<Change_Order__c> cos)
    {   ChangeOrderWrapper cow = new ChangeOrderWrapper();

            for(Change_Order__c co : trigger.new)
            {
                if(co.asset__c == cow.ast && co.opportunity__c == cow.opp)
                {
                    co.addError('Testing');
                }
            }
    }

}