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
Sabah FarhanaSabah Farhana 

Error in creating trigger

Hi all,

Iam getting an error in the line highlighted below.Is this the correct way to write it

trigger updateGroupLookup on Case (before insert) {
for (Case c : Trigger.new) {
  
      if(c.groupid__c!= null){
     
               
        
          c.group_Account__c = [select id from account where Group_ID__c =c.groupid__c];
    }
  }
Best Answer chosen by Sabah Farhana
Michael DsozaMichael Dsoza

Hi sabah,

1) Never use SOQL query in Loop (either Initialization level or inside loop)
2) Check for NULL at object level first then check for field otherwise it may throw NULL Pointer Exception
3) Try to use IN keyword for multiple id, do not use same query again and again for each id.

try below code,
trigger updateGroupLookup on Case (before insert) {
    List<Case> caseList = Trigger.NEW;
    for(Case c: caseList) {
        if(c != null && c.groupId__c != null) {
       

    }

}

Regards,
Michael

 

All Answers

Arunkumar RArunkumar R
It's a wrong way of coding.

1. You are using SOQL Inside the for loop.

2. Getting SOQL Result and assigning this to Field instead of object this is wrong.
The correct way is

List<Case> caseList = [select id from account where Group_ID__c =c.groupid__c];

3. Remove SOQL from for loop and use MAP or SET..
Michael DsozaMichael Dsoza

Hi sabah,

1) Never use SOQL query in Loop (either Initialization level or inside loop)
2) Check for NULL at object level first then check for field otherwise it may throw NULL Pointer Exception
3) Try to use IN keyword for multiple id, do not use same query again and again for each id.

try below code,
trigger updateGroupLookup on Case (before insert) {
    List<Case> caseList = Trigger.NEW;
    for(Case c: caseList) {
        if(c != null && c.groupId__c != null) {
       

    }

}

Regards,
Michael

 

This was selected as the best answer
Ramesh KallooriRamesh Kalloori
modify the query as below it will works.

c.group_Account__c = [select id from account where ID=:c.groupid__c].ID;

let me know error if it not works.