+ Start a Discussion
DivyanshD SinghDivyanshD Singh 

writing Trigger for 3 related objects (all lookups)

obj A mandatory lookup to obj B,obj C mandatory lookup to obj B , obj A lookup to obj C (not mandatory)...Provided this i have the following requirement.....if A created check whether obj C exists for obj B or not...if not create one and also link obj A to C.
there is a date time field in obj A and obj C...We need to check whether their d/f is more thasn 12 hrs or not..if yes create record in obj C if no simply link Obj A to obj C (link the records)....given obj 1- photo , obj 2 - asset , obj 3- asset visit
my trigger goes like this but not working as expected..

 
trigger createAV on AUDIT__c (after insert) {
​​​​​​​  
    list<ASSET_VISIT__c> assetVisit=new list<ASSET_VISIT__c>();
    list<AUDIT__c> listphoto=new list<AUDIT__c>();
    set<id> setAid=new set<id>();
    set<id> setAVid=new set<id>();
    for(AUDIT__c ph:Trigger.new){
        setAid.add(ph.ASSETS__c);
    //  setAVid.add(ph.ASSET_VISIT__c);
    }
    list<ASSET_VISIT__c> listAsset=[select id,name,FIRST_PHOTO_TAKEN__c from ASSET_VISIT__c where id=:setAid];
    
    //   for(integer i=0; i<=; i++){
    for(ASSETS__c a:[select id,name,PLANT__c from ASSETS__c where id=:setAid]){
        for(AUDIT__c p:Trigger.new){
            if(listasset.size() != 0 ){
                ASSET_VISIT__c ab=new ASSET_VISIT__c();
                if(p.PHOTOGRAPH_TAKEN__c !=null &&  p.PHOTOGRAPH_TAKEN__c.addhours(12)  > p.ASSET_VISIT__r.FIRST_PHOTO_TAKEN__c){
                    //            ASSET_VISIT__c ab=new ASSET_VISIT__c();
                    ab.ASSETS__c=p.ASSETS__c;
                    ab.PLANT__c=p.ASSETS__r.PLANT__c;
                    assetvisit.add(ab);
                    insert assetvisit;
                    update assetvisit;
                }
                else{
                    p.ASSET_VISIT__c=ab.Id;
                    p.ASSETS__c=a.Id;
                    listphoto.add(p);
                    update listphoto;
                }
            }
            else {
                ASSET_VISIT__c av=new ASSET_VISIT__c();
       //       ASSETS__c a=new ASSETS__c(); 
                av.ASSETS__c=a.id;
                av.PLANT__c=a.PLANT__c;
        //      p.ASSET_VISIT__c=av.Id;
                av.Id=p.ASSET_VISIT__c;
                assetVisit.add(av);
            }
            insert assetVisit;         
            update assetVisit;   
        }
    }
}