+ Start a Discussion
bhaskar reddy kbhaskar reddy k 

regarding triggers

Hi all,
          can any body help me on this,i have two objects Employee_DB__c(parent) and Employee_Address__c(child).my requirement is in parent and child there is a field called Country__c field is there,when ever the user wants to insert a new record or update the exsting record with country field , the country field of the child should be updated with parent country value.
thanks in advance.
venkat-Dvenkat-D
The simple way can be to create a formula field on Employee Address that references Country field from Employee. Why do you want to populate value using triggers?
Rakesh51Rakesh51
Best possible solution is to use Proces builder to sync cuntry field of the child record with parent country value
Ajay K DubediAjay K Dubedi
Hi bhaskar,
The following trigger will update the new value of Country__c in all its child object whenever you will change the value in Parent Object.
 
trigger toUpdateCountryfield on Employee_DB__c (after insert,before update) {
List<Employee_DB__c> EmployeeList = new List<Employee_DB__c>();
List<Employee_Address__c> EmployeeaddressList = new List<Employee_Address__c>();
map<id,string> mapofIdandCountry =new map<Id,string>();
set<Id> SetofparentId = new set<Id>();

for(Employee_DB__c emp : trigger.new){
mapofIdandCountry.put(emp.Id,emp.Country__c);
SetofparentId.add(emp.Id);
}

EmployeeaddressList = [SELECT Id,Country__c,Employee_DB__c FROM Employee_Address__c where Employee_DB__c in :SetofparentId];
for(Employee_Address__c eadd : EmployeeaddressList){
eadd.Country__c = mapofIdandCountry.get(eadd.Employee_DB__c);
}

update EmployeeaddressList;

}

Now if you want that when you create a new child object (Employee_Address__c), its Country__c field should automatically fill according to its Parent, then you have to use one more trigger. This trigger will be on child Object :
 
trigger toUpdateCountryfield2 on Employee_Address__c (after insert) {   
    List<Employee_Address__c> EmployeeaddressList = new List<Employee_Address__c>();
    set<Id> SetofchildId = new set<Id>();
for(Employee_Address__c eadd: trigger.new){
        SetofchildId.add(eadd.Id);
    }
    EmployeeaddressList = [SELECT Id,Country__c,Employee_DB__r.Country__c FROM Employee_Address__c WHERE Id in :SetofchildId ];
    for(Employee_Address__c ead :EmployeeaddressList){
    ead.Country__c = ead.Employee_DB__r.Country__c ;
}
    update EmployeeaddressList;
}

Regards,
Ajay