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

Before insert CreatedById Error



I have a custom field in Cases called Sales_Representative__c (Lookup to user). We want it to be updated by the OwnerID with the Region__c in User.Region__c


The code is a follows;


The Class


public with sharing class SalesRepRegion { 

	public static void updateSalesRepresantativeID (List<Case> caseList) {
		Set<id> CaseIds = new Set<id>();
			for(Case c: caseList){
			Map<Id, User> usersMap = new Map<Id, User>([Select Id, Region__c from User Where Id IN :CaseIds]);
			for (Case cs : caseList) {
				cs.Sales_Representative__c = usersMap.get(cs.CreatedById).id;
				cs.Region__c = usersMap.get(;



 The trigger


trigger beforeCase on Case (before insert, before update) { 

   List <Case> cs =;
       for (Case c: cs){



Thank you for your help


Your trigger calls the class for each row in the trigger, rather than just once (as the class expects).


What error do you actually get?


You are passing the CS iterable object of the for loop and should be passing c. However, to pass c you need to change the expected object in the class to (Case caseList). Doing this would call the class once per record thus causing you to hit governor limits after 100 records. The map in the class would always be filled with one and only one record.


Sorry, you are passing the List for each records, so if you hav 20 records in the trigger, you are calling the class 20 times with the full list.


You can just  do




by itself and not within any loops.