You need to sign in to do that
Don't have an account?

Trigger to update a lookup on a custom object is turning the field blank
Hi
I am trying to write a trigger that will update the lookup field called Most_recent_nomination_tenancy__c field on a custom object called Referral__c when a new Nomination/Tenancy is created. However at present rather than updating the field with the name of the new Nomination/Tenancy it is turning the field blank. Does anyone know why this trigger is turning the field blank and not updating it?
trigger UpdateReferralWithNewNomTen on Nomination_Tenancy__c (before insert, before update) {
for(Nomination_Tenancy__c newRecord : Trigger.new) {
Referral__c Referral = [Select Id, Most_recent_nomination_tenancy__c from Referral__c WHERE Id = :newRecord.Referral__c ];
Referral.Most_recent_nomination_tenancy__c = newRecord.Name;
update Referral;
}
}
Many Thanks,
Mike
I am trying to write a trigger that will update the lookup field called Most_recent_nomination_tenancy__c field on a custom object called Referral__c when a new Nomination/Tenancy is created. However at present rather than updating the field with the name of the new Nomination/Tenancy it is turning the field blank. Does anyone know why this trigger is turning the field blank and not updating it?
trigger UpdateReferralWithNewNomTen on Nomination_Tenancy__c (before insert, before update) {
for(Nomination_Tenancy__c newRecord : Trigger.new) {
Referral__c Referral = [Select Id, Most_recent_nomination_tenancy__c from Referral__c WHERE Id = :newRecord.Referral__c ];
Referral.Most_recent_nomination_tenancy__c = newRecord.Name;
update Referral;
}
}
Many Thanks,
Mike
Referral.Most_recent_nomination_tenancy__c = newRecord.id;
I've noticed a couple of things.
Referral.Most_Recent_Nomination_Tenancy__c = Nomination_Tenancy__c.Id (Not .Name)
Also, best practice is not to include DML inside a for loop.
https://developer.salesforce.com/page/Apex_Code_Best_Practices
Following those best practices here is design I would use:
-
Loop through your Nomination Tenancy records and create a Map of Referall Ids to Nomination Tenancy Id's. Ex: refMap.put(newRecord.Referral__c, newRecord.Id)
-
Outside the loop, get a list of Referrals WHERE Id IN :refMap.keyset()
-
Loop through those referral records and populate the Most Recent Nomination Tenancy field using the map. Ex. Referral.Most_Recent_Nomination_Tenancy__c = refMap.get(Referral.Id);
-
Finally, update your list of Referrals (outside any loops)
Hope this helps!trigger UpdateReferralWithNewNomTen on Nomination_Tenancy__c (after insert) {
List<Referral__c> referralsToUpdate = new List<Referral__c>{};
for(Nomination_Tenancy__c newRecord : Trigger.new) {
Referral__c Referral = [Select Id, Most_recent_nomination_tenancy__c from Referral__c WHERE Id = :newRecord.Referral__c ];
Referral.Most_recent_nomination_tenancy__c = newRecord.id;
referralsToUpdate.add(Referral);
}
update referralsToUpdate;
}