function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JuulJuul 

Copy a field from account to event

Hi,

 

I've tried to create a workflow to copy the field accountstage (invisible for users, just for reporting) to a new event. But this is not possible unfortunately.

Is it possible to create a trigger only on event creation that copies the field accountstage to the custom field Accountstage on event? Does anyone have an example or an idea, triggers are not my specialty :)

PrakashbPrakashb

Yes you can write a trigger to copy the field from Account to your event.

 

You also need to make sure that you trigger runs only when an event is created for account and not for other objects.

JuulJuul

Thanks Prakashb, do you have an example to copy a field from one object to another object?

Shivanath DevnarayananShivanath Devnarayanan

I Agree with prakash,

 

To give more insight on how I might go about it is,

Create a trigger on Events, and when the AccountId on event object is not null, I'd Query the corresponding field from the account and use it to store the value on to the event

 

you could take a look at the Event fields here 

 

Best practices for writing Triggers (from Jeff Douglas's Blog)

 

  • There should only be one trigger for each object.
  • Avoid complex logic in triggers. To simplify testing and resuse, triggers should delegate to Apex classes which contain the actual execution logic. See Mike Leach’s excellent trigger template for more info.
  • Bulkify any “helper” classes and/or methods.
  • Trigers should be “bulkified” and be able to process up to 200 records for each call.
  • Execute DML statements using collections instead of individual records per DML statement.
  • Use Collections in SOQL “WHERE” clauses to retrieve all records back in single query
  • Use a consistent naming convention including the object name (e.g., AccountTrigger)

Hope i did'nt convolute it too much. and it helped.

Do mark this as answered if it helped you solve your problem.

 

Happy coding!

JuulJuul

Thanks for the reply. I've got some help. The trigger is working without the test class.

 

trigger:

trigger EventAccountstage on Event (before insert, before update) {
    if(trigger.isInsert){
        //create a set of all unique WhatIDs and WhoIDs
        set<id> WhoIDs = new Set<id>();
        Set<id> WhatIds= new Set<id>();
        Set<id> AccountIds= new Set<id>();
        
        for (Event t : trigger.new){
            if (String.valueOf(t.whoId)!= null){
                WhoIDs.add(t.WhoID); 
            }else if (String.valueOf(t.WhatID)!= Null){
                WhatIds.add(t.WhatID);
            }else if (String.valueOf(t.AccountID)!= Null){
                AccountIds.add(t.AccountID);
            }
        }   
        //create a map for a hash table for the industry
        Map<id, Lead> who = new Map<id, Lead>([SELECT Account_Stage__c FROM Lead WHERE ID in :WhoIDs]);     
        Map<Id, Account> acct = new Map<Id, Account>([Select Account_Stage__c From Account Where ID in :AccountIds OR ID in: WhatIDs]);
        Map<id, Contact> con = new Map<id, Contact>([SELECT Account.Account_Stage__c from Contact WHERE ID in :WhoIDs]);
        Map<id, Opportunity> opp = new Map<id, Opportunity>([Select Account.Account_Stage__c From Opportunity Where Id in :WhatIDs]);   
    

        // iterate over the list of records being processed in the trigger and set the industry
        for (Event a : Trigger.new){
            if(who.ContainsKey(a.whoId)){
                a.Account_Stage__c = who.get(a.WhoId).Account_Stage__c;
            } else if (con.ContainsKey(a.whoId)){
                if(con.ContainsKey(a.WhoId)){
                    a.Account_Stage__c = con.get(a.WhoId).account.Account_Stage__c;
                }
            } else if (opp.ContainsKey(a.whatId)){
                a.Account_Stage__c = opp.get(a.WhatId).account.Account_Stage__c;
            } else if (acct != null && !acct.isEmpty()){
                    if(acct.ContainsKey(a.whatID)){
                        a.Account_Stage__c = acct.get(a.whatID).Account_Stage__c;
                    }else if(acct.ContainsKey(a.AccountId)){
                        a.Account_Stage__c = acct.get(a.AccountId).Account_Stage__c;
                    }
            }
        }
    } else {
        if(trigger.isUpdate){
             //create a set of all unique ids 
            set<id> WhoIDs = new Set<id>();
            Set<id> WhatIds= new Set<id>();
            Set<id> AccountIds= new Set<id>();
            
            for (Event t : Trigger.new){
                if (Trigger.oldMap.get(t.Id).WhoId != Trigger.newMap.get(t.Id).WhoId){
                    WhoIDs.add(t.WhoID); 
                }else if (Trigger.oldMap.get(t.Id).WhatID != Trigger.newMap.get(t.Id).WhatID){
                    WhatIds.add(t.WhatID);
                }else if (Trigger.oldMap.get(t.Id).AccountID != Trigger.newMap.get(t.Id).AccountID){
                    AccountIDs.add(t.AccountID);
                }
            }
            
            //create a map for a hash table for the industry
            Map<id, Lead> who = new Map<id, Lead>([SELECT Industry FROM Lead WHERE ID in :WhoIDs]);     
            Map<Id, Account> acct = new Map<Id, Account>([Select Industry From Account Where ID in :AccountIds OR ID in: WhatIDs]);
            Map<id, Contact> con = new Map<id, Contact>([SELECT Account.Industry from Contact WHERE ID in :WhoIDs]);
            Map<id, Opportunity> opp = new Map<id, Opportunity>([Select Account.Industry From Opportunity Where Id in :WhatIDs]);   
            
            for (Event a : Trigger.new){
                if (!who.isEmpty()&& who.ContainsKey(a.WhoId)){
                    a.Account_Stage__c = who.get(a.WhoId).Account_Stage__c;
                } else if (!con.isEmpty()){
                    a.Account_Stage__c = con.get(a.WhoId).account.Account_Stage__c;
                } else if (!opp.isEmpty()){
                    if(opp.ContainsKey(a.WhatId)){
                        a.Account_Stage__c = opp.get(a.WhatId).account.Account_Stage__c;
                    }               
                } else if (acct != null && !acct.isEmpty()){
                    if(acct.ContainsKey(a.whatID)){
                        a.Account_Stage__c = acct.get(a.whatID).Account_Stage__c;
                    }else if(acct.ContainsKey(a.AccountId)){
                        a.Account_Stage__c = acct.get(a.AccountId).Account_Stage__c;
                    }
                }
            }
        }       
    }
}

 

 

 

But having some problems with the test class. Can someone please help me?

 

@isTest
private class TestEventAccountstage {
    static testMethod void testInsert() {
       
       // create user to run the test as
       Profile p = [select Id from profile where name = 'Standard User'];
       UserRole r = [select Id from userrole where name = 'Product Support Rep'];
       
       User u = new User(lastname='testing', alias='test123', email='testing123@noemail.com',
        username='testing123@noemail.com', profileid = p.Id, userroleid = r.id);
        insert u;
       
        System.runAs(u) {  
            // Switch to the runtime 
            Test.StartTest();
            performDmlLeadEvents(u.id); 
            performDmlContactEvents(u.id);
            performDmlOpportunityEvents(u.id);
            performDmlAccountEvents(u.id);
            Test.StopTest();   
        }
        //check results of Lead events
        list <Event> InsertedEvents = [Select id, Account_stage__c from Event where OwnerId=:u.id];
        for (Event e : InsertedEvents){
            System.assertEquals('Suspect', e.Account_stage__c);   
        }  
    }
    @future
    public static void performDmlLeadEvents(string ownerid){
        List<Event> events = new List<Event>();

        // create lead
       Lead l = new Lead(Company='Testing Lead',Status='Open', Account_stage__c='Suspect', LastName='TestLastName');  
       insert l;              
    }    
    
    @future
    public static void performDmlContactEvents(string ownerid){
        List<Event> events = new List<Event>();
        
         // create account
       Account a = new Account(Name='Testing Account', Account_stage__c='Suspect');
       insert a;
       // create a contact for the account for testing
       Contact c = new Contact(AccountID=a.Id, LastName='lasttesting', Contact_type__c='Employee');
       insert c;                     
    }  
    
     @future
    public static void performDmlOpportunityEvents(string ownerid){
        List<Event> events = new List<Event>();
        
         // create account  
       Account a = new Account(Name='Testing Account', Account_stage__c='Suspect');
       insert a;
        // create opportunity on the account 
       Opportunity o = new Opportunity(name='Testing Account Opportunity', AccountID=a.id, type='New Client', StageName='Working', CloseDate=Date.newInstance(2012,08,05));
       insert o;       
       
    }  
        
         @future
    public static void performDmlAccountEvents(string ownerid){
        List<Event> events = new List<Event>();
        
         // create account  
       Account a = new Account(OwnerId=ownerid, Name='Testing Account', Account_stage__c='Suspect');
       insert a;    
              
    }  
    static testMethod void testUpdate(){
          // create user to run the test as
       Profile p = [select Id from profile where name = 'Standard User'];
       UserRole r = [select Id from userrole where name = 'Salesmanager BV1, Centrale Sales'];
       
       User u = new User(lastname='testing', alias='test123', email='testing123@noemail.com',
        username='testing123@noemail.com', profileid = p.Id, userroleid = r.id);
        insert u;
        
        System.runAs(u) {  
            // Switch to the runtime 
            Test.StartTest();
            performDmlLeadEventUpdate(u.Id);
            performDmlContactEventUpdate(u.Id);
            performDmlOpportunityEventUpdate(u.Id);
            performDmlAccountTaskUpdate(u.Id);
            Test.StopTest();   
        }
        //check results of Lead events
        list <Event> InsertedEvents = [Select id, Account_stage__c from Event where OwnerId=:u.id];
        for (Event e : InsertedEvents){
            System.assertEquals('Suspect', e.Account_stage__c);   
        }  
    }
    @future
    public static void performDmlLeadEventUpdate(string ownerid){
        List<Event> events = new List<Event>();

        // create lead
      Lead l = new Lead(Company='Testing Lead',Status='Open', Account_stage__c='Suspect', LastName='TestLastName');    
       insert l;
      
      Lead l1 = new Lead(Company='Testing Lead Updated',Status='Open', Account_stage__c='Suspect', LastName='UpdatedLastName');   
      insert l1;
      
        list <Event> InsertedEvents = [Select id, Account_stage__c from Event where OwnerId=:ownerid];
        for (Event e : InsertedEvents){
            e.WhoID = l1.id;   
        } 
        update InsertedEvents; 
    }   
    
       @future
    public static void performDmlContactEventUpdate(string ownerid){
        List<Event> events = new List<Event>();
        
         // create account
       Account a = new Account(Name='Testing Account', Account_stage__c='Suspect');
       insert a;
       
       Account a1 = new Account(Name='Testing Account Updated', Account_stage__c='Suspect');
       insert a1;
       
       // create a contact for the account for testing
       Contact c = new Contact(AccountID=a.Id, LastName='lasttesting', Contact_type__c='Employee');
       insert c;    
       
       Contact c1 = new Contact(AccountID=a1.Id, LastName='updatedlast', Contact_type__c='Employee');
       insert c1;                   

        list <Event> InsertedEvents = [Select id, Account_stage__c from Event where OwnerId=:ownerid];
        for (Event e1 : InsertedEvents){
            e1.WhoID = c1.id;   
        } 
        update InsertedEvents;           
    }  
    
        @future
    public static void performDmlOpportunityEventUpdate(string ownerid){
        List<Event> events = new List<Event>();
        
         // create account  
       Account a = new Account(Name='Testing Account', Account_stage__c='Suspect');
       insert a;
       Account a1 = new Account(Name='Testing Account Updated', Account_stage__c='Suspect');
       insert a1;
 
        // create opportunity on the account 
       Opportunity o = new Opportunity(Name='Testing Account Opportunity', AccountID=a.id, type='Bestaande omzet', StageName='Einddatum Contract', CloseDate=Date.newInstance(2012,08,05));
       insert o;                
       Opportunity o1 = new Opportunity(Name='Updated Testing Account Opportunity', AccountID=a1.id, type='Bestaande omzet', StageName='Einddatum Contract', CloseDate=Date.newInstance(2012,08,05));
       insert o1;
       
        }
                       
        List <Event> InsertedEvents = [Select id, Account_stage__c from Event where OwnerId=:ownerid];
        for (Event e1 : InsertedEvents){
            e1.WhatID = o1.id;   
        } 
        update InsertedEvents;                       
    }  
    
        @future
    public static void performDmlAccountTaskUpdate(string ownerid){
    List<Event> events = new List<Event>();
        
         // create account  
       Account a = new Account(Name='Testing Account', Account_stage__c='Suspect');
       insert a;
       Account a1 = new Account(Name='Testing Account Updated', Account_stage__c='Suspect');
       insert a1;
       
        List <Event> InsertedEvents = [Select id, Account_stage__c from Event where OwnerId=:ownerid];
        for (Event e1 : InsertedEvents){
            e1.WhatID = a1.id;   
        } 
        update InsertedEvents;                       
    }                       
}

 

Shivanath DevnarayananShivanath Devnarayanan
What exactly is the problem? and why have you used @future methods in the test class ? or am I missing something?

JuulJuul

I saw this in an example.... I receive a compilation error: Compile Error: expecting right curly bracket, found 'insert' at line....

 

Can you perhaps help me in the right direction?

 

thanks