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
NiknitNiknit 

How to create trigger to avoid duplication in the related lists of object at the time of insertion/updation.

heres the scenario

There is sobject Campaign - > under it is related list for custom object PD.There is two fields under PD - Campaign and Dlr

For pd object record creation there is two fields - Campaign(child) and Dlr field [both are lookup field - campaign to Campaign and Dlr to accounts]

What I want to create is trigger to throw error when user tries to create PD object record with a campaign lookup using the Dlr which is already in use with another campaign that got used for creating another PD before.

But I am not atall able to figure out to put in the relation between all thus finding hard to finish.

 

this is what i came up with, if anyone can, pls show me, thank you

 

 

set<id> CampaignId = new set<id>
for(PD__c i : trigger.old)
    campaignid.add(i.Campaign__c)

List<account> CampaignDlr= [Select id (Select id , Dlr__c from PD__c) from account where id in : CampaigniD]

for(PD__c i : trigger.new){

    for(account p : campaigndealer){

        if(i.dlr__c == p.dlr__c){
        I.adderror('Error');
        }

        }
      }
 

Ajay K DubediAjay K Dubedi
Hi Niknit,
Here is the Trigger Code written according to your requirements:-

Trigger:-
trigger PD_Trigger on PD__c (after insert,after update) {
    PD_Controller.createPD(trigger.new);
}

Controller:-
public with sharing class PD_Controller {
    public static void createPD(list<PD__c> newPDobj)
    {
        set<id> dlrId=new set<id>();
        map<id,list<PD__c>> PDidToPDmap=new map<id,list<PD__c>>();
        for(PD__c pdObj:newPDobj)
        {
            dlrId.add(pdObj.dlr__c);
        }
        list<PD__c> existingPD=[select Dlr__c,Campaign__c from PD__c where dlr__c in:dlrId];
        
        if(existingPD.size()>0)
        {
        for(PD__c pObj:existingPD)
        {
             if(!PDidToPDmap.containskey(pObj.dlr__c))
             {
              PDidToPDmap.put(pObj.dlr__c,new list<PD__c>());
             } 
              PDidToPDmap.get(pObj.dlr__c).add(pObj);
              PDidToPDmap.put(pObj.dlr__c,PDidToPDmap.get(pObj.dlr__c));
        }
        
        for(PD__c pObj:newPDobj)
        {
            if(PDidToPDmap.get(pObj.dlr__c).size()>1) 
            {
                pObj.dlr__c.addError('Same Dlr Not Allowed');
            }
        }
    }}
}

Regards,
Ajay
NiknitNiknit

Hi Ajay,

Sorry for the late reply.

Will really appreciate if you could please explain your code.

Just the flow thats it, please if you can.

Thanks

NiknitNiknit

Hi Ajay,

 

Can you please explain.