• stefandl
  • NEWBIE
  • 0 Points
  • Member since 2010

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 2
    Replies

Hello, I've created a trigger in order to create a case when a new product is added to an opportunity, according some rules.

But now, for a product added case is created more then once.

 

This is the trigger:

 

 

trigger NewProductAdded on OpportunityLineItem (after insert) {

//Query for Case record types
     List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Case' and isActive=true];
     
//Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> CampaignsRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
     CampaignsRecordTypes.put(rt.Name,rt.Id);
     
//Query for Users 

    List<User> users = [Select Name, Id From User];
    
//Create a map between the User Name and Id for easy retrieval

     Map<String,String> CaseUsers = new Map<String,String>{};
     for(User  usr: Users)
     CaseUsers.put(usr.Name,usr.Id);
     
for (OpportunityLineItem oli : Trigger.new) 
 { 
     if (oli.Implementation_DirectTrack__c == 'Yes'& (oli.Approval_status__c == 'Approved by AD'))
        
    { 
       Case c = new Case ( 
       Opportunity__c = oli.OpportunityId, 
       Status = 'New', 
       Origin = 'Web', 
       Type = 'Internal Case', 
       Reason = 'Add Campaign to R-ADserver', 
       Description = 'Hello, a new product has been added. Please add campaign to R-Adserver',
       R_Adserver_Status__c = '',
       RecordTypeId=CampaignsRecordTypes.get('Traffic'),
       Account_Manager__c = oli.Account_Manager__c,
       OwnerId = CaseUsers.get('Traffic List') 
       ); 
       insert c; 
    }   
     else if (oli.Implementation_DirectTrack__c == 'No' & (oli.Approval_status__c == 'Approved by AD') )
    { 
       Case c = new Case ( 
       Opportunity__c = oli.OpportunityId, 
       Status = 'New', 
       Origin = 'Web', 
       Type = 'Internal Case', 
       Reason = 'Add Campaign to Emediate', 
       Description = 'Hello, a new product has been added. Please add campaign to Emediate',
       RecordTypeId=CampaignsRecordTypes.get('Traffic'),
              Account_Manager__c = oli.Account_Manager__c,
       OwnerId = CaseUsers.get('Traffic List')  
       ); 
       insert c; 
    } 
    else { } 
 }         

}

 

 

Any idea about how to fix it?

 

Many thanks in advance,

 

Stefano Di Leone

 

 

Hello,

 

I've created a trigger and corresponding class test in sandbox.

Test in SB works perfectly, but during deployment in production an error occurred.

 

Trigger is:

 

 

trigger NewCaseFromOpp on Opportunity (after update) {

//Query for Case record types
     List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Case' and isActive=true];
     
//Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> CampaignsRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
     CampaignsRecordTypes.put(rt.Name,rt.Id);
     
     
//Query for Users 

    List<User> users = [Select Name, Id From User];
    
//Create a map between the User Name and Id for easy retrieval

     Map<String,String> CaseUsers = new Map<String,String>{};
     for(User  usr: Users)
     CaseUsers.put(usr.Name,usr.Id);

 
 for (Opportunity opp : Trigger.new) 
 { 
    if ( (opp.approval_status__c == 'Approved by AD' ) &&
         (trigger.oldMap.get(opp.id).approval_status__c != 'Approved by AD' ) && 
         (opp.Implementation_DirectTrack__c == 'Yes') )
    { 
       Case c = new Case ( 
       Opportunity__c = opp.Id, 
       Status = 'New', 
       Origin = 'Web', 
       Type = 'Internal Case', 
       Reason = 'Campaign  Setup', 
       Subject = 'New Direct Track Implementation', 
       RecordTypeId=CampaignsRecordTypes.get('Traffic'),
       OwnerId = CaseUSers.get('Traffic List') ); 
       insert c; 
    } 
    else if ((opp.approval_status__c == 'Approved by AD' ) &&
         (trigger.oldMap.get(opp.id).approval_status__c != 'Approved by AD' ) && 
         (opp.Implementation_DirectTrack__c == 'No'))
    { 
       Case c = new Case ( 
       Opportunity__c = opp.Id, 
       Status = 'New', 
       Origin = 'Web', 
       Type = 'Internal Case', 
       Reason = 'Campaign  Setup', 
       Subject = 'New Affiliation Campaign', 
       RecordTypeId=CampaignsRecordTypes.get('Traffic'),
       OwnerId = CaseUSers.get('Traffic List')  ); 
       insert c; 
    } 
    else
    {
    } 
 } 
}

 

 

