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
gautamgautam 

Checking record existence based on some criteria in trigger

Hi..

I have scenario where I need to check existance of record in some custom  Object1 for each insertion of  records in another Custom  Object2 depending on 2 fields Combination  values.
There is another custom junction object exist between these objects which have a relation with both the object.
So, I need to check whether a record exist in Custom Object1 for specific combination of values inserted in custom object2.If exist I need to upadte the record in the Custom object1  with a field value of custom object2 .If not I have to insert a new record for those Combination field values in custom object1.

As the Combination of values to be checked is more it is becoming quite cumbersome and leading to use of lots of maps and list.

Can anyoone share a code or suggest how this could be acheived.

Cloud99Cloud99

Hi Gautam - As far as i've understood your problem:
 1. you have two objects a) object1__c and object2__c
 2. there are two fields let us say field1__c and field2__c that are in both the object. (they may have different name)
 3. you are inserting data in object2__c and checking if (corresponding to field1__c and field2__c there may or may not be a record in object1__c)
 4. Not sure about your third object (junction object), if you want to create a record for this object also.

Let us take an example for your case:

you'll need to have an insert trigger on object2__c

//this trigger is not optimized for number of soql queries
trigger object2Inset on object2__c (before insert){
    
    List<object1__c> toBeinserted = new List<object1__c>();
    List<object1__c> toBeUpdated = new List<object1__c>();
    for(Integer i=0;i<Trigger.new.size();i++){
        object1__c object1 = [select id, field1__c,field2__c from object1__c where field1__c =: Trigger.new[i].field1__c and field2__c =: Trigger.new[i].field2__c][0];//assuming only one record matched the criteria
        if(object1 != null)toBeUpdated.add(object1);
        else toBeinserted.add(object1);
    }

    if(toBeUpdated != null && toBeUpdated.size() > 0)update toBeUpdated;
    if(toBeinserted != null && toBeinserted.size() > 0)insert toBeinserted;
}