function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shamsi 110Shamsi 110 

How to Create a Parent object than its related child and than related grandchild and than related great grand child in trigger ?

Hello Friends.

I have Four objects in salesforce Project , Project Phase , Project Task, WBS.

Project Is master Project Phase Is child.
Project Phase is Master and Project task is child
Project Task is Master and WBS is child.
Diagram

In the system, there is a sample project, along with phases and associated tasks and WBS.
I want to create a sample record by copying these objects data.

I have a situation now i have three tasks records and i want to create tasks, phases, WBS of these tasks and associate this to new Project.

How do i achieve this?

In simple words i have task records and i have to insert first a new hardcoded project than associate these task and the phases of these tasks and WBS of these task to new hardcoded project.






Thanks
 
Waqar Hussain SFWaqar Hussain SF
Hi Shamsi, 

You can use external Id fiel to insert parent child records using one dml statements. Create a new text field on each parent object and mark it as External Id. See below example 
 
list<sObject> ListToInser = new list<sObject>();

Project__c p = new Project__c();
p.Name = 'Test Project';
p.External_Id__c = '1111';
ListToInser.add(p);

Project_Phase__c projPhase = new Project_Phase__c();
projPhase.Name = 'Phase 1';
Project__c proj = new Project__c(External_Id__c = '111');
projPhase.Project__r = proj;
ProjPhase.External_Id__c = '2222';
ListToInser.add(projPhase);

Project_Task__c task = new Project_Task__c();
task.Name =  'Task 2';
Project_Phase__c ph = new Project_Phase__c(External_Id__c = '2222';);
task.Project_Phase__r = ph;
ListToInser.add(projPhase);

Database.SaveResult[] results = Database.insert(ListToInser);

See below post, which may clarify more things.
https://developer.salesforce.com/forums/ForumsMain?id=9060G000000Bj6fQAC

Let me know If you have any quesiton.

Thanks
Shamsi 110Shamsi 110
Thanks for reply waqar.
Actually I have tasks lets say three task records

Task one
Id =123,name='Task one',Phase = 'Phase one'

Task two 
Id = 124,name ='Task two',Phase='Phase two'

Task three
Id=125,name ='Task three',Phase='Phase one'


Now I want to create 
One  Project (All Hardcoded Values )
Name = 'Test Project'

Two Phases 
1) Name : Phase One
Project = above Project id
Task one and three will be its children

2) Name : Phase two
Project = above Project Id
Task two will be its child

Three tasks (One is associated with Phase two, and two is associated with phase one).

You can see image to get some idea of schema
User-added image
Thanks,
Hasan Shamsi