Apex Test:

 

 

/**
 * This class tests the trigger named AddCampaign.
 */
@isTest
private class CaseFromOpp{

    static testMethod void TriggersTest() {       
                    
//Data Prep
        
        User usr = [Select Id,Name,ProfileId,TimeZoneSidKey,LocaleSidKey,EmailEncodingKey,LanguageLocaleKey  from User limit 1];
        User user1 = new User ();
        user1.LastName = 'Tester';
        user1.ProfileId = usr.ProfileId;
        user1.TimeZoneSidKey = usr.TimeZoneSidKey;
        user1.LocaleSidKey = usr.LocaleSidKey;
        user1.EmailEncodingKey = usr.EmailEncodingKey;
        user1.LanguageLocaleKey = usr.LanguageLocaleKey;
        user1.alias = 'tst';
        user1.Email = 'tester@test.com';
        user1.Username = 'tester@test.com';  
        insert user1;
        
//Create Account, Opportunity, Product, etc.
        Account acct1 = new Account(name='test Account One1');
        acct1.Type = 'Advertiser';
        insert acct1;
        
        
//Create Opportunity1 on Account
        Opportunity Oppty1 = new Opportunity(name='test Oppty One1');
        Oppty1.AccountId = acct1.Id;
        Oppty1.StageName = 'Test';
        Oppty1.CloseDate = Date.today();
        Oppty1.AED__Campaign_Start_Date__c = Date.today();
        Oppty1.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty1.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty1.AED__Country__c = 'Spain';
        Oppty1.Campaign_Name_Agreement__c = 'test Oppty One1' ;
        Oppty1.Implementation_DirectTrack__c = 'Yes';
        Oppty1.Implementation_DT_Status__c = '1. Create Campaign';
        Oppty1.Approval_Status__c = 'Waiting for Approval';
       
        insert Oppty1;    
   
//Create Opportunity2 on Account
        Opportunity Oppty2 = new Opportunity(name='test Oppty One2');
        Oppty2.AccountId = acct1.Id;
        Oppty2.StageName = 'Test';
        Oppty2.CloseDate = Date.today();
        Oppty2.AED__Campaign_Start_Date__c = Date.today();
        Oppty2.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty2.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty2.AED__Country__c = 'Spain';
        Oppty2.Campaign_Name_Agreement__c = 'test Oppty One2' ;
        Oppty2.Implementation_DirectTrack__c = 'No';
        Oppty2.Approval_Status__c = 'Waiting for Approval';   
        
        insert Oppty2;      
    
        test.starttest();    

        Oppty1.Approval_Status__c = 'Approved by AD'; 
        Oppty2.Approval_Status__c = 'Approved by AD';
        update Oppty1;
        update Oppty2;
        
        test.stoptest();
   
    }

}

 

 

Error is:

 

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>Another user has already selected this username.<br>Please select another.: [Username]", Failure Stack Trace: "Class.CaseFromOpp.TriggersTest: line 22, column 9 External entry point"

 

Any suggestions?

 

Thanks,

 

Stefano

 

 

Hello,

 

I'm having problems with a test on two triggers. Both are working correctly but when I execute the apex test I'm receiving the message: 

 

System.LimitException: Too many SOQL queries: 21

 

Trigger.NewCaseFromOpp: line 4, column 32

 

The trigger is: 

 

 

