You need to sign in to do that
Don't have an account?
Trigger doesn't update lookup field on related record
Hi everyone!
I have three objects that are linked together (Account, Project__c, Space__c). Both the Project and the Space have a lookup to an Account and the Project looks up to a Space. What I want to do is when I populate the Account on the Project record it will update the related Space with that same Account.
Here's my code:
trigger PopulateCurrentTenant on Project__c (after insert, after update) { Set<id> tenantIds = new Set<id>(); Set<id> spaceIds = new Set<id>(); for (Project__c p : Trigger.new){ tenantIds.add(p.Account__c); spaceIds.add(p.Space__c); } // query for all the tenant records for the unique tenantIds in the records // create a map for a lookup / hash table for the user info List<Account> tenants = [Select Id, Name from Account Where Id in :tenantIds]; Map<id, Account> tenantsMap = new Map<id, Account>(); for(Account a : tenants){ tenantsMap.put(a.Id,a); } List<Space__c> spaces = [Select Id, Name, Account__c from Space__c Where Id in :spaceIds]; Map<id, Space__c> spacesMap = new Map<id, Space__c> (); for(Space__c s : spaces){ spacesMap.put(s.Id,s); } // iterate over the list of records being processed in the trigger and // set the Existing Tenant on the Space after being inserted or updated for (Project__c p : Trigger.new){ Space__c thisSpace = spacesMap.get(p.Space__c);
Account thisTenant = tenantsMap.get (p.Account__c);
thisSpace.Account__c = thisTenant;
} }
The code deploys fine but there's only one issue: it doesn't do a thing; nothing happens when I edit a project. it just doesnt update the related space with the account.
Are the maps empty? Am I querying the data incorrectly?
Thank you in advance for your help!
Hi,
I think you should write update statement at the end of the trigger:
All Answers
Hi,
I think you should write update statement at the end of the trigger:
Wow!
I spent endless hours trying to fix this thing and it was as simple as adding that update statement at the end!!!
Thanks miha!
Note: I had tried the before trigger but it didnt work either. Thanks for the suggestion though.
I have the same issue, I'm assuming I can substitute the api names and use the code above... I'm pretty new to this stuff, so could someone let me know if I'm missing anything?
Account = My_Biz_Office_User__c
Space = Zip_code__c
Project = Lead
as far as the field, I want:
enrollment_manager__c (on zip_code__c) to update enrollment_manager__c (on lead) upon creation of a new lead.
Would something like this work?