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
realtimetasks1.3941822547955107E12realtimetasks1.3941822547955107E12 

trigger for updating parent object

hi i have two objects known as employee and department having relationship.if i update deparment name in the departmnet object automatically emp name should be updated using triggers.can anyone help me for this code
Sonam_SFDCSonam_SFDC
Hi,

Please go through the following link - this has cde snippet to explain how you can update the parent fields when a record on child is created/updated:
https://developer.salesforce.com/forums/ForumsMain?id=906F000000090cFIAQ
kaustav goswamikaustav goswami
Hi,

Can you please elaborate your requirement a bit further. Please specify the parent and the child object and the fields you want to update.
For the time being you can refer to the following code to get an idea of bulk handled triggers.

trigger updateEmp on Department__c (before update){

// declare a set and store the ids of the department records whose name have been updated
Set<Id> depIds = new Set<Id>();

// iterate over all chnaged department records and add the Id to the set only if the name field has been changed
for(Department__c var: Trigger.newMap.values()){
  Department__c oldVar = Trigger.oldMap.get(var.Id);
  if(oldVar.Name != var.Name){
   depIds.add(var.Id);
  }
}

// query the related employee records
List<Employees__c> empList = new List<Employees__c>();
empList = [SELECT Id, Name, Department_Name__c FROM Employees__c WHERE Department_Name__c IN:depIds];
if(!empList.isEmpty()){
  // update emp name
  for(Employee__c var : empList){
   // update whatever fields you need on the employee object
   // make sure they are included in the SOQL query
   var.Name = 'New Name for Employee';
  }
  // update the list
  try{
   update empList;
  }catch(Exception ex){
   System.debug('#### Error #### ' + ex.getMessage());
  }
}
}