trigger NewCaseFromOpp on Opportunity (after update) {

//Query for Case record types
     List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Case' and isActive=true];
     
//Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> CampaignsRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
     CampaignsRecordTypes.put(rt.Name,rt.Id);
     
     
//Query for Users 

    List<User> users = [Select Name, Id From User];
    
//Create a map between the User Name and Id for easy retrieval

     Map<String,String> CaseUsers = new Map<String,String>{};
     for(User  usr: Users)
     CaseUsers.put(usr.Name,usr.Id);

 
 for (Opportunity opp : Trigger.new) 
 { 
    if ( (opp.approval_status__c == 'Approved by AD' ) &&
         (trigger.oldMap.get(opp.id).approval_status__c != 'Approved by AD' ) && 
         (opp.Implementation_DirectTrack__c == 'Yes') )
    { 
       Case c = new Case ( 
       Opportunity__c = opp.Id, 
       Status = 'New', 
       Origin = 'Web', 
       Type = 'Internal Case', 
       Reason = 'Campaign  Setup', 
       Subject = 'New Direct Track Implementation', 
       RecordTypeId=CampaignsRecordTypes.get('Traffic'),
       OwnerId = CaseUSers.get('Traffic List') ); 
       insert c; 
    } 
    else if ((opp.approval_status__c == 'Approved by AD' ) &&
         (trigger.oldMap.get(opp.id).approval_status__c != 'Approved by AD' ) && 
         (opp.Implementation_DirectTrack__c == 'No'))
    { 
       Case c = new Case ( 
       Opportunity__c = opp.Id, 
       Status = 'New', 
       Origin = 'Web', 
       Type = 'Internal Case', 
       Reason = 'Campaign  Setup', 
       Subject = 'New Affiliation Campaign', 
       RecordTypeId=CampaignsRecordTypes.get('Traffic'),
       OwnerId = CaseUSers.get('Traffic List')  ); 
       insert c; 
    } 
    else
    {
    } 
 } 
}

The goal of this trigger is inserting a case (depending on some conditions on Opportunity) populating some fields and assigning to a specific Record Type and Owner.

 

The test is:

 

 

/**
 * This class tests the trigger named AddCampaign.
 */
@isTest
private class TriggerCampaignAndCaseTest {

    static testMethod void TriggerCampaignAndCaseTest() {       
                    
//Data Prep
        
        User user = [Select Id,Name,ProfileId,TimeZoneSidKey,LocaleSidKey,EmailEncodingKey,LanguageLocaleKey  from User limit 1];
        User user1 = new User ();
        user1.LastName = 'Tester';
        user1.ProfileId = user.ProfileId;
        user1.TimeZoneSidKey = user.TimeZoneSidKey;
        user1.LocaleSidKey = user.LocaleSidKey;
        user1.EmailEncodingKey = user.EmailEncodingKey;
        user1.LanguageLocaleKey = user.LanguageLocaleKey;
        user1.alias = 'tst';
        user1.Email = 'tester@test.com';
        user1.Username = 'tester@test.com';  
        insert user1;
        
//Create Account, Opportunity, Product, etc.
        Account acct1 = new Account(name='test Account One1');
        acct1.Type = 'Advertiser';
        insert acct1;
        
        
//Create Opportunity on Account
        Opportunity Oppty1 = new Opportunity(name='test Oppty One1');
        Oppty1.AccountId = acct1.Id;
        Oppty1.StageName = 'Test';
        Oppty1.CloseDate = Date.today();
        Oppty1.AED__Campaign_Start_Date__c = Date.today();
        Oppty1.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty1.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty1.AED__Country__c = 'Spain';
        Oppty1.Campaign_Name_Agreement__c = 'test Oppty One1' ;
        Oppty1.Implementation_DirectTrack__c = 'Yes';
        Oppty1.Implementation_DT_Status__c = '1. Create Campaign';
        Oppty1.Approval_Status__c = 'Waiting for Approval';
       
        insert Oppty1; 

// Create Products 
         Product2 testprod1 = new Product2 (name='test product one1');
         testprod1.productcode = 'test pd code1one';
         insert testprod1;      

// Get Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];            
        
// Add to pricebook
         PricebookEntry testpbe1 = new PricebookEntry ();
         testpbe1.pricebook2id = testpb.id;
         testpbe1.product2id = testprod1.id;
         testpbe1.IsActive = True;
         testpbe1.UnitPrice = 250;
         testpbe1.UseStandardPrice = false;
         insert testpbe1;  
   
//Create Opportunity on Account
        Opportunity Oppty2 = new Opportunity(name='test Oppty One2');
        Oppty2.AccountId = acct1.Id;
        Oppty2.StageName = 'Test';
        Oppty2.CloseDate = Date.today();
        Oppty2.AED__Campaign_Start_Date__c = Date.today();
        Oppty2.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty2.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty2.AED__Country__c = 'Spain';
        Oppty2.Campaign_Name_Agreement__c = 'test Oppty One2' ;
        Oppty2.Implementation_DirectTrack__c = 'No';
        Oppty2.Approval_Status__c = 'Waiting for Approval';
               
        insert Oppty2;              
                               
// Create Products          
         Product2 testprod2 = new Product2 (name='test product two2');
         testprod2.productcode = 'test pd code2two';
         insert testprod2;

// Add to pricebook
         PricebookEntry testpbe2 = new PricebookEntry ();
         testpbe2.pricebook2id = testpb.id;
         testpbe2.product2id = testprod2.id;
         testpbe2.IsActive = True;
         testpbe2.UnitPrice = 250;
         testpbe2.UseStandardPrice = false;
         insert testpbe2;
      
    test.starttest();   
    
    Oppty1.Approval_Status__c = 'Approved by AD';
    Oppty2.Approval_Status__c = 'Approved by AD';
    
    update Oppty1;
    update Oppty2;
         
                //And now you want execute the startTest method to set the context 
                //of the following apex methods as separate from the previous data 
                //preparation or DML statements.  
       
        
          // add the line item which should call the trigger
          // with this line item it should fail out quickly 
          // As Auto Schedule is false
    OpportunityLineItem oli1 = new OpportunityLineItem();
    oli1.Quantity = 1;
    oli1.TotalPrice = 1;
    oli1.PricebookEntryId = testpbe1.id;
    oli1.OpportunityId = Oppty1.id;
    oli1.AED__Sales_Mode__c = 'CPA';
    oli1.AED__Country__c = 'IT';
    insert oli1;   
      
          // add the line item which should call the trigger
          // Auto Schedule is true so it should build the schedule.
    OpportunityLineItem oli2 = new OpportunityLineItem();
    oli2.Quantity = 1;
    oli2.TotalPrice = 1;
    oli2.PricebookEntryId = testpbe2.id;
    oli2.OpportunityId = Oppty2.id;    
    oli2.AED__Sales_Mode__c = 'CPA';
    oli2.AED__Country__c = 'IT';
    insert oli2;
            
    test.stoptest();
   
    }

}

 

 

