Thursday, October 4, 2012

Execute Anonymous 1:

Execute Anonymous 1:
This is a simple execute anonymous explanation.You can observe logs carefully using your developer console.

public class Updater{
  public void updateFirstContact(List<Contact> listOfContacts){
    if(listOfContacts!=null && (!listOfContacts.isEmpty())){
      Contact firstContact = listOfContacts.get(0);
      if(firstContact.id!=null){
        firstContact.firstName += '-updated';
        firstContact.lastName = firstContact.lastName + '-updated';
        Database.update(firstContact);
      }
    } else {
      System.debug('There are no contacts in the list');
    }
  }
}

Account theAccount = new Account(name='My First Account');
insert theAccount;
System.debug('The new Account Id is ' + theAccount.id);

List<Contact> contactList = new List<Contact>();
for(Integer iCounter=0; iCounter <= 5; iCounter++){
  Contact oneContact= new Contact();
  oneContact.accountId=theAccount.id;
  oneContact.firstName='testFirst' + iCounter;
  oneContact.lastName='testLast' + iCounter;
  contactList.add(oneContact);
  System.debug('Added to list contact #' + iCounter);
}
Database.insert(contactList);

Integer howManyContacts= [select count() from Contact where accountId=:theAccount.id];
System.debug('The account has ' + howManyContacts + ' contacts.');

System.debug(contactList.get(0));
updater myUpdater = new updater();
myUpdater.updateFirstContact(contactList);
System.debug(contactList.get(0));

Note:Execute anonymous committed to database.

No comments:

Post a Comment