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
skiptomylou11skiptomylou11 

Fill the Record field name of a child object via trigger?

Hi,

 

I am new to Apex and triggers...

 

This is what I want to do:

I have a Child_Object__c to Opportunity. The record name field is set to Text (80). 

On creation (or saving) of a child record I would like the record name field to be filled with the name of the parent opportunity. Even though it is set up via Master-Detail relationship there is always just one related child record required so there is no issue with the text being unique.

 

I really appreciate your support.

Cheers! 

Starz26Starz26

trigger myTrg on Child_Object__c (before update, before insert){

 

//Build a list of Unique Child Object IDs in this trigger

set<id> idCO = new set<id>();

 

//Populate id list

for(Child_Object__c a : trigger.new)

  idCO.add(a.id)

 

//Build a map from the child Object ID to the parent object name

Map<id,Parent_Object__c> mapCOtoPO = [Select Name__c FROM Parent_Object__c WHERE id IN :idCO];

 

//for each record in the trigger

for(Child_Object__c co : trigger.new)

 

   //Get the related Parent Object Name from the map and set the field on the child object to that name

   co.Parent_Object__c = mapCOtoPO.get(co.id).Name__c;

 

}

 

 

 

 

 

skiptomylou11skiptomylou11

Dear Starz26,

Many thanks for the quick response.

When I try to implement the code I however get the following error message:

Error: Compile Error: unexpected token: 'Map' at line 11 column 0

Any idea what the issue might be?

Thank you! 

Starz26Starz26

Yea, I forgot a semicolon on the previous line:

 

trigger myTrg on Child_Object__c (before update, before insert){

 

//Build a list of Unique Child Object IDs in this trigger

set<id> idCO = new set<id>();

 

//Populate id list

for(Child_Object__c a : trigger.new)

  idCO.add(a.id);

 

//Build a map from the child Object ID to the parent object name

Map<id,Parent_Object__c> mapCOtoPO = [Select Name__c FROM Parent_Object__c WHERE id IN :idCO];

 

//for each record in the trigger

for(Child_Object__c co : trigger.new)

 

   //Get the related Parent Object Name from the map and set the field on the child object to that name

   co.Parent_Object__c = mapCOtoPO.get(co.id).Name__c;

 

}