I am creating my very first Apex trigger and am having trouble with the syntax.
I have a formula field in the Contact object that pulls in the Industry field from the Account. When an account is updated and the Industry is changed, I want the child Contacts to update (no changes to data) so that my "on update" workflow runs (which triggers an outbound message to update my external ERP through Jitterbit).
I have an error: Compile Error: Method does not exist or incorrect signature: [LIST].keySet() at line 6 column 20
I would also like the trigger to fire only when the industry is changed.
My code is below:
trigger UpdateContactsWithNewCustomerType on Account (after update) {
If(Trigger.isUpdate){
Set<ID> ids = Trigger.new.keySet();
List<Account> updatedParents = [SELECT Id,
(select ID, AccountID from Contacts)
FROM Account
WHERE Id in :ids];
List<Contact> childrenToUpdate = new List<Contact>();
for (Account p : updatedParents)
{
for(Contact kid : p.Contacts)
{
childrenToUpdate.add(kid);
}
}
if( !childrenToUpdate.isEmpty )
{
update childrenToUpdate;
}
}
}
* UPDATE * Thanks to both @Ralph and @Regal I was able to get this working. Below is the final code that worked.
trigger UpdateContactsWithNewCustomerType on Account (after update) {
//CREATE NEW LIST ids THAT CONTAINS ACCOUNT IDS SENT TO TRIGGER
Set<ID> ids = Trigger.newMap.keySet();
// FIND ALL ACCOUNTS WHERE ID = THOSE SENT TO TRIGGER
List<Account> updatedParents = [SELECT Id, Industry, (select ID, AccountID from Contacts)
FROM Account
WHERE Id in :ids];
//CREATE NEW EMPTY LIST CALLED childrenToUpdate
List<Contact> childrenToUpdate = new List<Contact>();
//LOOP OVER UPDATED ACCOUNTS
for(Account acc : updatedParents)
{ // CHECK IF THE NEW AND OLD INDUSTRY VALUES ARE THE SAME
String oldvalue = Trigger.oldMap.get(acc.Id).Industry;
String newValue = acc.Industry;
//IF NOT, THEN ADD IDS OF RELATED CONTACTS TO childrenToUpdate LIST
if(oldvalue != newValue )
{
for(Contact kid: acc.Contacts)
{
childrenToUpdate.add(kid);
}
}
}
//UPDATE CONTACTS IF childrenToUpdate IS NOT EMPTY
if( !childrenToUpdate.isEmpty() )
{
update childrenToUpdate;
}
}