+ Start a Discussion
Nina GonzalezNina Gonzalez 

Lookup field between two objects

I am trying to add a Lookup field for a custom object called "CB Order" to the Case object based on the Account. The CB Order object has the Account and the Contact as lookup fields. But the CB Order is a related list on the Account page. It was set-up as one (Account) to many (CB Order) but we don't use this functionality. In reality they have a one-to-one relationship.

How can I create an auto lookup relationship for the CB Order on the Case object using the Account?
LBKLBK
Hi Nina,

1. You need to create a Lookup field in Case object, which looks up to CB Order object.

2. You can create a trigger (before insert, before update) on Case object to populate CB Order lookup field using the Account lookup that is already populated in Case.

Let me know if you need more information.
LBKLBK
Your before trigger will look roughly like this.
 
trigger updateCBOrder on Case (before insert, before update){
	
	List<Id> lstAccountIds = new List<Id>();
	
	for(Case c : trigger.new){
		 if(c.AccountId != null){
			lstAccountIds.add(c.AccountId);
		 }
	}
	
	List<CB_Order__c> lstCBOrder = [SELECT AccountId, Id FROM CB_Order__c WHERE Account__r.Id = :lstAccountIds];
	
	Map<String, CB_Order__c> mapCBOrder = new Map<Id, CB_Order__c> ();
	
	for(CB_Order__c cbo : lstCBOrder){
		mapCBOrder.put((String)cbo.AccountId, cbo);
	}
	for(Case c : trigger.new){
		 if(c.AccountId != null){
			c.CB_Order__c = mapCBOrder.get((String)c.AccountId);
		 }
	}
}

Look for syntactical errors, because I do not know the exact object definition details.