[SalesForce] Update parent field with field from child record

I have two managed custom object, so I can use master detail relationship to update the field on the parent record.

For example:

Object 1 – Parent__c
Field – Firmware__c
Object 2 – Child__c
Field – Firmware__c

I just want to create a custom button to update the firmware field of the parent record with the firmware field in the child record. This way, my users can choose which child record to update the parent record with. How can I achieve this?

Best Answer

I would create a custom button on the child object page layout. This button would open a VF page. I would use the action attribute of that page to do this logic, and then return the user to the child record.

VF

<apex:page StandardController="Child__c" extensions="customExtension" action="{!copyFirmwareField}"/>

Apex

public class customExtension{

     private final Child__c myChild;

     public CheckForExpiredMilestonesNowExtension(ApexPages.StandardController stdController){
          this.myChild = (Child__c)stdController.getRecord();
          this.myChild = [Select Id, Name, Parent__c From Child__c Where Id =: myChild.Id];
     }

     public PageReference copyFirmwareField(){
          Parent__c parent = new Parent__c(Id = myChild.Parent__c, Firmware__c = myChild.Firmware__c);
          update parent;
          PageReference page = new PageReference('/' + myChild.Id);
          page.setRedirect(true);
          return page;
     }
}
Related Topic