Both triggers are tested 100%.

 

Thanks in advance for your help.

 

Stefano

 

 

 

Hello,

 

I wrote a trigger that fires a new custom object (AED_Campaign__c) when a new OpportunityLineItem is added to an Opportunity.

The trigger is working fine even when I've added definition of Record Types.

The problem is that when I try to test the trigger I receive some errors taht don'0t understand very well.

 

Code is the following:

 

 

trigger AddCampaign on OpportunityLineItem (after insert) {


//Query for the Account record types
     List<RecordType> rtypes = [Select Name, Id From RecordType 
                  where sObjectType='AED_Campaign__c' and isActive=true];
     
//Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> CampaignsRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
     CampaignsRecordTypes.put(rt.Name,rt.Id);
     
  
        
         

 for (OpportunityLineItem oli : Trigger.new) {
 
     if (oli.Implementation_DirectTrack__c == 'Yes') {
 
        AED_campaign__c cam = new AED_campaign__c (
            Name = oli.Magic_Id__c,
            Opportunity__c = oli.OpportunityId,
            Sales_Mode__c = oli.AED__Sales_Mode__c,
            Implementation_DirectTrack__c = oli.Implementation_DirectTrack__c, 
            Country__c = oli.AED__Country__c,
            Product__c = oli.ProductTr__c,
            Channel__c = oli.Channel__c,
            RecordTypeId=CampaignsRecordTypes.get('DirectTrack')
        );
        insert cam;
    }
    
    else if (oli.Implementation_DirectTrack__c == 'No') { 
    
        AED_campaign__c cam = new AED_campaign__c (
            Name = oli.Magic_Id__c,
            Opportunity__c = oli.OpportunityId,
            Sales_Mode__c = oli.AED__Sales_Mode__c,
            Implementation_DirectTrack__c = oli.Implementation_DirectTrack__c, 
            Country__c = oli.AED__Country__c,
            Product__c = oli.ProductTr__c,
            Channel__c = oli.Channel__c,
            RecordTypeId=CampaignsRecordTypes.get('No_DirectTrack')
        );
        insert cam;
        }
     else {}

}
}

Thetest I'm using is the following:

 

 

/**
 * This class tests the trigger named AddCampaign.
 */
@isTest
private class AddCampaignTriggerTest {

