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

Compile Error
Hi everyone- I have four fields on the User object that have corresponding fields on the Account object. I need to make a trigger that pulls the values from the User record and maps them appropriately on the Account record. Here's the code I have:
trigger UserData on Account (before insert, before update) { //The purpose of this trigger is to pull four field values from an account owner's user record, and map them onto the account record //Pulls 'Business Unit', 'Sales Role', 'Reports To', 'Region' fields // create a set of all the unique ownerIds Set<Id> ownerIds = new Set<Id>(); for (Account a : Trigger.new) ownerIds.add(a.OwnerId); // query for all the User records for the unique userIds in the records // create a map for a lookup / hash table for the user info Map<Id, User> owners = new Map<Id, User>([Select USER.Business_Unit__c, USER.Sales_Role__c, USER.Reports_To__c, USER.Region__c from User Where Id in :ownerIds]); // iterate over the list of records being processed in the trigger and // set the field values before insert & update for (Account a: Trigger.new) a.Business_Unit__c = owners.get(a.OwnerId).Business_Unit__c; a.Sales_Role__c = owners.get(a.OwnerID).Sales_Role__c; a.Reports_To__c = owners.get(a.OwnerID).Reports_To__c; a.Region_c = owners.get(a.OwnerID).Region_c; }
For some reason in the IDE it's stating that there's a save error: "Variable a.Sales_Role__c does not exist". Does anyone know how I can fix this?
Use this
in a for loop or in if condition block if you don't write { } then scope only remains for one statement.
All Answers
In the last for loop, you don't have {} around the 4 fields you want to update. So the "a" variable has lost scope.
Use this
in a for loop or in if condition block if you don't write { } then scope only remains for one statement.
Thanks guys- that was extremely helpful. I'm also trying to get the test class setup but I'm getting 0% coverage and it's giving me an error:
The error message it's giving me is "System.StringException: Invalid id: Test Report". The Reports_To__c field is a user look up field. I also tried putting a valid user ID in there but it's still giving me the error. Any ideas? Thanks again!
u.Reports_To__c = 'Test Report';
in above statement from your test method you are trying to assign a text field in a reference field , reference fields only take valid ID value.
Thanks Shashikant- when I try to put in a valid 18 digit (or 15 digit) reference ID it gives me this error:
System.DmlException: Update failed. First exception on row 0 with id 005000000074MeFAAU; first error: CIRCULAR_DEPENDENCY, attempt to violate hierarchy constraints: []
Any ideas?
Figured it out- I couldn't use my unique user ID for some reason. Once I changed it to a different active user it worked fine.