When to use before and after trigger in Salesforce?

Before Trigger:
  1. In case of validation check in the same object.
  2. Update the same object.
After Trigger: 
  1. Insert/Update related object, not the same object.
  2. Notification email.

If we want to update a record of an object, we cannot use After trigger, because it causes read only error. This is because, after inserting or updating, we cannot update a record. Update should be made in before event for the same object.

Cheers!!!

2 comments:

  1. Sir this is venkatesh,i use this after update triggercode for updating the customobject from StandardObject after insert is working but after update is not updating the record in existing one......its create a new updated record................

    code example:
    -------------------------

    trigger addcontacts on Contact(after insert,after Update)
    {
    for (Contact c :Trigger.new) {
    CustomContact__c cust = new CustomContact__c(
    Name=c.Name,
    Firstname__c = c.FirstName,
    Lastname__c = c.LastName,
    Email_id__c = c.Email,Mobile_Number__c=c.MobilePhone);
    insert cust;
    }
    if(Trigger.isUpdate)
    {
    Set setContactAddressChangedIds = new Set();

    for (Contact oContact : trigger.new) {
    Contact oOldContact = trigger.oldMap.get(oContact.Id);

    boolean bIsChanged = (oContact.FirstName != oOldContact.FirstName || oContact.LastName != oOldContact.LastName ||

    oContact.Email!=oOldContact.Email || oContact.MobilePhone!=oOldContact.MobilePhone);
    if (bIsChanged) {
    setContactAddressChangedIds.add(oContact.Id);
    }
    }

    //If any, get contacts associated with each account
    if (setContactAddressChangedIds.isEmpty() == false) {
    List listContacts = [SELECT

    Ext_Id__c,FirstName__c,LastName__c,Email_id__c,Mobile_Number__c FROM CustomContact__c WHERE Ext_Id__c IN

    :setContactAddressChangedIds];
    for (CustomContact__c contact : listContacts) {
    //Get Account
    oContact = trigger.newMap.get(contact.Id__c);

    //Set Address
    contact.FirstName__c = oContact.FirstName;
    contact.LastName__c = oContact.LastName;
    contact.Eamil_id__c = oContact.Eamil;
    contact.Mobile_Number__c= oContact.MobilePhone;
    }

    //If any, execute DML command to save contact addresses
    if (listContacts.isEmpty() == false) {
    update listContacts;
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. for (Contact c :Trigger.new) {
      CustomContact__c cust = new CustomContact__c(
      Name=c.Name,
      Firstname__c = c.FirstName,
      Lastname__c = c.LastName,
      Email_id__c = c.Email,Mobile_Number__c=c.MobilePhone);
      insert cust;
      }

      the above piece of code in your trigger creates a contact whenever the trigger is fired.

      Cheers!!!

      Delete