    static testMethod void AddCampaignTest() {       
                    
        //Data Prep
        
        //Create Account, Opportunity, Product, etc.
        Account acct1 = new Account(name='test Account One1');
        acct1.Type = 'Advertiser';
        insert acct1;
        
        //Create Opportunity on Account
        Opportunity Oppty1 = new Opportunity(name='test Oppty One1');
        Oppty1.AccountId = acct1.Id;
        Oppty1.StageName = 'Test';
        Oppty1.CloseDate = Date.today();
        Oppty1.AED__Campaign_Start_Date__c = Date.today();
        Oppty1.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty1.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty1.AED__Country__c = 'Spain';
        Oppty1.Campaign_Name_Agreement__c = 'test Oppty One1' ;
        Oppty1.Implementation_DirectTrack__c = 'Yes';
        Oppty1.Implementation_DT_Status__c = '1. Create Campaign';
       
        insert Oppty1;   
        
         //Create Opportunity on Account
        Opportunity Oppty2 = new Opportunity(name='test Oppty One2');
        Oppty2.AccountId = acct1.Id;
        Oppty2.StageName = 'Test';
        Oppty2.CloseDate = Date.today();
        Oppty2.AED__Campaign_Start_Date__c = Date.today();
        Oppty2.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty2.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty2.AED__Country__c = 'Spain';
        Oppty2.Campaign_Name_Agreement__c = 'test Oppty One2' ;
        Oppty2.Implementation_DirectTrack__c = 'No';
        
       
        insert Oppty2;              
                        
       // Create Products 
         Product2 testprod1 = new Product2 (name='test product one1');
         testprod1.productcode = 'test pd code1one';
         insert testprod1;
         
         Product2 testprod2 = new Product2 (name='test product two2');
         testprod2.productcode = 'test pd code2two';
         insert testprod2;

// Ger Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   

// Add to pricebook
         PricebookEntry testpbe1 = new PricebookEntry ();
         testpbe1.pricebook2id = testpb.id;
         testpbe1.product2id = testprod1.id;
         testpbe1.IsActive = True;
         testpbe1.UnitPrice = 250;
         testpbe1.UseStandardPrice = false;
         insert testpbe1;
         PricebookEntry testpbe2 = new PricebookEntry ();
         testpbe2.pricebook2id = testpb.id;
         testpbe2.product2id = testprod2.id;
         testpbe2.IsActive = True;
         testpbe2.UnitPrice = 250;
         testpbe2.UseStandardPrice = false;
         insert testpbe2;
         
         
                //And now you want execute the startTest method to set the context 
                //of the following apex methods as separate from the previous data 
                //preparation or DML statements.  
        test.starttest();
        
          // add the line item which should call the trigger
          // with this line item it should fail out quickly 
          // As Auto Schedule is false
    OpportunityLineItem oli1 = new OpportunityLineItem();
    oli1.Quantity = 1;
    oli1.TotalPrice = 1;
    oli1.PricebookEntryId = testpbe1.id;
    oli1.OpportunityId = oppty1.id;    
    insert oli1;   
    
            
          // add the line item which should call the trigger
          // Auto Schedule is true so it should build the schedule.
    OpportunityLineItem oli2 = new OpportunityLineItem();
    oli2.Quantity = 1;
    oli2.TotalPrice = 1;
    oli2.PricebookEntryId = testpbe2.id;
    oli2.OpportunityId = oppty1.id;    
    insert oli2;
     
                         
          // add the line item which should call the trigger
          // Auto Schedule is true so it should build the schedule.
          // This uses a date on OpptyLineItem to try another code path
    OpportunityLineItem oli3 = new OpportunityLineItem();
    oli3.Quantity = 1;
    oli3.TotalPrice = 1;
    oli3.ServiceDate = date.today();
    oli3.PriceBookEntryId = testpbe2.id;
    oli3.OpportunityId = oppty1.id;    
    insert oli3;
    
           
        test.stoptest();
    }
}

 Message Error:

 

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddCampaign: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: id value not valid for the users profile: : [RecordTypeId] Trigger.AddCampaign: line 31, column 9: []


Class.AddCampaignTriggerTest.AddCampaignTest: line 73, column 5 External entry point

 

 

 

 

Someone can help me?

 

Thanks,

 

Stefano

 

 

 

 

 

Hello,

 

I'm writing a trigger that should fire a new case when the custom field Approval_Status__c changes to a specific value (Value changed to "Approved by AD" when opportunity is approved based on an approval process).

