You need to sign in to do that
Don't have an account?
Keerthi G
Update contact records custom lookup field value
On Contact, based on two custom fields (subgroup id and code), look for Subgroup object record to get subgroup account field value then update contact subgroup account look up field value.
I have the below code working but want to bulkfy as we have millins of contact records.
trigger UpdateSubgroupOnContact on Contact (before insert) {
if(Trigger.isBefore){
if(Trigger.isInsert){
Set<Decimal> setOfSubgroupIds = new Set<Decimal>();
for(Contact cnt : trigger.new){
if(cnt.SubgroupCode__c != null && cnt.SubgroupId__c != null){
setOfSubgroupIds.add(cnt.SubgroupId__c);
//system.debug('setof subgroup ids======'+setOfSubgroupIds);
//subGroupRecords = [Select Id,Account__c, Subgroup_Id__c, SubGroup_Code__c from SubGroup__c where Subgroup_Id__c =:cnt.SubgroupId__c];
for(List<SubGroup__c> sbg: [Select Id,Account__c,Subgroup_Id__c, SubGroup_Code__c from SubGroup__c where Subgroup_Id__c IN:setOfSubgroupIds]){
for(SubGroup__c s: sbg){
cnt.Subgroup__c = s.Account__c;
}
}
}
}
}
}
}
I have the below code working but want to bulkfy as we have millins of contact records.
trigger UpdateSubgroupOnContact on Contact (before insert) {
if(Trigger.isBefore){
if(Trigger.isInsert){
Set<Decimal> setOfSubgroupIds = new Set<Decimal>();
for(Contact cnt : trigger.new){
if(cnt.SubgroupCode__c != null && cnt.SubgroupId__c != null){
setOfSubgroupIds.add(cnt.SubgroupId__c);
//system.debug('setof subgroup ids======'+setOfSubgroupIds);
//subGroupRecords = [Select Id,Account__c, Subgroup_Id__c, SubGroup_Code__c from SubGroup__c where Subgroup_Id__c =:cnt.SubgroupId__c];
for(List<SubGroup__c> sbg: [Select Id,Account__c,Subgroup_Id__c, SubGroup_Code__c from SubGroup__c where Subgroup_Id__c IN:setOfSubgroupIds]){
for(SubGroup__c s: sbg){
cnt.Subgroup__c = s.Account__c;
}
}
}
}
}
}
}
And could you explain each line of the following for loop?
trigger UpdateSubgroupOnContact on Contact (before insert) {
if(Trigger.isBefore){
if(Trigger.isInsert){
Set<Decimal> setOfSubgroupIds = new Set<Decimal>();
for(Contact cnt : trigger.new){
if(cnt.SubgroupCode__c != null && cnt.SubgroupId__c != null){
setOfSubgroupIds.add(cnt.SubgroupId__c);
}
}
Map<Id,SubGroup__c> mapofSubgroups = new Map<Id,SubGroup__c>([Select Id,Subgroup_Id__c,Account__c from SubGroup__c where Subgroup_Id__c IN:setOfSubgroupIds]);
for(Contact c : trigger.new){
for(SubGroup__c sbg :mapofSubgroups.values()){
if(c.SubgroupId__c == sbg.Subgroup_Id__c){
c.Subgroup__c =sbg.Account__c;
}
}
}
}
}
}
The only (minor?) concern is your double for loop attempts to check every value until it finds a match, which may be a bit inefficient. The solution would be a map so you know which subgroup belongs to which Contacts without needing a check.