You need to sign in to do that
Don't have an account?
ShayneO
Trigger Creating 2 Records
I'm attempting to write a trigger to create a new custom object record, when a Contact record meets specific criteria. The problem is, the trigger is creating 2 records instead of 1.
Code below:
trigger createPreferenceWeb on Contact (before update) { List <rethink3__Requirements__c> prefToInsert = new List <rethink3__Requirements__c> (); for (Contact c : Trigger.new) { if (c.Web_To_Lead__c = true){ rethink3__Requirements__c p = new rethink3__Requirements__c (); p.rethink3__Contact__c = c.Name; p.rethink3__Contact__c = c.Id; p.Down_Payment_Available__c = c.Down_Payment_Available__c; p.Maximum_Price__c = c.Maximum_Price__c; prefToInsert.add(p); } } try { insert prefToInsert; } catch (system.Dmlexception e) { system.debug (e); } }
if (c.Web_To_Lead__c == true){
rethink3__Requirements__c p = new rethink3__Requirements__c ();
// p.rethink3__Contact__c = c.Name;remove this line
p.rethink3__Contact__c = c.Id;
p.Down_Payment_Available__c = c.Down_Payment_Available__c;
p.Maximum_Price__c = c.Maximum_Price__c;
prefToInsert.add(p);
}
}
try {
insert prefToInsert;
} catch (system.Dmlexception e) {
system.debug (e);
}
}
All Answers
Try with after update trigger event.
i think you click your save button two times ...according to ur code as many time u save it will create record
use trigger.old to compare with old value
Would it make more sense to use after insert? Since I only want the new record to be created if the parent record meets the criteria at the time it is created.
Apex trigger createPreferenceWeb caused an unexpected exception, contact your administrator: createPreferenceWeb: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.createPreferenceWeb: line 11, column 1
Here after trigger is good approach, because once the contact changes are save into database the recorde will create.
Can you correct errors in your code.
If rethink3__contact__c is lookup field then remove the line p.rethink3__Contact__c = c.Name; in your code. In your code you ar assigning value value twice to that filed.
2. correct If condition c.web_To_lead__c == true from c.web_To_lead__c == true.
if (c.Web_To_Lead__c == true){
rethink3__Requirements__c p = new rethink3__Requirements__c ();
// p.rethink3__Contact__c = c.Name;remove this line
p.rethink3__Contact__c = c.Id;
p.Down_Payment_Available__c = c.Down_Payment_Available__c;
p.Maximum_Price__c = c.Maximum_Price__c;
prefToInsert.add(p);
}
}
try {
insert prefToInsert;
} catch (system.Dmlexception e) {
system.debug (e);
}
}
Any thoughts?