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
Isak Stensmar 8Isak Stensmar 8 

Help creating a trigger that links two objects of the same object type

Hi,

I´m trying to create a trigger that link two objects of the same object type.
This is what I´ve come up with so far...
Trigger CheckIfExists on MonthlyDonor__c (before insert) 
{

    MonthlyDonor__c md_Object;
    
    List<MonthlyDonor__c> md1=[Select id from MonthlyDonor__c where MonthlyDonor__c.SSN__c=:trigger.new[0].SSN__c];
    if(md1.size()>0)
    {
        md_Object = md1[0];
        
        md_Object.Link_Objects__c = trigger.new[0].id;
    }
}
The trigger should check if an object (monthlydonor) allready exists in the database by comparing the SSN number from the object im trying to insert.

If md1.size()>0 it indicates that an objects exists and I should now link these objects together.

This is where I´m stuck. I´ve looked at relationships between objects but haven´t figured it out yet and could use some help.
Link_Objects__c is of the type Lookup and I thought the easiest way to link two objects was with the id, but I cant see any value in the lookup field for my object when I´m testing it.

Any help would be appreciated.

Regards,
Isak
 
Best Answer chosen by Isak Stensmar 8
Mahesh DMahesh D
Hi Isak,

Please find the modified code:
 
Trigger CheckIfExists on MonthlyDonor__c (before insert) {
    Set<String> ssnStrSet = new Set<String>();
    for(MonthlyDonor__c md: Trigger.new) {
        if(md.SSN__c != null)
            ssnStrSet.add(md.SSN__c);
    }
    
    if(!ssnStrSet.isEmpty()){
        Map<String, MonthlyDonor__c> existMDMap = new Map<String, MonthlyDonor__c>();
        for(MonthlyDonor__c md : [Select Id, SSN__c, CreatedDate from MonthlyDonor__c where SSN__c IN: ssnStrSet ORDER BY CreatedDate ASC]) {
            existMDMap.put(md.SSN__c, md);
        }
        
        if(!existMDMap.isEmpty()) {
            for(MonthlyDonor__c md: Trigger.new) {
                if(md.SSN__c != null && existMDMap.get(md.SSN__c) != null)
                    md.Link_Objects__c = existMDMap.get(md.SSN__c).Id;
            }
        }
    }   
}

Please do let me know if it helps you.

Regards,
Mahesh

All Answers

Ravi Dutt SharmaRavi Dutt Sharma
Hey Isak,

Few things you need to know before writing a trigger :
1) In before insert event, id of the record is not present. so line 13 will not work. Record id would be generated in after insert event.
2) Your trigger is not bulkified. If I upload 200 records using dataloader, you trigger will only process the first record. Make your trigger bulikified so that it handles all the records coming in Trigger,new
Mahesh DMahesh D
Hi Isak,

Please find the modified trigger:

Here I considered:

(1) Bulkified the trigger.
(2) Naming Convention.
(3) Executed the code in my DE environment and looks good. 

 
Trigger CheckIfExists on MonthlyDonor__c (before insert) {
    Set<String> ssnStrSet = new Set<String>();
    for(MonthlyDonor__c md: Trigger.new) {
        if(md.SSN__c != null)
            ssnStrSet.add(md.SSN__c);
    }
    
    if(!ssnStrSet.isEmpty()){
        Map<String, MonthlyDonor__c> existMDMap = new Map<String, MonthlyDonor__c>();
        for(MonthlyDonor__c md : [Select Id, SSN__c from MonthlyDonor__c where SSN__c IN: ssnStrSet]) {
            existMDMap.put(md.SSN__c, md);
        }
        
        if(!existMDMap.isEmpty()) {
            for(MonthlyDonor__c md: Trigger.new) {
                if(md.SSN__c != null && existMDMap.get(md.SSN__c) != null)
                    md.Link_Objects__c = existMDMap.get(md.SSN__c).Id;
            }
        }
    }   
}

Also follow the best practices to write the Trigger:

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

Please do let me know if it helps you.

Regards,
Mahesh
Isak Stensmar 8Isak Stensmar 8
Hi Mahesh,

Your code works fine and I can see that the records are linked.
But this only solved some parts of my problem, maybe because I wasn´t explaining good enough.

With your code the record is linked with the last inserted record,correct? That´s what happens at least when I insert more than two records.
What I want to accomplish is, instead of linking to the last inserted I want all incoming records to link to the first one.

So if we insert 2ndRec and 3rdRec they will be linked as:
2ndRec ->1stRec
3rdRec ->1stRec
Instead of 
2ndRec ->1stRec
3rdRec ->2ndRec
4thRec ->3rdRec ...

All this is done because I want to have better statistics.
For example:
I have a donor with the donation amount as 200 for 2 years.
Then it´s changed to 300 2 years and 500 for 3 years.
If I update the record to 500, it will say that the donation amount has been 500 for 4 years already, where it should´ve been 200 and 100.
That is why I want to link the records so I can get proper statistics.
Maybe you can solve it in another way, but linking the records was the first that came to mind.
 
Mahesh DMahesh D
Hi Isak,

Please find the modified code:
 
Trigger CheckIfExists on MonthlyDonor__c (before insert) {
    Set<String> ssnStrSet = new Set<String>();
    for(MonthlyDonor__c md: Trigger.new) {
        if(md.SSN__c != null)
            ssnStrSet.add(md.SSN__c);
    }
    
    if(!ssnStrSet.isEmpty()){
        Map<String, MonthlyDonor__c> existMDMap = new Map<String, MonthlyDonor__c>();
        for(MonthlyDonor__c md : [Select Id, SSN__c, CreatedDate from MonthlyDonor__c where SSN__c IN: ssnStrSet ORDER BY CreatedDate ASC]) {
            existMDMap.put(md.SSN__c, md);
        }
        
        if(!existMDMap.isEmpty()) {
            for(MonthlyDonor__c md: Trigger.new) {
                if(md.SSN__c != null && existMDMap.get(md.SSN__c) != null)
                    md.Link_Objects__c = existMDMap.get(md.SSN__c).Id;
            }
        }
    }   
}

Please do let me know if it helps you.

Regards,
Mahesh
This was selected as the best answer
Isak Stensmar 8Isak Stensmar 8
Hi Mahesh,

Thank you, it works!
Just had to change from ASC to DESC but after that it did what I wanted. :)

Regards,
Isak