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 

compare two fields and then update a third

I have two objects linked with a lookup field. 
On each object is a field called "reciept number" (that is unique).
On one object the information comes in through an automated process. My hope is to build something that compares the two "reciept number" fields and if it finds a match, it populates the look upfield with the Salesforce Unique ID number for that record (to link the two records).
Try as I might, I haven't been able to find anything that discusses how this can be done.
Any help in pointing me in the right direction would be greatly appreciated. 
Best Answer chosen by David Jobe
UC InnovationUC Innovation
Hi David,

It seems like you need a trigger to do this. If you create an insert trigger on the object that gets the receipt number through the automated process, you can query the other object to find matching receipt numbers and relate them together. 

Here's a prototype trigger you can use as a reference. I just used accounts and contacts as an example.
trigger UpdateRelationshipThroughReceipt on Account (after insert)
	set<string> receiptNumberSet = new set<string>();
	for(Account a :
	// getting all the contacts with the same receipt numbers as the accounts that was inserted
	list<contact> contactList = [SELECT ID, receiptnumber__c, lookupToAccount__c FROM contact WHERE receiptnumber__c in: receiptNumberSet];
	for (Account a:
		for (Contact c: contactList)
			// Link the account and contact together if they have same receiptnumber__c fields
			if (a.receiptnumber__c == c.receiptnumber__c)
				c.lookupToAccount__c = a.ID;
	update contactList;

Let me know if you have any questions!