You need to sign in to do that
Don't have an account?
adiaz
Apex trigger creates two records
Hello,
I have a trigger that creates is supposed to create a new record based on a status field of a different custom object. When i run the trigger, it creates 2 new records in the second custom object. Help solving why it is creating two instead of one is appreciated.
My code below:
Trigger:
trigger CreateTicket on Maintenance_Request__c(after update)
{
if(Trigger.isUpdate){
for(Maintenance_Request__c m: Trigger.new)
{
if(m.Status__c == 'Pending Support')
{
Support_Team_Request__c st = new Support_Team_Request__c();
st.Your_name__c = m.Your_Name__c;
st.Client_reported_issue__c = 'No';
st.Short_description__c = m.Short_Description__c;
st.Client_Name__c = m.Client_Name__c;
st.Description_of_Issue__c = m.Detailed_Description__c;
st.Mailbox__c = m.Mailbox__c;
st.Priority__c = 'medium';
st.Created_From_MTR__c = 'Yes';
st.Request_Type__c = 'production' ;
st.Participant_Name__c = m.Participant_Name__c;
st.Participant_ID__c = m.Participant_ID__c;
st.CC_Contact__c = m.CC_Contact__c;
insert st;
}
}
}
}
Test Class:
@isTest
private class CreateTicketTriggerTest {
static testMethod void myUnitTest() {
Maintenance_Request__c mr = new Maintenance_Request__c();
mr.Your_Name__c = 'Test User';
mr.Short_Description__c = 'Test request';
mr.Client_Name__c = '0015000000GibFx';
mr.Detailed_Description__c = 'Test maintenance request';
mr.Mailbox__c = 'test@example.org';
mr.Participant_Name__c = 'Test Participant';
mr.Participant_ID__c = '123';
mr.Request_Type__c = 'Account Merge';
mr.Request_Type__c = 'Account Merge';
insert mr;
mr.Status__C = 'Pending Support';
update mr;
}
}
Never mind. The problem was a workflow that occured when the status was changed causing the record to re update and shoot the trigger for a second time.
All Answers
Never mind. The problem was a workflow that occured when the status was changed causing the record to re update and shoot the trigger for a second time.
You want your trigger to fire only once when your mr.Status__c value changes to "Pending Support". In your case, it will fire every time your Maintenance_Request__c record is updated and when the Status__c value = "Pending Support".
So first, collect the old and the new values of the records from the trigger:
Then only fire the trigger the first time its Status__c value updates to "Pending Request":
Hope that gives you an idea.
Can you tell me the workaround that becuase I am facing the same issue right now.