+ Start a Discussion
John StamersJohn Stamers 

Trigger to create mulitple tasks from a single record creation

Hi all,

I'm looking for some guidance on how I would go about writing a trigger that creates a task for a number of records. What I want to do is that when a new record is created under my object Blood_Draw a task is assigned to all of the records of another object Subjecct. Both the Blood_Draw and Subject objects have a child relationship with another object I have called Trial. The Blood_Draw records are each related to a trial so I would only want the subject records that are also related to the same trial to be updated.

Any help would be much appreciated!


Best Answer chosen by John Stamers
Ramu_SFDCRamu_SFDC
Hi John,

Here is the sample code. This is just to give you an idea to startup. The codes needs to be improvised for bulk operations

- ChildAcct1__c & ChildAcct2 are two child objects related to Account.
- When a new ChildAcct1 record is created, it runs the below trigger finds all the ChildAcct2 records that are related to the same account and creates Task on those.

trigger Child1 on ChildAcct1__c (after insert) {
    for(childacct1__c c1:trigger.new){
        List<childacct2__c> c2=[select id,Account__c from childacct2__c where Account__c=:c1.Account__c];
        list<task> tasklist=new list<task>();
        for(childacct2__c c2a:c2){
            Task tsk=new Task();
            tsk.WhatId=c2a.id;
            tsk.Subjectb='testing';
            tasklist.add(tsk);
        }
        insert tasklist;       
    }
}

Please mark this as the best answer if it resolves your requirement.

All Answers

Ramu_SFDCRamu_SFDC
Hi John,

Here is the sample code. This is just to give you an idea to startup. The codes needs to be improvised for bulk operations

- ChildAcct1__c & ChildAcct2 are two child objects related to Account.
- When a new ChildAcct1 record is created, it runs the below trigger finds all the ChildAcct2 records that are related to the same account and creates Task on those.

trigger Child1 on ChildAcct1__c (after insert) {
    for(childacct1__c c1:trigger.new){
        List<childacct2__c> c2=[select id,Account__c from childacct2__c where Account__c=:c1.Account__c];
        list<task> tasklist=new list<task>();
        for(childacct2__c c2a:c2){
            Task tsk=new Task();
            tsk.WhatId=c2a.id;
            tsk.Subjectb='testing';
            tasklist.add(tsk);
        }
        insert tasklist;       
    }
}

Please mark this as the best answer if it resolves your requirement.
This was selected as the best answer
John StamersJohn Stamers
Thanks Ramu, this is a huge help!