+ Start a Discussion
Sebastian Röder_CognizantSebastian Röder_Cognizant 

Update lookup field by Trigger

Hi,
i facing following issue:

We Have Obj. Account and Obj. B__c.
On Object Account we have a ID__c which stores an ID.  Now we get this ID from an external System written in an text field on Obj. B__c

Now i need a piece of code which matches teh ID from Obj. B__c with the ID from Account and if a match is found the LOOKUP on Obj. B__c should be populated with the ACCOUNT NAME which has the same ID.

 

I hope it is undersantable and anyone can help me out with some link for ressources.

Thank you.

Sebastian

Best Answer chosen by Sebastian Röder_Cognizant
Vijay NagarathinamVijay Nagarathinam
Use the below code, it will work for builkified,
 
Set<Id> accountIds = new Set<Id>();
Map<Id,Account> accountMap = new Map<Id,Account>();
for(B__c b : Trigger.New){
	accountIds.add(b.Id);
}
for(Account acc : [SELECT Id__c FROM Account WHERE Id__c IN : accountIds]){
	accountMap.put(acc.Id__c,acc);
}
if(accountMap.size() > 0){
	for(B__c b : Trigger.New){
	   if(accountMap.containsKey(b.Id)){
		 b.LookUpfield__c = accountMap.get(b.Id).Id;
		 b.text__c = accountMap.get(b.Id).Name;
	   }
	}
}

Let me know if you need any help regarding this,

Thanks,
Vijay

All Answers

Nagendra Prasad ChNagendra Prasad Ch
Use below code in your Obj.B__c before trigger.(code given is not bulkified)
 
for(B__c b : Trigger.New){
ID ObjId = b.Id;
Account Acc = [SELECT Id,Name FROM Account WHERE ID__c = :ObjId];
b.LookUpfield__c = Acc.Id;// Lookup field can be assigned only with Ids. On UI it will automatically displaces Name instaead of ID
b.Text__c = Acc.Name;//If the field is not a lookup and is a text ,then u can assign name.
}



 
Vijay NagarathinamVijay Nagarathinam
Use the below code, it will work for builkified,
 
Set<Id> accountIds = new Set<Id>();
Map<Id,Account> accountMap = new Map<Id,Account>();
for(B__c b : Trigger.New){
	accountIds.add(b.Id);
}
for(Account acc : [SELECT Id__c FROM Account WHERE Id__c IN : accountIds]){
	accountMap.put(acc.Id__c,acc);
}
if(accountMap.size() > 0){
	for(B__c b : Trigger.New){
	   if(accountMap.containsKey(b.Id)){
		 b.LookUpfield__c = accountMap.get(b.Id).Id;
		 b.text__c = accountMap.get(b.Id).Name;
	   }
	}
}

Let me know if you need any help regarding this,

Thanks,
Vijay
This was selected as the best answer
Sebastian Röder_CognizantSebastian Röder_Cognizant

HI @Vijay   thanks for your post. I have a question regarding:

for(Account acc : [SELECT Id__c FROM Account WHERE Id__c IN : accountIds]){......

Id__c is this supposed to be the field from ACCOUNT object or from b__c Object?

Vijay NagarathinamVijay Nagarathinam
ID__c field in Account object. If the ID__c value is matched in the B__c Id then we perform the account name to custom field in B__c object.

Thanks,
Vijay