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
catapangfercatapangfer 

two object that will update with one trigger

Hi all,

 

I am new to apex trigger i have a situation here and hoping for your quick response.

 

i have two custom objects here Exercise__c and Trainee__c, in Exercise__c i have a field of exercise1(number), exercise2(number)exercise3(number), exercise name and a lookup field of trainee name in Trainee__c object while in the Trainee__c i have a fields of trainee name and status(picklist).

 

i want to validate the 3 fields in the Exercise__c if the sum of 3 fields is less than 75 the status picklist field in Trainee__c will update to Fail and if it isgreater than 75 it will update to Pass.

 

 

Thank.

SLockardSLockard

You might have to change the field names a little but, but try something like this:

 

trigger exerciseTrigger on Exercise__c(after insert, after update)
{
	Map<Id, Exercise__c> exMap = new Map<Id, Exercise__c>();
	List<Trainee__c> trainers = new List<Trainee__c>();
	
	if(Trigger.isInsert)
	{
		for (Exercise__c ex : Trigger.New)
		{
			if (ex.exercise1__c != null && ex.exercise2__c != null && ex.exercise3__c != null && ex.Trainee_Field__c != null)
			{
				exMap.put(ex.Trainee_Field__c, ex);
			}
		}
	}
	else
	{
		for (Exercise__c ex : Trigger.New)
		{
			Exercise__c oldEx = Trigger.oldMap.get(ex.Id);
			
			if (ex.exercise1__c != null && ex.exercise2__c != null && ex.exercise3__c != null && ex.Trainee_Field__c != null)
			{
				if (ex.exercise1__c != oldEx.exercise1__c || ex.exercise2__c != oldEx.exercise2__c || ex.exercise3__c != oldEx.exercise3__c)
				{
					exMap.put(ex.Trainee_Field__c, ex);
				}
			}
		}
	}
	
	if (exMap.size() > 0)
	{
		trainers = [SELECT  Id, Status__c FROM Trainee__c WHERE Id IN : exMap.keySet()];
		
		if (!trainers.isEmpty())
		{
			for (Trainee__c t : trainers)
			{
				Integer score = exMap.get(t.Id).exercise1__c + exMap.get(t.Id).exercise2__c + exMap.get(t.Id).exercise3__c;
				if (score < 75)
				{
					t.Status__c = 'Fail';
				}
				else
				{
					t.Status__c = 'Pass';
				}
			}
			
			update trainers;
		}
	}
}

 Good luck