You need to sign in to do that
Don't have an account?

Trigger Doesn't Work When I Specify Record Type
I wrote a trigger that is supposed to create records on a related object called Opportunity Heading every time a new Opportunity is created with the record type RPM.
When I don't specify the Opportunity record type in the trigger, it creates the records the way it should. However, if a user creates a Opportunity of another record type, validation rules on those other record types cause system.dmlexception errors:
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Must select at least one product proposal type.: []
I only want this trigger to run if the opportunity created has a "RPM" recordtype, but when I add that to the trigger, it doesn't create the related list record. Any ideas what I'm doing wrong?
Here is the trigger that creates the records (but need record type specified):
Trigger AddOppHdgtoRelatedList on Opportunity (after insert)
{
List<Opportunity_Headings__c> OHdg = new List<Opportunity_Headings__c>();
for (Opportunity O : Trigger.new)
{
{
Opportunity_Headings__c OH = new Opportunity_Headings__c(Heading__c = O.Main_Heading__c,Opportunity__c = O.ID, Account__c = O.Accountid);
OHdg.add(OH);
}
}
if(OHdg.size() > 0)
insert OHdg;
}
Here is the trigger with record type specified that does not work:
Trigger AddOppHdgtoRelatedList on Opportunity (after insert)
{
List<RecordType> OpprtID = [Select Id From RecordType
where sObjectType='Opportunity' and Name='RPM'];
Set<RecordType> s=new Set<RecordType>();
s.addAll(OpprtId);
List<Opportunity> Opps = new List<Opportunity>();
List<Opportunity_Headings__c> OHdg = new List<Opportunity_Headings__c>();
for (Opportunity O : Trigger.new)
{
If (s.contains(o.RecordType))
{
Opportunity_Headings__c OH = new Opportunity_Headings__c(Heading__c = O.Main_Heading__c,Opportunity__c = O.ID, Account__c = O.Accountid);
OHdg.add(OH);
}
}
if(OHdg.size() > 0)
insert OHdg;
}
Add a few System.debug to see what your code is doing.
System.debug(s);
System.debug(o.RecordType); This should be o.RecordTypeId
I would create a map to store the RecordType records:
Map<Id, RecordType> theMap = new Map<Id, RecordType>([Select Id, Name From RecordType
where sObjectType='Opportunity' and Name='RPM']);
then compare against the map
If (theMap.containsKey(o.RecordType)) {....
All Answers
Add a few System.debug to see what your code is doing.
System.debug(s);
System.debug(o.RecordType); This should be o.RecordTypeId
I would create a map to store the RecordType records:
Map<Id, RecordType> theMap = new Map<Id, RecordType>([Select Id, Name From RecordType
where sObjectType='Opportunity' and Name='RPM']);
then compare against the map
If (theMap.containsKey(o.RecordType)) {....
Thank you! When I modified my code to save the ids to a map instead of a set, it worked with no problems.