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
dgdeyo09dgdeyo09 

Way to check if one particular record exists?

Hi All,

 

Im trying to see if one particular record of my custom object exists in my trigger, but I think there is somthing wrong with my query. Any pointers would be greatly appreciated. 

 

trigger TriggerName on Custom__c (after insert) {

    
for (Custom__c c: Trigger.New){ 
        List<Custom2__c> C2s = new List<Custom2__c>([select id from Custom2__c where Custom_Field__c = c.Custom_Field__c  Limit 1]);

}

 

Best Answer chosen by Admin (Salesforce Developers) 
SarfarajSarfaraj

You missed a ':'.

trigger TriggerName on Custom__c (after insert) {
for (Custom__c c: Trigger.New){
List<Custom2__c> C2s = new List<Custom2__c>([select id from Custom2__c where Custom_Field__c = :c.Custom_Field__c Limit 1]);
}
}

This will work but I would recomend bulkifying the code. You may try the following approach,

trigger TriggerName on Custom__c (after insert) {
List<Id> l = new List<Id>();
for (Custom__c c: Trigger.New)
l.add(c.Custom_Field__c);
Map<Id, Custom2__c> m = new Map<Id, Custom2__c>();
for(Custom2__c c2 : [Select Id From Custom2__c Where Custom_Field__c in :l])
m.put(c2.Custom_Field__c, c2);
for (Custom__c c: Trigger.New){
Custom2__c C2 = m.get(c.Custom_Field__c);
//if c2 is not null you have the record in your respective custom object
}
}

You haven't specified the data type of your Custom_Field__c. I have assumed it to be Id. Please modify it as necessary.

All Answers

SarfarajSarfaraj

You missed a ':'.

trigger TriggerName on Custom__c (after insert) {
for (Custom__c c: Trigger.New){
List<Custom2__c> C2s = new List<Custom2__c>([select id from Custom2__c where Custom_Field__c = :c.Custom_Field__c Limit 1]);
}
}

This will work but I would recomend bulkifying the code. You may try the following approach,

trigger TriggerName on Custom__c (after insert) {
List<Id> l = new List<Id>();
for (Custom__c c: Trigger.New)
l.add(c.Custom_Field__c);
Map<Id, Custom2__c> m = new Map<Id, Custom2__c>();
for(Custom2__c c2 : [Select Id From Custom2__c Where Custom_Field__c in :l])
m.put(c2.Custom_Field__c, c2);
for (Custom__c c: Trigger.New){
Custom2__c C2 = m.get(c.Custom_Field__c);
//if c2 is not null you have the record in your respective custom object
}
}

You haven't specified the data type of your Custom_Field__c. I have assumed it to be Id. Please modify it as necessary.

This was selected as the best answer
dgdeyo09dgdeyo09

Thanks! This really helped

SarfarajSarfaraj

You are welcome