[SalesForce] Auto Populate parent Values in child fields using trigger

I have two objects Employee__C (Parent) and Leave_Request__c(Child) [M-D Relationship]

Employee__c has the fields:

      available_casual_leaves__c (Number(15,0))
      avilable_sick_leaves__c  (Number(15,0))

Leave_Request__c has the fields:

      available_casual_leaves__c (Number(15,0))
      avilable_sick_leaves__c  (Number(15,0))

I have to auto-populate the Employee__c field values in Leave_request__c i.e when I click on New Leave Request from the Employee__c details page. I wrote the trigger shown below, but the values are not getting populated into child page. The debug logs were showing correct results:

trigger prepopulateleaves on Employee__c (before update,before insert) 
{
    Map<Id, Employee__c> leaveWithDefaultvalues = new Map<Id, Employee__c>();

    if(checkRecursive.runOnce())
    {
        for (Integer i = 0; i < Trigger.new.size(); i++) 
        {
            leaveWithDefaultvalues.put(Trigger.old[i].id,Trigger.new[i]);
            System.debug('default values '+leaveWithDefaultvalues.keySet());
        }

        List<Leave_Request__c> updatedLeaves = new List<Leave_Request__c>();

        for (Leave_Request__c c : [SELECT id,employee__r.id,available_casual_leaves__c,
            available_sick_leaves__c FROM Leave_Request__c 
            WHERE employee__r.id in :leaveWithDefaultvalues.keySet()]) 
        {
            Employee__c parentAccount = leaveWithDefaultvalues.get(c.employee__r.id);
            c.available_casual_leaves__c = parentAccount.available_casual_leaves__c;
            c.available_sick_leaves__c = parentAccount.available_sick_leaves__c;
            updatedLeaves.add(c);
        }

        System.debug('values ' +updatedLeaves);
        update updatedLeaves;
    }
}

Could anyone help me out

Best Answer

First, do you need those fields on the child object in readonly mode ? if so you could use a formula field.

otherwise if you are looking to only auto-populate the child fields with the same values as parent values when you click on the new button, I suggest that you take a look at this blog poste