+ Start a Discussion
bkradminbkradmin 

Simple Cross Object Field Update

I am very new to Apex. I am looking to write a trigger that will dynamically update a field on an Account page with the value of a field on a Contact page (where the contact belongs to that account). So, for example, the Accound field would be called "Vice President's Personal Number" and it would pull its value from the mobile number of the contact whose role matches "Vice President". I imagine this is a pretty simple trigger to write, but I can't find any examples of this to get me started. 

Sean TanSean Tan

I highly recommend you start reading the getting started guides of the Apex coding. You can find it here:

 

http://wiki.developerforce.com/page/Get_Started_With_Apex_Code

 

Now in terms of your example, here was something written quickly to match what you're asking (it may not compile depending on field names)

 

trigger UpdateAccountPhone on Contact (after insert, after update)
{
    Account[] aList = new Account[]{};
    
    for (Contact c : Trigger.new)
    {
        if (c.AccountId != null && c.Role == 'Vice President' &&
            ((Trigger.isInsert && c.MobilePhone != null) || (Trigger.isUpdate && Trigger.oldMap(c.Id).MobilePhone != c.MobilePhone)))
        {
            aList.add(new Account(Id=c.AccountId, Vice_Presidents_Phone_Number__c=c.MobilePhone));
        }
    }
    
    if (!aList.isEmpty())
    {
        update aList;
    }
}

 To explain whats happening.

 

  • The trigger fires after insert or update of a Contact
  • Loops through all Contacts being inserted or updated
  • It checks if the Contact has a valid Account Id and the role of the contact is vice president
  • Then it checks if it's either a new contact that has a mobile phone OR if its an update and the mobile phone is changing
  • It add's an "Account" object to update to the database
  • Lastly checks if there are any accounts and fires the update call.