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
Srinivas223Srinivas223 

using map instead of list

I am trying to implement best practices in my trigger. I want to avoid writing a query in the loop but not getting the logic for it. can anyone please help?
I have a CSRid text field on contact and a badge__c text field in Employee object. I want to autofill employee lookup field on contact from contact trigger based on the CSRid on contact. This is the logic I have written which is working fine but couldnot avoid writing a query in the FOR loop. Please help.
Thank you

 list<contact> lstConid = new list<contact>();
    if(trigger.isUpdate && trigger.isBefore){
        for(contact con : trigger.new){
            if(con.CSRid__c != null){  //
                lstConid.add(con);
            }
        }
        if(!lstConid.isempty()){
            for(contact con: lstConid){
                if(con.CSRid__c != null){
                Employee_Table__c emp = [select id, name from Employee_Table__c where badge__c =: con.CSRid__c limit 1];
                if(emp.id != null)
                    con.SurveyEmployees__c = emp.id;
                }
            }
               
        }
        
     // map<lstCSRid, Employee_Table__c> CsrEmpMap = new map<lstCSRid, Employee_Table__c>([select Name from Employee_Table__c where badge__c in :lstCSRid]);
    }
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
list<contact> lstConid = new list<contact>();
    if(trigger.isUpdate && trigger.isBefore)
	{
	
		Set<String> setContCSID = new Set<String>();
		
        for(contact con : trigger.new)
		{
            if(con.CSRid__c != null){  //
				setContCSID.add(con.CSRid__c);
                lstConid.add(con);
            }
        }
        if(!lstConid.isempty())
		{
			List<Employee_Table__c> lstEmp =  [select id, name,badge__c from Employee_Table__c where badge__c in : setContCSID ];
			Map<String,Employee_Table__c> mapBadgeWiseEmp = new Map<String,Employee_Table__c>();
			for(Employee_Table__c emp : lstEmp){
				mapBadgeWiseEmp.put(emp.badge__c , emp);
			}
			
		
            for(contact con: lstConid)
			{
                if(con.CSRid__c != null && mapBadgeWiseEmp.containsKey(con.CSRid__c) ){
					Employee_Table__c emp = mapBadgeWiseEmp.get(con.CSRid__c);
					if(emp.id != null)
						con.SurveyEmployees__c = emp.id;
					}
            }
               
        }
        
     // map<lstCSRid, Employee_Table__c> CsrEmpMap = new map<lstCSRid, Employee_Table__c>([select Name from Employee_Table__c where badge__c in :lstCSRid]);
    }

Let us know if this will help you