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
Salesforce Dev in TrainingSalesforce Dev in Training 

Before Insert Trigger - Speciality Objects

I'd like to create code that would be a before insert I believe.

I have a Custom Object titled, "Speciality Objects". This object has a record type titled "HERO Stories". There is a lookup to Contacts on this object (not a Master Detail).

The code needs to lookup to the Contact and pull the Contact's "First Name" (from Contact) + "Last Name" (from Contact) + HERO Story (plain text) into a field.

How is this possible?


Here is the code, Try this code. it is working fine for me. 
Dont forget to mark best answer if the code is working correct.

trigger abc on Speciality_Objects__c (before insert) {
    Set<Id> ContactId = new Set<Id>();
    Map<Id, String> ContactMap = new Map<Id, String>();
    Map<Id, String> ContactMap1 = new Map<Id, String>();
    for(Speciality_Objects__c so: Trigger.New){ 
     ContactId.add(so.ContactName__c); //ContactName__c is a custom Lookup field
    for(Contact c : [Select FirstName from Contact where Id IN : ContactId]){
        ContactMap.put(c.Id, c.FirstName);
    for(Contact c : [Select LastName from Contact where Id IN : ContactId]){
        ContactMap1.put(c.Id, c.LastName );
    for(Speciality_Objects__c soc: Trigger.New){
        soc.Result_Field__c= soc.Hero_Story_Field__c+' '+ ContactMap.get(soc.ContactName__c)+' '+ ContactMap1.get(soc.ContactName__c);

Result will be
herostoryfield contactFirstName contactLastName

change the order according to you.

Thanks & Regards,

Santosh Sriram 2310Santosh Sriram 2310
Please do not write a trigger for the same. Use can create formula field to get this work. If you want this to happen only on insert then use the following formula
IF(ISNEW(), Contact__r.FirstName  + ' - ' + Contact__r.LastName  + ' - ' + $RecordType.Name, '')