0

We have 2 custom objects Certificate_of_Insurance__c and Policy_Section__c and there is a lookup to Policy_Section__c field "HPL_Policy_Section__c". Trying to write a trigger to populate lookup field HPL_Policy_Section__c on Certificate_of_Insurance__c object based on SOQL list. I'm getting a compile error Variable does not exist: cert at line 15 column 40

trigger UpdateHPI on Certificate_of_Insurance__c (before insert) {

Set<id>ids=new set<id>();
list<Policy_Section__c> Pl =new list<Policy_Section__c>();
for(Certificate_of_Insurance__c  cert:trigger.new){
    if(cert.HPL_Policy_Section__c!=Null){
        ids.add(cert.HPL_Policy_Section__c); 
    }
}
if(!ids.Isempty()){
    list<Policy_Section__c> NewPL=[select id,name, Policy_Number__c from Policy_Section__c where HPL_COI_Policy_Section__c= TRUE AND Campus_Text__c = 'RUMC' AND id in:ids limit 1];
    for(Policy_Section__c policy: NewPL){

      for(Certificate_of_Insurance__c  bd: trigger.new){ 
       policy.HPL_Policy_Section__c= cert.id;    // this is where I'm getting compile error
      Pl.add(policy);
     }
   }
    update Pl;
  }

}

1
  • Apex variables are blocked scope. cert will only be available within foreach {-}. You need to refactor your code. You can eliminate nested loops as well. Commented Jan 12, 2021 at 5:01

1 Answer 1

1

Your code is incorrect in many ways.

  1. You are using before insert context to update other objects. This should be done in after insert.

  2. Your logic seems incorrect as the first loops takes all HPL_Policy_Section__c, but in second loop you are again trying to populate the same thing back

  3. You are using limit query in SOQL, what if there are multiple Policy_Section__c with different Ids, your code will only take the first one.

  4. Finally : cert.id; your scope of cert variable ended when you closed the bracket of first loop, so there is no cert variable in the second for loop, even of you were trying to do a bd.id, I would say that would be incorrect as your based on my 2nd point.

You must log in to answer this question.

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