Friday, May 27, 2022

How to Link a Child Record Every Time it's Created With An Existing/New Parent Record.

Lets take a use case when a child record has been created it should be automatically link to existing parent record ,in case if parent is not available it should create a parent and link the child record automatically.

The relationship between these objects is "Lookup Relationship" and the identifier to map the child with parent and the identifier when to create a new parent will be discussed below.

Simple use case here is we will have daily time sheet entries of an employee and all these daily time sheet entries should get linked under weekly time sheet entry which is like one entry for one week with 7 daily time sheet under same parent.

We can assume child object as "Daily_Time_Sheet__c" and parent object as "Weekly_Time_Sheet__c". On parent object we will have one field with name as "Parent_User_Week_Start__c(which is an external id) " which is the combination of user id and start date of the week of a given date in "Daily_Time_Sheet__c".The field name in child would be something like "ChildUserIdWeekStrartDate__c".

Source Code:

Trigger DailyTimeSheetTrigger On Daily_Time_Sheet__c(after insert)
{
	List<Weekly_Time_Sheet__c> listWTSToUpsert = new List<Weekly_Time_Sheet__c>();
	List<Daily_Time_Sheet__c> listDTSUpdate = new List<Daily_Time_Sheet__c >();
	Map<String,id> mapHours = new Map<String,id>();
	set<string> setUniqueParent = new set<string>();

	for(Daily_Time_Sheet__c dts:Trigger.new)
	{
		if(dts.ChildUserIdWeekStrartDate__c!=null && dts.Weekly_Time_Sheet__c==null)
		{
			Weekly_Time_Sheet__c wts = new Weekly_Time_Sheet__c();
			wts.Parent_User_Week_Start__c = dts.Chi;
			if(!setUniqueParent.contains(wts.Parent_User_Week_Start__c))
			{
			  listWTSToUpsert.add(wts);
			  setUniqueParent.add(wts.Parent_User_Week_Start__c);
			}
		}
	}
	
	try
	{
		if(!listWTSToUpsert.isEmpty())
		  Database.UpsertResult[] wtsUpsertResult = Database.upsert(listWTSToUpsert,Weekly_Time_Sheet__c.Parent_User_Week_Start__c,false);
	  
		for(Weekly_Time_Sheet__c ws:listWTSToUpsert)
		{
			mapHours.put(ws.Parent_User_Week_Start__c,ws.id);
		}


		for(Daily_Time_Sheet__c dts:[SeLEcT id ,ChildUserIdWeekStrartDate__c,Weekly_Time_Sheet__c FROM Daily_Time_Sheet__c WHERE ID IN: Trigger.new])
		{
			if(dts.ChildUserIdWeekStrartDate__c!=null && dts.Weekly_Time_Sheet__c==null)
			{
				if(mapHours.containsKey(bh.ChildUserIdWeekStrartDate__c))
				{
					bh.Weekly_Time_Sheet__c = mapHours.get(guid);
					listDTSUpdate.add(bh);
				}
			}
		}
		
		if(!listDTSUpdate.isEmpty())
			Database.SaveResult[] wbhUpsertResult2 = Database.update(listDTSUpdate,false);
	}
	catch(exception e)
	{
		system.debug('exception ..'+e);
	}
}

Hope this helps you..Enjoy..!


Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.