Ideally this trigger would look to see if a record of a certain record type has a yes flag and set it to no before inserting a new record (all under the same related Contact_c). More specifically, I would like to take the value of Contact_c from the incoming record and query all MyActivity__c records in Salesforce to gather a list that match (including the other query parameters – flag/record type/etc.).
This trigger I've written seems to gather all MyActivity__c records for every Contact in the database and then iterates through them, setting the flag of their records to NO. Hoping someone can point out where I'm going wrong. Thank you.
Trigger:
trigger MyTrigger on MyActivity__c (before insert) {
List<MyActivity__c> contactrecords = new List<MyActivity__c>();
ID rtId = [SELECT Id FROM RecordType WHERE Name = 'Record Type Name'].Id;
for(MyActivity__c r: trigger.new){
if(r.RecordTypeId == rtId){
String c = r.Contact__c;
String i = r.Id;
List<MyActivity__c> act = [SELECT Contact__c FROM MyActivity__c WHERE Contact__c = :c AND Id != :i AND Flag__c = 'Yes' AND RecordTypeId IN (SELECT Id FROM RecordType WHERE Name = 'Record Type Name')];
for (MyActivity__c contactlist : act){
contactlist.Flag__c = 'No';
contactrecords.add(contactlist);
}
}
}
if(contactrecords.size()>0) {
update contactrecords;
}
}
Best Answer
What exactly is your requirement? it is a little hazy to understand. As far as I can tell you want to do the following.
A couple of questions
That being said there are a number of issues with this trigger, starting with the fact that you are executing a SOQL query within a for loop which is against best practice. Always try to execute queries outside of any loop structure.
Also when you query a Recordtype you should also try to query the objecttype not just the name and preferably the developer name (Usually the same as name with underscores, but the name may change, hence why its good to query developername)
Here is an example of how you might write this trigger based on what I can gather from your requirements, with comments explaining step by step.