The problem is that my trigger is working but generates a case each time that the opportunity is updated.

 

The trigger I wrote is the following:

 

trigger NewCaseFromOpp on Opportunity (after update) { for (Opportunity opp : Trigger.new) { if (opp.approval_status__c == 'Approved by AD' ) { Case c = new Case ( Opportunity__c = opp.Id, Status = 'New', Origin = 'Web', Type = 'Request', Case_reason__c = 'Campaign Setup', Subject = 'New Direct Track Implementation', OwnerId= '00G20000001Pz10' ); insert c; } else {} } } 

 

Is there someone that can help me with this trigger?

 

Thanks,

 

Stefano

Hello,

 

I'd like to create a trigger in order to populate Partner Related List in Opportunity, from a custom field called Partner.

 

I don't have experience in Apex Code, so any comments will be very very helpful!

 

Thanks,

 

Stefano

Hello,

 

I'd like to create a trigger in order to populate Partner Related List in Opportunity, from a custom field called Partner.

 

I don't have experience in Apex Code, so any comments will be very very helpful!

 

Thanks,

 

Stefano

 

Hello,

 

I wrote a trigger that fires a new custom object (AED_Campaign__c) when a new OpportunityLineItem is added to an Opportunity.

The trigger is working fine even when I've added definition of Record Types.

The problem is that when I try to test the trigger I receive some errors taht don'0t understand very well.

 

Code is the following:

 

 

trigger AddCampaign on OpportunityLineItem (after insert) {


//Query for the Account record types
     List<RecordType> rtypes = [Select Name, Id From RecordType 
                  where sObjectType='AED_Campaign__c' and isActive=true];
     
//Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> CampaignsRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
     CampaignsRecordTypes.put(rt.Name,rt.Id);
     
  
        
         

 for (OpportunityLineItem oli : Trigger.new) {
 
     if (oli.Implementation_DirectTrack__c == 'Yes') {
 
        AED_campaign__c cam = new AED_campaign__c (
            Name = oli.Magic_Id__c,
            Opportunity__c = oli.OpportunityId,
            Sales_Mode__c = oli.AED__Sales_Mode__c,
            Implementation_DirectTrack__c = oli.Implementation_DirectTrack__c, 
            Country__c = oli.AED__Country__c,
            Product__c = oli.ProductTr__c,
            Channel__c = oli.Channel__c,
            RecordTypeId=CampaignsRecordTypes.get('DirectTrack')
        );
        insert cam;
    }
    
    else if (oli.Implementation_DirectTrack__c == 'No') { 
    
        AED_campaign__c cam = new AED_campaign__c (
            Name = oli.Magic_Id__c,
            Opportunity__c = oli.OpportunityId,
            Sales_Mode__c = oli.AED__Sales_Mode__c,
            Implementation_DirectTrack__c = oli.Implementation_DirectTrack__c, 
            Country__c = oli.AED__Country__c,
            Product__c = oli.ProductTr__c,
            Channel__c = oli.Channel__c,
            RecordTypeId=CampaignsRecordTypes.get('No_DirectTrack')
        );
        insert cam;
        }
     else {}

}
}

Thetest I'm using is the following:

 

 

/**
 * This class tests the trigger named AddCampaign.
 */
@isTest
private class AddCampaignTriggerTest {

