In an update trigger, how can I query all contacts related to an account where the record type of the account should be 'AnyString' and Shipping Address is being updated?
2 Answers
In your trigger,:
- Identify when Account records have had the address updated and store the IDs
- At the end of the trigger use the ID's from #1 and query the contacts where the AccountID IN the IDs from #1.
Some rough code to get you started. First you need to find the list of account IDs where the address has been changed, then you need to query for the contacts after. You can do this by querying accounts and getting the children to save you having to map them out manually.
trigger Account_BeforeUpdate(before update)
{
set<id> accountIds = new set<id>();
for(Account a: trigger.new)
{
if(a.ShippingAddress != trigger.oldMap.get(a.Id).ShippingAddress)
accountIds.add(a.Id);
}
for(Account a : [select Id, (select Id, Name from Contacts)
where Id in : accountIds and RecordType.DeveloperName = 'AnyString'])
{
// do stuff with the accounts & contacts
}
}
Note that when working with record types it is important to use the DeveloperName
field as the label of the record type could be changed at any time by an administrator. The DeveloperName
is the equivalent of the API name on an SObject or field, i.e. it can't be changed as easily as the label can, meaning your code is less likely to be broken later on.