+ Start a Discussion

Assign Account Owner in Trigger

Hi All,
I have this trigger once checkbox MSep30 is checked, a new Pint will be generated, Account will be the same as previous Pint, but we want to pull Account Owner from Account Object in case there's change of Account owner. But error message says variable "Account.Owner.Firstname & Account.Owner.Lastname" don't exist, please help.

trigger MSep30 on Pint__c (after update) {
    List<Pint__c> pints = new List<Pint__c>();
   for (Pint__c p : Trigger.new) {
           if (p.MSep30__c == true ) {
               Pint__c newPint = new Pint__c();
               newPint.Account__c = p.Account__c;
               newPint.Pint_Owner__c = Account.Owner.Firstname & Account.Owner.Lastname
               newPint.Payroll_Date__c = p.Payroll_Date__c + 30;
               newPint.Schedule_Start_Date_5_Biz_Days_Prior_PR__c = p.Payroll_Date__c + 23;
   if(pints.size() > 0) insert pints;
Hi KatherineC,

I can see two issues:

1. "Account" is a relationship from your object, so instead of "Account.", you should use "p.Account__r."
2. But this won't solve the problem, as Owner field is polymorphic, i.e., it can contain a User or a Queue ID. So you can't use it directly in SOQL or direct expressions, which means you would need to take out OwnerIDs first and then run a query on User to get the values before updating your fields with those values.

So your trigger should be:

1. Retreive AccountIDs & Account OwnerIDs from Pint__C object, using SOQL.  SOQL is required as you can't access related objects in triggers directly, you would need to write a SOQL query to do that.
2. Retrieve User Fields from User Object, for the OwerIDs and then use those User Fields to populate your object.

This article might help : https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_bulk_idioms.htm

- Hargobind