    static testMethod void AddCampaignTest() {       
                    
        //Data Prep
        
        //Create Account, Opportunity, Product, etc.
        Account acct1 = new Account(name='test Account One1');
        acct1.Type = 'Advertiser';
        insert acct1;
        
        //Create Opportunity on Account
        Opportunity Oppty1 = new Opportunity(name='test Oppty One1');
        Oppty1.AccountId = acct1.Id;
        Oppty1.StageName = 'Test';
        Oppty1.CloseDate = Date.today();
        Oppty1.AED__Campaign_Start_Date__c = Date.today();
        Oppty1.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty1.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty1.AED__Country__c = 'Spain';
        Oppty1.Campaign_Name_Agreement__c = 'test Oppty One1' ;
        Oppty1.Implementation_DirectTrack__c = 'Yes';
        Oppty1.Implementation_DT_Status__c = '1. Create Campaign';
       
        insert Oppty1;   
        
         //Create Opportunity on Account
        Opportunity Oppty2 = new Opportunity(name='test Oppty One2');
        Oppty2.AccountId = acct1.Id;
        Oppty2.StageName = 'Test';
        Oppty2.CloseDate = Date.today();
        Oppty2.AED__Campaign_Start_Date__c = Date.today();
        Oppty2.AED__Campaign_Close_Date__c = Date.today()+1;
        Oppty2.AED__Invoice_Client_Name__c = acct1.Id;
        Oppty2.AED__Country__c = 'Spain';
        Oppty2.Campaign_Name_Agreement__c = 'test Oppty One2' ;
        Oppty2.Implementation_DirectTrack__c = 'No';
        
       
        insert Oppty2;              
                        
       // Create Products 
         Product2 testprod1 = new Product2 (name='test product one1');
         testprod1.productcode = 'test pd code1one';
         insert testprod1;
         
         Product2 testprod2 = new Product2 (name='test product two2');
         testprod2.productcode = 'test pd code2two';
         insert testprod2;

// Ger Pricebook
         Pricebook2 testpb = [select id from Pricebook2 where IsStandard = true];   

// Add to pricebook
         PricebookEntry testpbe1 = new PricebookEntry ();
         testpbe1.pricebook2id = testpb.id;
         testpbe1.product2id = testprod1.id;
         testpbe1.IsActive = True;
         testpbe1.UnitPrice = 250;
         testpbe1.UseStandardPrice = false;
         insert testpbe1;
         PricebookEntry testpbe2 = new PricebookEntry ();
         testpbe2.pricebook2id = testpb.id;
         testpbe2.product2id = testprod2.id;
         testpbe2.IsActive = True;
         testpbe2.UnitPrice = 250;
         testpbe2.UseStandardPrice = false;
         insert testpbe2;
         
         
                //And now you want execute the startTest method to set the context 
                //of the following apex methods as separate from the previous data 
                //preparation or DML statements.  
        test.starttest();
        
          // add the line item which should call the trigger
          // with this line item it should fail out quickly 
          // As Auto Schedule is false
    OpportunityLineItem oli1 = new OpportunityLineItem();
    oli1.Quantity = 1;
    oli1.TotalPrice = 1;
    oli1.PricebookEntryId = testpbe1.id;
    oli1.OpportunityId = oppty1.id;    
    insert oli1;   
    
            
          // add the line item which should call the trigger
          // Auto Schedule is true so it should build the schedule.
    OpportunityLineItem oli2 = new OpportunityLineItem();
    oli2.Quantity = 1;
    oli2.TotalPrice = 1;
    oli2.PricebookEntryId = testpbe2.id;
    oli2.OpportunityId = oppty1.id;    
    insert oli2;
     
                         
          // add the line item which should call the trigger
          // Auto Schedule is true so it should build the schedule.
          // This uses a date on OpptyLineItem to try another code path
    OpportunityLineItem oli3 = new OpportunityLineItem();
    oli3.Quantity = 1;
    oli3.TotalPrice = 1;
    oli3.ServiceDate = date.today();
    oli3.PriceBookEntryId = testpbe2.id;
    oli3.OpportunityId = oppty1.id;    
    insert oli3;
    
           
        test.stoptest();
    }
}

 Message Error:

 

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddCampaign: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: id value not valid for the users profile: : [RecordTypeId] Trigger.AddCampaign: line 31, column 9: []


Class.AddCampaignTriggerTest.AddCampaignTest: line 73, column 5 External entry point

 

 

 

 

Someone can help me?

 

Thanks,

 

Stefano

 

 

 

 

 

Hello,

 

I'm writing a trigger that should fire a new case when the custom field Approval_Status__c changes to a specific value (Value changed to "Approved by AD" when opportunity is approved based on an approval process).

The problem is that my trigger is working but generates a case each time that the opportunity is updated.

 

The trigger I wrote is the following:

 

trigger NewCaseFromOpp on Opportunity (after update) { for (Opportunity opp : Trigger.new) { if (opp.approval_status__c == 'Approved by AD' ) { Case c = new Case ( Opportunity__c = opp.Id, Status = 'New', Origin = 'Web', Type = 'Request', Case_reason__c = 'Campaign Setup', Subject = 'New Direct Track Implementation', OwnerId= '00G20000001Pz10' ); insert c; } else {} } } 

 

Is there someone that can help me with this trigger?

 

Thanks,

 

Stefano