Thursday, 15 January 2015

Trigger on Parent Object to copy the fields on its child record in Salesforce!!

Hi Guys!!

Its been long time since I have been here. My obsession with salesforce has taken next level.

Still, I love writing triggers. I know all these are very small triggers. But it may help beginners who are trying to connect to salesforce.

Anyways, lets start with another trigger(Only for beginners) .

Scenario:-

I have to replicate a field of parent object to all its child records. It is very simple scenario for experience people.

Here is the code for you folks....

Trigger replicateFieldsOnChild on Parent (After update){
 Set<id> setOfParentId = new Set<Id>();
 for(Parent pt : trigger.new){
  setOfParentId.add(pt.id);
 }
 List<Child> listChild = new List<Child>([Select id, parentId from child where ParentId in: setOfParentId]);
 List<Child> updatedlistChild = new List<Child>
 for(Parent pt : trigger.new){
  for(Child ch : listChild){
   ch.field = pt.field;
   updatedlistChild.add(ch);
  }
 }
 Update updatedlistChild;
}


Remember :-  There are may ways of doing a job . You may find more simpler and efficient way. keep Exloring!


Happy coding 

Cheers
Ankush
ankushsalesforce@gmail.com

















2 comments:

  1. is the reverse is possible? i have a value in child object and that has to be copied to Parent object. thanks in advance

    ReplyDelete
  2. i need to populate email id of all associated contacts on account page in a text field as commma seperated list.how to do it. the trigger should work on insert,delete and update.


    i have tried doing this,let me know howfar i am correct?


    trigger AccEmail on Contact (before insert,after update) {
    String Em='';
    if(trigger.isInsert || trigger.isUpdate ){
    Set accID = New Set ();
    For (Contact con: Trigger.new) {
    if (con.AccountId != Null ) {
    accID.add (con.AccountId);
    }
    }

    if (accID.size ()> 0) {
    List upAccList = new List ();

    for(Account acc : [Select id, EmailId__c,
    (Select Id, Email From Contacts)
    From Account Where Id In : accID])
    {
    for(Contact con : acc.contacts)
    {
    if(con.Email != null)
    {
    Em = Em + ', ' + con.Email;
    }
    acc.Contact_Names__c = names;
    }
    upAccList.add(acc);
    }
    update upAccList;
    }
    }

    ReplyDelete

oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...