0

I have 3 objects. Child__c is junction object, ParentA__c is master object, Parentb__c master object.

So Child__c (Many to Many relationship) is junction object between ParentA__c and ParentB__c. In Child__c i have 2 date fiels Startdate, Enddate.

while creating a junction object record need to maintain uniqueness using ParentA__c, ParentB__c and range of Startdate and Enddate.

example : dd/mm/yyyy

Record1: startdate  10/06/2016  enddate 10/07/2016 save record sucessfully          
Record2: startdate  10/06/2016  enddate 02/07/2016 need to give error message 
Record1: startdate  20/06/2016  enddate 20/07/2017 save record sucessfully
Record2: startdate  20/06/2016  enddate 01/07/2016 need to give error message

For this i wrote below sample code. Please help me bulkify

trigger Jundupcheck on Child__c (before insert) {
    for (Child__c  ci : trigger.new) {
        // We only care if there is one record<br>      
        List<Child__c> resultList = [SELECT id,Name,Enddate__c,StartDate__c,(selected id) FROM Child__c WHERE ParentA__c = :ci.ParentA__c AND ParentB__c = :ci.ParentB__c and ((StartDate__c >= :ci.StartDate__c AND StartDate__c <= :ci.EndDate__c) OR (endDate__c >= :ci.StartDate__c AND endDate__c <= :ci.endDate__c))];
        // Raise the error back if any records found    
        if (resultList.size()>0) {
            ci.addError('Duplicate record, a Affisiation already exists for that combination');    
        }
    }
}

1 Answer 1

2

First thing is first, you will need to pull that SOQL statement out of the For Loop. So you'll want to collect the ParentA__c and ParentB__c and then do your SOQL.

Set<Id> aParents = new Set<Id>();
Set<Id> bParents = new Set<Id>();

for(Child__c ci : trigger.new) {
    aParents.add(ci.ParentA__c);
    bParents.add(ci.ParentB__c);

}

List<Child__c> resultList = [SELECT Id, Name, Enddate__c, StartDate__c FROM Child__c WHERE ParentA__c IN :aParents ANd ParentB__c IN :bParents];

I'm still not entirely clear on how the dates make a record unique, but you'll have to do the processing for those after you make the SOQL query.

Note: In the case where you have more than 1 child object being inserted it is possible that the resultList will have records with either ParentA__c or ParentB__c not matching your Child__c record so you will have to double check those as well.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .