You need to sign in to do that
Don't have an account?
KatherineC
Trigger Error: Duplicate variable
I have a custom object Pint, I want it create new pint again automatically once a pint's status is Closed. I got an error message while creating a trigger, please help.
Error Error: Compile Error: Duplicate variable: p (attempt to re-create the variable with type: Pint__c) at line 4 column 32
trigger CreatePin on Pint__c (after update) {
for (Pint__c p : Trigger.new) {
if (p.Status == 'Closed') {
Pint__c p = new Pint__c();
p.Account__c = c.AccountId;
insert p;
}
}
}
Error Error: Compile Error: Duplicate variable: p (attempt to re-create the variable with type: Pint__c) at line 4 column 32
trigger CreatePin on Pint__c (after update) {
for (Pint__c p : Trigger.new) {
if (p.Status == 'Closed') {
Pint__c p = new Pint__c();
p.Account__c = c.AccountId;
insert p;
}
}
}
Change the new Pint you creating to a different variable:
EX:
Pint__c newPint = new Pint__c();
newPint.Account = c.AccountId;
Also, it is best practice not have have DML inside a for loop. If you do, you code can error out due to governor limits.
https://developer.salesforce.com/page/Apex_Code_Best_Practices
To avoid governor limits issues, before your for loop, create a new List of Pint__c ==> List<Pint__c> pints = new List<Pint__c>();
Then instead of inserting your pint inside the for loop, add the new Pint to the list. Then if your list has any pints, insert the List.
All Answers
Use below code:
Change the new Pint you creating to a different variable:
EX:
Pint__c newPint = new Pint__c();
newPint.Account = c.AccountId;
Also, it is best practice not have have DML inside a for loop. If you do, you code can error out due to governor limits.
https://developer.salesforce.com/page/Apex_Code_Best_Practices
To avoid governor limits issues, before your for loop, create a new List of Pint__c ==> List<Pint__c> pints = new List<Pint__c>();
Then instead of inserting your pint inside the for loop, add the new Pint to the list. Then if your list has any pints, insert the List.