You need to sign in to do that
Don't have an account?
dgdeyo09
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]); }
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
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.
Thanks! This really helped
You are welcome