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
SFDC-NOOBSFDC-NOOB 

Trigger help with data loader

Hello apex experts,

 

I have a field on the account object that updates when the account is edited.  When the record is edited individually, the correct value gets written to the field.  When I use the data loader . . . One value applies to all records.  Here is my trigger, please advise.

 

trigger Populate_Transfer_Manager on Account (before insert, before Update) {   
   
    list<id> aid = new list<id>();
    for(account a: trigger.new){           
        aid.add(a.ownerid);
    }
    
list<user> managers = new list<user>();
    managers = [select managerid from user where id in: aid];
   

set<id> manid = new set<id>();                             
    for(user u: managers){
        manid.add(u.managerid);
    }
   

for(account a: trigger.new){        
    for(id i: manid){           
            a.transfer_manager__c = i;       
        }
    }
}

Best Answer chosen by Admin (Salesforce Developers) 
SFDC-NOOBSFDC-NOOB
I needed to use a map and bulkify the trigger. A little more research was needed on my end. :D

Turns out this was a simple task!

trigger Populate_Transfer_Manager on Account (before insert, before Update) {

list<id> aid = new list<id>();
for(account a: trigger.new){
aid.add(a.ownerid);
}
map<id, user> users = new map<id, user>(
[select managerid from user where id in: aid]);

for(account a: trigger.new){
a.Transfer_Manager__c = users.get(a.ownerid).managerid;
}
}

All Answers

SFDC-NOOBSFDC-NOOB
I needed to use a map and bulkify the trigger. A little more research was needed on my end. :D

Turns out this was a simple task!

trigger Populate_Transfer_Manager on Account (before insert, before Update) {

list<id> aid = new list<id>();
for(account a: trigger.new){
aid.add(a.ownerid);
}
map<id, user> users = new map<id, user>(
[select managerid from user where id in: aid]);

for(account a: trigger.new){
a.Transfer_Manager__c = users.get(a.ownerid).managerid;
}
}
This was selected as the best answer
jungleeejungleee

You could do something like this;

 

trigger Populate_Transfer_Manager on Account (before insert, before Update) {   
   
    set<id> aid = new set<id>();
    for(account a: trigger.new){           
        aid.add(a.ownerid);
    }
   
	//add the user with the managers in the map.   
	   map<id, user> userManagersMap = new map<id, user>([select managerid from user where id in: aid and Managerid <> null]);
	
	//Iterate thru the accounts and add the manager's value to your field
	for(account a: trigger.new){ 
		//Check if the account's owner is present in the map
		if(userManagersMap.containsKey(a.ownerId)){
			a.transfer_manager__c = userManagersMap.get(a.ownerId).managerId;
		}
	}
}