Monday, January 6, 2014

Execute Anonymous - I

Execute Anonymous :
This is a simple example to understand how we can use apex class for various actions. The reason we are implementing in Execute Anonymous we can see immediate effect on Salesforce server and can see logs for debug statement and my favorite to observe Governor Limits

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));

Here is the debug statements screen looks like



No comments:

Post a Comment