Friday 3 January 2014

Simple trigger to Update Child records in Salesforce

Problem: 

Whenever account record Description field is updated the corresponded contacts records Description fields should be updated.

Solution:

  1. trigger contactUpdate on Account (after insert,after update)
  2. {
  3.     List<Contact> conList =  [Select Id,Name,AccountId, Description from Contact where AccountId in: trigger.oldmap.keyset()];
  4.    
  5.     for(Contact con : conList)
  6.     {
  7.         Account relatedAccount = trigger.newmap.get(con.AccountID);
  8.         con.Description= relatedAccount.Description;
  9.     }  
  10.     update conList;
  11. }

3 comments:

  1. Hi,
    I have tried this code but its throwing an error: " Illegal assignment from Contact to Account at line 6 column 17".. Here is my code. Can you please help me fix it.

    trigger testcon on Contact (after insert) {
    List conList = [Select Id,Name,AccountId,Type__c from Contact where AccountId in: trigger.oldmap.keyset()];

    for(Contact con : conList)
    {
    Account relatedAccount = trigger.newmap.get(con.AccountID);
    con.Type__c= relatedAccount.Type;
    }
    update conList;
    }

    ReplyDelete
  2. i know it's too late, still useful for others.

    trigger was written on Contact object and u r trying to get the Account object from the Contact trigger.
    use the below code

    trigger testcon on Contact (Before insert) {
    List lstAccId = New List();
    Map mpAcc = Null;
    for(Contact con : trigger.newmap.values()){
    lstAccId.add(con.AccountID);
    }
    mpAcc = New Map([select Id,Type From Account Where Id in: lstAccId]);
    for(Contact con : trigger.newmap.values())
    {
    Account relatedAccount = mpAcc.get(con.AccountID);
    con.Type__c = relatedAccount.Type;
    }
    }

    ReplyDelete
  3. How to change Hotmail account password?
    Hotmail is now famous across the world and you will need to change its password from time to time to keep it secure. To change your password, login to your Hotmail or Outlook.com email account and then, click on your profile and choose View Account. Now, click on Change Password and enter your current password and then, click on Sign In. Call on +44-800-368-9064 if you want to know about the strong password.
    Hotmail Support Number UK

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...