Book Image

Learning Apex Programming

5 (1)
Book Image

Learning Apex Programming

5 (1)

Overview of this book

Table of Contents (17 chapters)
Learning Apex Programming
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

You want me to process how many records?


We'll talk about triggers more in a later chapter, but for now you just need to know that a trigger is code that is automatically executed whenever a record is operated upon (meaning inserted, updated, deleted, or undeleted). When you first start programming in Apex, it tends to be trigger-related. These are usually simple scenarios such as when an account phone is modified, update the phone for all of the contacts on that account. This is shown in the following code:

//This code has a potentially fatal flaw in it
public static void updateContactAddresses(){
List<Contact> contactList = [
Select Id, Phone, AccountId, Account.Phone 
from Contact 
];
for ( Contact c : contactQuery ){
  c.Phone = c.Account.Phone;
}
update contactQuery;
}

Did you spot the flaw in the previous code block? If you tried it out in your Developer Edition org, it probably worked exactly as described. The problem doesn't lie in the syntax or logic.

A common mistake of new...