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
_tofu_tofu 

Trigger updating self referenced lookup records

I'm trying to write trigger that updates records specified in a self referenced lookup.

 

My example would be seats in a theatre and their are two self-referenced fields. One lookup for "Seat To Left" and lookup for "Seat To Right." I want to write a trigger that updates the records you're specifying as lookups.

 

User scenario would be something like the user is updating 192. The user marks "Seat to the Left" as 191. I want the trigger to go to seat 191 and update it's "Seat to the Right" field as being 192, so the user doesn't have to mess around too much.

 

Really roughly, something like this:

 

trigger SeatTrigger on Seat__c (before insert, before update) {
	
	List<Seat__c> triggerSeatsUpdate = new List<Seat__c>(); 
	
	for (Seat__c triggerSeat : Trigger.new) {
		if(triggerSeat.Seat_To_Left__c != null) {
			Seat__c seatToTheLeft = new Seat__c();  
			seatToTheLeft.Id = triggerSeat.Seat_To_Left__c;
			seatToTheLeft.Seat_To_Right__c = triggerSeat.Id;
			triggerSeatsUpdate.add(SeatToTheLeft); 	
		}
		if(triggerSeat.Seat_To_Right__c != null) {
			Seat__c seatToTheRight = new Seat__c(); 
			seatToTheRight.Id = triggerSeat.Seat_To_Right__c;
			seatToTheRight.Seat_To_Left__c = triggerSeat.Id;
			triggerSeatsUpdate.add(SeatToTheRight);
		}
	}
	
	update triggerSeatsUpdate;

}

 Except using an update this way won't work. I don't think I could just add the records to the trigger.new either. Is there a solution for this problem?

Best Answer chosen by _tofu
GunnarGunnar

Given what you know about the seat to the left, create a new list(or single object) and use what you know in a new SELECT... WHERE.

Now in a separate list/or object, you have the seat to the left. This can be updated and saved.

All Answers

GunnarGunnar

Well one issue ...

 

You cannot set id's.

 

seatToTheLeft.Id = triggerSeat.Seat_To_Left__c; // <<<< can't do that.
GunnarGunnar

Given what you know about the seat to the left, create a new list(or single object) and use what you know in a new SELECT... WHERE.

Now in a separate list/or object, you have the seat to the left. This can be updated and saved.

This was selected as the best answer