function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
David JobeDavid Jobe 

how to write apex code to match two different ojects

Hello,
I am making the transition from Admin to Developer, and I am working on building an Apex Class. Still very new at it. Very.
What I am trying to do is to build code that when a new Account is added, that the system goes and checks the Contracts Object to see if there is a matching Contract to that Account (sometimes Accounts will not have a contract). Normally, I would do this with Access beforehand, but the base files are getting to large for both contracts and accounts. 
What I need is that the code pulls the new account, checks that it has something in the Contract Number Custom Field (Contract_Number__c). If it does, it pulls all the Contracts and does basically a VLOOKUP against the custom field Bg Contract Number (BG_Contract_Number__c). If it finds a match, it fills in the Account lookup field on Contracts. 
Any help would be greatly appreciated.
Best Answer chosen by David Jobe
Ron ReedRon Reed
Is there a 1-1 relationship from Contracts to Account? If so, this should work:
 
trigger updateContracts on Account(after insert) {

	Map<Integer, Id> contractNumbersToAccountIds = new Map<Integer, Id>();
	for (Account acct : trigger.new) {
		contractNumbers.add(acct.Contract_Number__c, acct.Id);
	}

	List<Contract> contracts = [SELECT Id, BG_Contract_Number__c FROM Contract WHERE BG_Contract_Number IN: contractNumbersToAccountIds.keySet()];
	Map<Integer, Id> contractNumberToContractId = new Map<Integer, Id>();
	for (Contract cont : contracts {
		cont.AccountId = contractNumbersToAccountIds.get(cont.BG_Contract_Number__c);
	}
	update contracts;

}