/ ==================================================================================
// Object: biuContact
// Author: John Westenhaver
// Comments: Automatically assign ownership of a Contact to the owner of the parent
// Account.
// ==================================================================================
// Changes: 2010-05-05 Initial version.
// ==================================================================================
trigger biuContact on Contact (before insert, before update)
{
set accountIds = new set();
// Get a list of Account IDs where the Owner ID has changed.
for (Contact c : system.trigger.new)
{
if (system.trigger.isInsert)
{
// By definition, on insert, the Owner ID has changed.
if (c.AccountId != null) accountIds.add(c.AccountId);
}
else if (system.trigger.isUpdate)
{
// Only check if the Owner ID is changed.
if (c.OwnerId != system.trigger.oldMap.get(c.Id).OwnerId)
{
if (c.AccountId != null) accountIds.add(c.AccountId);
}
}
}
// Get a map of Accounts.
map accountMap = new map(
[SELECT Id, Name, OwnerId FROM Account WHERE Id IN :accountIds]);
// Loop over all Contacts and update the Owner if
// the Contact owner differs from the Account owner.
Account a;
for (Contact c : system.trigger.new)
{
a = accountMap.get(c.AccountId);
if (a != null)
{
if (a.OwnerId != c.OwnerId) c.OwnerId = a.OwnerId;
}
}
}
0 comments:
Post a Comment