You need to sign in to do that
Don't have an account?
OcoBri
Error on my first trigger
I'm writing a trigger that will:
Every time a new contact is created, of Record Type 'Consumer', I want to create a corresponding record in the master-detail custom object Compliance2__c. The only field that needs to be passed is the lookup value. The other fields on Compiance2__c are formulas.
The error I'm getting is: "Error: Compile Error: unexpected token: 'for' at line 5 column 4"
My code is:
Any help is appreciated.
Thank you!
Every time a new contact is created, of Record Type 'Consumer', I want to create a corresponding record in the master-detail custom object Compliance2__c. The only field that needs to be passed is the lookup value. The other fields on Compiance2__c are formulas.
The error I'm getting is: "Error: Compile Error: unexpected token: 'for' at line 5 column 4"
My code is:
trigger createCompliance on Contact (after insert) { List <Compliance2__c> compToInsert = new List <Compliance2__c> for (Contact c : Trigger.new) { //check if this is a Consumer being created if (c.RecordType.Name = 'Consumer') { //create a new Compliance for each new Consumer Compliance2__c i = new Compliance2__c (); i.Consumer__c = c.Id; //add to the list of Compliances to insert compToInsert.add(i); } //end if } //end for c //after loop, insert new Compliances insert complianceToInsert; }
Any help is appreciated.
Thank you!
List <Compliance2__c> compToInsert = new List <Compliance2__c>();
Looks like it should be a quick fix. You are just missing this snippet at the end of line 3 in your code:
( );
you can give c.name='Consumer'
But it's not working. I've added test Contacts and no Compliances are created.
trigger createCompliance on Contact (after insert) {
for (Contact c : Trigger.new) {
//check if this is a Consumer being created
if (c.RecordType.Name = 'Consumer') {
//create a new Compliance for each new Consumer
Compliance2__c newComp = new Compliance2__c ();
newComp.Consumer__c = c.Id;
insert newComp;
} //end if
} //end for c
}
Id consumerRecTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Consumer').getRecordTypeId();
and then replace if(c.RecordType.Name = 'Consumer') with ...
if(c.RecordTypeId == consumerRecTypeId)
But your "IF" will not ever meet because you only have one "=" sign. This needs to be two "==" otherwise it is trying to assign that value not compare.
trigger createCompliance on Contact (after insert) {
List <Compliance2__c> compToInsert = new List <Compliance2__c>();
for (Contact c : Trigger.new) {
//check if this is a Consumer being created
if (c.RecordType.Name == 'Consumer') {
Compliance2__c i = new Compliance2__c ();
i.Consumer__c = c.Id;
compToInsert.add(i);
}
}
}
The current code is this: