+ Start a Discussion

field to update another field on a different object

distribution is a custom object distribution__c. I created a custom
 checkbox field quantity__c in this object. I want this field to updated another checkbox  field  called supplied__c on account object . That is, if  quantity__c is true and checked, supplied__c will also be true and checked. Also, for other records that already exist, how do I update this these records . Thank you
Santosh K SamudralaSantosh K Samudrala
Hi Sten,

Below should meet your requirement , Place this code in a method and call this on afterupdate context of trigger on Distribution object.

Please let me  know in case of any questions.

Map<ID,distribution__c> newRecordsMap = trigger.newMap; 
Map<ID,distribution__c> oldRecordsMap = trigger.oldMap; 

List<distribution__c> newList = new List<distribution__c>();
List<ID> accIDLst = new List<>(ID);
List<Account> accLstToUpdate = new List<Account>();

/* Below is to identify the distribution records on which the quantity value is changed , if the quantity is changed on update and set to true , capture the account id in a list */
for(ID recID:newRecordsMap.keySet()){

    if((newRecordsMap.get(recID).distribution__c) && ((newRecordsMap.get(recID).distribution__c) != (oldRecordsMap.get(recID).distribution__c)) {
/* If the Account ID List size is greater than 0 , it means quantity is changed on a distribution and its account needs to be updated

    for(Account accRec : [select ID ,supplied__c from account where ID in : accIDLst and  supplied__c = false]){

        accRec.supplied__c = true; // update the required flag and copy the account into a list

    if(accLstToUpdate.size()>0){ // If the List of accounts to be updated is greater than zero  ,perform an update on the List of Accounts to be updated.

        update accLstToUpdate;