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
Lee_CampbellLee_Campbell 

Struggling to automatically populate a lookup field dependent on "CreatedBy"

I'm trying to write a Trigger that will automatically populate a lookup field with the Partner User's account when the partner creates a new record in a custom object. The Trigger I tried is thus:

 

trigger UpdateAccountName on Change_Request__c (after update) {
    for(Change_Request__c a : Trigger.old)
{a.Customer_Name__c = a.CreatedBy.Contact.AccountID; }
}

 I've tried various combinations of "old" and "new" and "before", "after", "update" and "insert", but I either get the error message below, when attempting to actually utilise the Trigger (there are no compiling errors), or the Trigger simply does nothing, but with no error message. Can anyone offer any guidance? Thanks!

 

Apex trigger UpdateAccountName caused an unexpected exception, contact your administrator: UpdateAccountName: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.UpdateAccountName: line 8, column 1

Best Answer chosen by Admin (Salesforce Developers) 
Gunners_23Gunners_23

You use the same code suggested by GreatG with before trigger . It should work,  try it and let us know whether the result

All Answers

MiddhaMiddha

try this:

 

trigger UpdateAccountName on Change_Request__c (after update) {
    
	Set<Id> userIds = new Set<Id>();

	for(Change_Request__c c: TRigger.new)
		{
			userIds.add(a.CreatedBy);
		}


	Map<Id, User> userMap = new Map<Id, User>([Select Id, Contact.AccountId from User where Id IN: userIds]);
	
	for(Change_Request__c a : Trigger.new)
		{
			a.Customer_Name__c = userMap.get(a.CreatedBy).Contact.AccountID; 
		}
}

 

tchrisbakertchrisbaker

I think you have to query for it. Something like this:

trigger UpdateAccountName on Change_Request__c (after update) {
	Set <ID> changeReqIds = new Set<ID>();
	for(Change_Request__c a : Trigger.old) 
	{
		changeReqIds.add(a.Id);
	}
	
	Change_Request__c [] changeReqests = [SELECT CreatedBy.Contact.AccountID FROM Change_Request__c WHERE Id IN :changeReqIds];
	
    for(Change_Request__c a : changeReqests)
	{
		a.Customer_Name__c = a.CreatedBy.Contact.AccountID; 
	}
}

 

Lee_CampbellLee_Campbell

Neither of these suggestions worked, I'm afraid folks. The former was met with the error message:

 

"Incompatible element type SOBJECT:User for collection of ID."

 

upon trying to compile.

 

The latter was met with no error message, but as with previous attempts the trigger appeared not to fire.

 

Very grateful for your help, but the search continues...

tchrisbakertchrisbaker

oops try mine with a before update instead of an after update.

 

If you're updating a record on the object where the trigger is firing, use before 

MiddhaMiddha

Lee, the code i wrote was just written in note pad hence not compiled. The purpose is to give you the idea how this works not to provifr you exact running code. Please fix the smaller issues that you face while compiling it. fixing the one you said:

 

trigger UpdateAccountName on Change_Request__c (after update) {
    
	Set<Id> userIds = new Set<Id>();

	for(Change_Request__c c: TRigger.new)
		{
			userIds.add(a.CreatedById);
		}


	Map<Id, User> userMap = new Map<Id, User>([Select Id, Contact.AccountId from User where Id IN: userIds]);
	
	for(Change_Request__c a : Trigger.new)
		{
			a.Customer_Name__c = userMap.get(a.CreatedById).Contact.AccountID; 
		}
}

 But again not tried to compile.

Lee_CampbellLee_Campbell

I tried both of those suggestions, and still nothing; I get the same error as I started with if I make your correction, Gulshan (so it would appear mapping isn't the answer if we're back where we started after adding several lines of code), and the trigger still doesn't fire if I make your correction, Chris.

Does it have something to do with "CreatedBy", do you reckon? I mean, when does a record know who it was created by? Is it before or after it's inserted?I know that shouldn't matter for "after update", but I can't for the life of me figure out why none of the three lots of code we've suggested work...

tchrisbakertchrisbaker

That is a good question about when it knows who it's created by. Try leaving it on after update and adding an update statement.

 

If you are doing an after update you need to do the update statment. So in my example:

update changeReqests;

 

just put thate statment at the very end

 

Also in the code I posted try using trigger.new instead of trigger.old

Gunners_23Gunners_23

You're trying to update the record in "After Update" context, in which all the records would be Read-only.

 

Change it to "Before Update" and try it out.

Lee_CampbellLee_Campbell

I get a shiny new self-referencing error by adding the "update changeRequests;" line (while the Trigger is set to fire "before"):

 

Apex trigger UpdateAccountName caused an unexpected exception, contact your administrator: UpdateAccountName: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a02E0000002fjpMIAQ; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a02E0000002fjpM) is currently in trigger UpdateAccountName, therefore it cannot recursively update itself: []: Trigger.UpdateAccountName: line 13, column 1

 

Also, changing from "after" to "before" gets rid of the "read-only" error (without including the final "update" line), but the Trigger still does not fire (I've literally tried every permutation of "new", "old", "before" and "after"). When including the final "update" line when the Trigger is set to fire "after", I get an infinite loop kind of an error:

 

Apex trigger UpdateAccountName caused an unexpected exception, contact your administrator: UpdateAccountName: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a02E0000002fjpMIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateAccountName: maximum trigger depth exceeded Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM] Change_Request trigger event AfterUpdate for [a02E0000002fjpM]: []: Trigger.UpdateAccountName: line 13, column 1

 

Which was nice. Proper head-scratcher this one... Massively appreciative of your help so far though, folks!

 

Lee

Gunners_23Gunners_23

Post the update code. And you don't have to use "Update" again in the trigger ( the reason being You cannot Use any Kind of

 

DML operation on same object. But you can do for other). After inserting this are you trying to insert/Update any other object

 

based on this? Can you post the Change_Request Trigger?

Lee_CampbellLee_Campbell

Okay, so here's the code:

 

trigger UpdateAccountName on Change_Request__c (before insert, before update){
    Set<ID> changeReqIDs = new Set<ID>();
    for (Change_Request__c a:Trigger.new){
        changeReqIDs.add(a.Id);
    }
    Change_Request__c [] ChangeRequests = [SELECT CreatedBy.Contact.AccountID
                                           FROM Change_Request__c 
                                           WHERE Id IN : changeReqIDs];
    for (Change_Request__c a: ChangeRequests){
        a.Customer_Name__c = a.CreatedBy.Contact.AccountID;
        
    }
    
 }

Which causes the Trigger not to fire. Inserting the line "update ChangeRequests;" before the final brace causes the errors described in my last post.

Lee_CampbellLee_Campbell

Also, no. No updates are further based on the result of this Trigger.

Gunners_23Gunners_23

You use the same code suggested by GreatG with before trigger . It should work,  try it and let us know whether the result

This was selected as the best answer
Lee_CampbellLee_Campbell

Yes! Get in!

 

I could've sworn I tried that. What a fool.

 

Thanks very much, you're all life-savers!

 

Lee