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
Kunal Purohit 4Kunal Purohit 4 

How to write trigger?

Hi,
In my org, there are two objects Case and Project. Case object is having lookup relation with Project and Account Object. Now whenever, Case record is cretaed for particular Project, its asscoiated Account should get populated in case record. Plz help to write trigger for same.
Best Answer chosen by Kunal Purohit 4
Suraj Tripathi 47Suraj Tripathi 47
Hi Kunal,
You can take reference from this below code.
trigger CaseTrigger on Case (after insert) {
    if(trigger.isAfter && trigger.isInsert){
        Map<id,case> cas=new Map<id,case>([select accountid,projectid__c from case where id IN: trigger.new]);
        set<id> sid= new set<id>();
        for(case ca: cas.values()){
            if(ca.projectid__c!=null){
                sid.add(ca.projectid__c);
            }
        }
        map<id,project__c> proj=new Map<id,project__c>([select id,accountid__c,name from project__c where id IN: sid]);
        for(case ca: cas.values()){
            if(ca.projectid__c!=null){
                ca.AccountId = proj.get(ca.projectid__c).accountid__c;
            }
        }
        update cas.values();
    } 
}
In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

 

All Answers

mukesh guptamukesh gupta
Hi Kunal,

what is relationship between Project and Account?
Kunal Purohit 4Kunal Purohit 4
Hi Mukesh,
Project Object is having Lookup relation with Account.
Suraj Tripathi 47Suraj Tripathi 47
Hi Kunal,
You can take reference from this below code.
trigger CaseTrigger on Case (after insert) {
    if(trigger.isAfter && trigger.isInsert){
        Map<id,case> cas=new Map<id,case>([select accountid,projectid__c from case where id IN: trigger.new]);
        set<id> sid= new set<id>();
        for(case ca: cas.values()){
            if(ca.projectid__c!=null){
                sid.add(ca.projectid__c);
            }
        }
        map<id,project__c> proj=new Map<id,project__c>([select id,accountid__c,name from project__c where id IN: sid]);
        for(case ca: cas.values()){
            if(ca.projectid__c!=null){
                ca.AccountId = proj.get(ca.projectid__c).accountid__c;
            }
        }
        update cas.values();
    } 
}
In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

 
This was selected as the best answer