0
votes

I have a custom object called ‘FinanceCapture’, it has a lookup field to Account and a field called Contract_Term. I am trying to write a Apex Trigger to make the value of Contract_Term equal to the Contract Term value in Contract Object.

Draft the following code, but it's not working, needs your help please. Thanks

trigger populate_record on FinanceCapture__c (before insert) {
    List<Contract> ContractList = new List<Contract>();


    Map<Id,FinanceCapture__c> fin = new Map<Id,FinanceCapture__c>(
        [SELECT Id, FinanceCapture__lookup_Account__c FROM FinanceCapture__c WHERE Id IN :Trigger.New]);

    for (FinanceCapture__c a : Trigger.new){

//in Contract object, if its account ID matches with the account ID in FinanceCapture object, make the Contract_Term__c same as ContractTerm value

        If (ContractList.AccountId == fin.get(a.TMS_lookup_Account__c)){
            a.Contract_Term__c = ContractList.ContractTerm
        }
    }
}
1

1 Answers

0
votes

A few things, Your contractList object does not seem to be populated with anything it's just an empty list, therefore, the 'if' statements condition here ContractList.AccountId == fin.get(a.TMS_lookup_Account__c) is not ever going to work, not only because its an empty list but because you are trying to access a the accountId of a list of contracts which will not work also. Another thing is you use two different fields on FinanceCapture__c as your account lookup field the first FinanceCapture__lookup_Account__c in the SOQL Query and the second TMS_lookup_Account__c when checking the contract accountid with the FinanceCaptures accountId. You need to make clear exactly what you are trying to do which seems to be...

  1. Get a list of Contract records where the accountId is contained in the list of accountId's from the trigger.new list of FinanceCapture__c records.
  2. For all the FinanceCapture__c records, where a Contract has been found for the given account id, set the contract_term__c field to the corresponding Contract records contractTerm field

Here is the trigger which should achieve that (I used FinanceCapture__lookup_Account__c as the lookup fields name)

trigger populate_record on FinanceCapture__c (before insert) {
    Map<Id, FinanceCapture__c> accountIds = new Map<Id, FinanceCapture__c>();

    for(FinanceCapture__c fin : trigger.new){
        accountIds.put(fin.FinanceCapture__lookup_Account__c, fin); //Add financeCapture Record to map with its accountId as the key
    }

    //Create a list of contracts with Id's in the set of id keys from account -> financeCapture map
    List<Contract> contractList = [SELECT id, contractTerm, accountId FROM Contract WHERE accountId IN :accountIds.keyset()];

    for(Contract contract : contractList){
        //Get the FinanceCapture record using the contracts accountId and
        //Set the Contract term fields to be equal
        accountIds.get(contract.AccountId).contract_Term__c = contract.ContractTerm;
    }
}