function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jill HedbergJill Hedberg 

Help with trigger - don't know where to add $RecordType.Name = "License Opportunity"

I have this Apex Trigger which works good. However I want it to only be valid for license opportunities (all other record types should be able to close deal without having to add Delivery Contact), so I want to add $RecordType.Name = "License Opportunity" somewhere, but don't know where or how.

 

Anyone who has a solution for this? :)

 

This is the trigger:

trigger Opportunity_DeliveryContact_Required on Opportunity (before insert, before update) {

//map to keep track of the contact_required = 1
Map<String, Opportunity> oppy_contact = new Map<String, Opportunity>();

//Trigger.new is an array of opportunities
//and adds any that have Contact_Required = 1 to the oppy_contact Map
for (Integer i = 0; i < Trigger.new.size(); i++) {
System.debug('*****Required? ' + Trigger.new[i].contact_required__c);
if (Trigger.new[i].contact_required__c == 1) {
oppy_contact.put(Trigger.new[i].id,Trigger.new[i]);
}
}

//map to keep track of the opportunity contact roles
map<Id, OpportunityContactRole> oppycontactroles = new map<Id, OpportunityContactRole>();

//select OpportunityContactRoles for the opportunities with contact role required

List<OpportunityContactRole> roles = [select OpportunityId, Role from OpportunityContactRole
where (OpportunityContactRole.Role ='Delivery Contact') and OpportunityContactRole.OpportunityId
in :oppy_contact.keySet()];


for (OpportunityContactRole ocr : roles) {
//puts the contact roles in the map with the Opportunity ID as the key
oppycontactroles.put(ocr.OpportunityId,ocr);
}

// Loop through the opportunities and check if they exists in the contact roles map or contact role isn't required
for (Opportunity oppy : system.trigger.new) {
//system.debug('List oppy Id - '+oppy.id);
if (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id))
{
oppy.addError('No Delivery Contact exists. Please go to the Contact Roles area and select a delivery contact before you can move on to stage "A6 - Closed Won".');
}
} //for
}

 

Best Answer chosen by Admin (Salesforce Developers) 
Naidu PothiniNaidu Pothini
String OppRectypeId = [SELECT Id, Name FROM RecordType WHERE Sobjecttype = 'Opportunity' AND Name = 'License Opportunity'].Id;

for (Opportunity oppy : system.trigger.new) { if(Oppy.RecordTypeId == OppRectypeId) { if (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id)) { oppy.addError('No Delivery Contact exists. Please go to the Contact Roles area and select a delivery contact before you can move on to stage "A6 - Closed Won".'); } } }

 Thanks dphill,

 

I guess this would work with out any issues.

 

All Answers

Naidu PothiniNaidu Pothini
for (Opportunity oppy : system.trigger.new) 
	{
		//system.debug('List oppy Id - '+oppy.id);
		if(Oppy.RecordType.Name == 'License Opportunity')
		{
			if (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id))
			{
				oppy.addError('No Delivery Contact exists. Please go to the Contact Roles area and select a delivery contact before you can move on to stage "A6 - Closed Won".');
			}
		}
	}

try this.

dphilldphill
One quick note on Naidu's response. What he said will ALMOST work. You cannot access the Recordtype.Name on the Trigger.new. In order to access that value you actually need to requery for the records and bring that value back.
Naidu PothiniNaidu Pothini
String OppRectypeId = [SELECT Id, Name FROM RecordType WHERE Sobjecttype = 'Opportunity' AND Name = 'License Opportunity'].Id;

for (Opportunity oppy : system.trigger.new) { if(Oppy.RecordTypeId == OppRectypeId) { if (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id)) { oppy.addError('No Delivery Contact exists. Please go to the Contact Roles area and select a delivery contact before you can move on to stage "A6 - Closed Won".'); } } }

 Thanks dphill,

 

I guess this would work with out any issues.

 

This was selected as the best answer
Jill HedbergJill Hedberg

Thanks guys! Works perfectly :D

 

Would it be possible for you to also help me with my test class that is failing? It used to have 4/4 test methods passed, but after my change it only has 2 passed . Even before my change where I had 4/4 test methods passed, it still had 0% code coverage. I have no idea how to fix it so that I can deploy this to my production environment.

 

Failures:

Method Name testoppyrequired1wodeliverycontact
Pass/Fail Fail
Error Message System.AssertException: Assertion Failed
Stack Trace Class.test_Oppty_DeliveryContact_Required.testoppyrequired1wodeliverycontact: line 124, column 1

 

Method Name testoppyrequired1
Pass/Fail Fail
Error Message System.AssertException: Assertion Failed
Stack Trace Class.test_Oppty_DeliveryContact_Required.testoppyrequired1: line 62, column 1

 

My test class code:

public class test_Oppty_DeliveryContact_Required {


// test to ensure an opportunity can be added

public static testMethod void testoppyrequired0()
    {
        //create oppty 
        List<Opportunity> oppy = new List<Opportunity>();
                                    
        //add 10 opportunites without a contact, and with the condition contact required = 0
        
        for (Integer i = 0; i < 10; i++) {
            oppy.add(new Opportunity(Name='nick_test'+i,StageName='A0 - Initial Qualification',CloseDate=System.Today()));
        }
        insert oppy;
        
        map<Id, Opportunity> oppy_map = new map<Id, Opportunity>();
        
        for (Integer i = 0;i<10;++i){
            oppy_map.put(oppy[i].Id,oppy[i]);
        } //for
        
        System.assert([SELECT count() FROM Opportunity WHERE Id IN :oppy_map.keySet()] == 10);   
    } //testoppyrequired = 0
    
    
    //test to go from a not required value to a required value

public static testMethod void testoppyrequired1()
    {   
            //create oppty 
            List<Opportunity> oppy2 = new List<Opportunity>();
                                        
            //add 10 opportunites without a contact, and with the condition contact required = 0       
            for (Integer i = 0; i < 10; i++) {
                oppy2.add(new Opportunity(Name='nick_test'+i,StageName='A5 - Negotiate',CloseDate=System.Today()));
            }
            
            insert oppy2;
            
            for (Integer i = 0; i < 10; i++) {
                
              oppy2[i].StageName='A6 - Closed Won';
            
            }

            Test.startTest();

            try {
            
                update oppy2;
                
                Opportunity sampleTest = [Select Id, Contact_Required__c From Opportunity where Id = :oppy2[0].id];
                
                System.debug('*****SAMPLE' + sampleTest);
                
                System.assert(false, 'This update should have failed.');
            
            } catch(System.DmlException e) {
            
                System.assert(e.getMessage().contains('No Delivery Contact exists.'));
            
            }

            Test.stopTest();
       
 
    } //testoppyrequired = 1



public static testMethod void testoppyrequired1wodeliverycontact()
    {   
            //create oppty 
            List<Opportunity> oppy = new List<Opportunity>();
                                        
            //add 10 opportunites 
                    
            for (Integer i = 0; i < 10; i++) {
                oppy.add(new Opportunity(Name='nick_test'+i,StageName='A1 - Initiate',CloseDate=System.Today()));
            }
            
            insert oppy;
            
            //add 10 contacts
            
            List<Contact> c = new List<Contact>();
                                        
    
            for (Integer i = 0; i < 10; i++) {
                c.add(new Contact(LastName='nick_test'+i));
            }

            insert c;

            for (Integer i = 0; i < 10; i++) {
                
            oppy[i].StageName='A6 - Closed Won';
            
            }

            //add 10 opporunity contact roles associated to the opportunities and contacts above
            
            List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
            
            for (Integer i = 0; i < 10; i++) {
                ocr.add(new OpportunityContactRole(Role='Business User',OpportunityId=oppy[i].id,ContactId=c[i].id));
            }
            
            insert ocr;
            
boolean caughtException = false;


Test.startTest();

try {

    update oppy;

} catch(System.DmlException e) {

    System.assert(e.getMessage().contains('No Delivery Contact exists.'));

    caughtException = true;

}

    Test.stopTest();

    System.assert(caughtException);         
 
    } //testoppyrequired = 1


public static testMethod void testoppyrequired1deliverycontact()
    {   
            //create oppty 
            List<Opportunity> oppy = new List<Opportunity>();
                                        
            //add 10 opportunites 
                    
            for (Integer i = 0; i < 10; i++) {
                oppy.add(new Opportunity(Name='nick_test'+i,StageName='A1 - Initiate',CloseDate=System.Today()));
            }
            
            insert oppy;
            
            map<Id, Opportunity> oppy_map = new map<Id, Opportunity>();
            
            for (Integer i = 0;i<10;++i){
                oppy_map.put(oppy[i].Id,oppy[i]);
            } //for
            
            //add 10 contacts
            
            List<Contact> c = new List<Contact>();
                                        
    
            for (Integer i = 0; i < 10; i++) {
                c.add(new Contact(LastName='nick_test'+i));
            }

            insert c;

            //add 10 opporunity contact roles associated to the opportunities and contacts above
            
            List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
            
            for (Integer i = 0; i < 10; i++) {
                ocr.add(new OpportunityContactRole(Role='Delivery Contact',OpportunityId=oppy[i].id,ContactId=c[i].id,IsPrimary=True));
            }
            
            insert ocr;
            
            for (Integer i = 0; i < 10; i++) {
                
            oppy[i].StageName='A5 - Negotiate';
            
            }

            try {
            
                update oppy;
                
                    System.assert([SELECT count() FROM Opportunity
                        WHERE Id IN :oppy_map.keySet()] == 10);
            
            } catch(System.DmlException e) {
            
                System.assert(false);
            
            }   
 
    } //testoppyrequired = 1 and delivery contact (+primary contact) = true

} //test class

 

Naidu PothiniNaidu Pothini
for (Integer i = 0; i < 10; i++) {
            oppy.add(new Opportunity(Name='nick_test'+i,StageName='A0 - Initial Qualification',CloseDate=System.Today()));
        }
        insert oppy;

I guess you should try creating opportunities with the recordTypeId.

 

Let me know if it doesnt work.

 

 

Jill HedbergJill Hedberg

But how? I am not a developer... yet ;) , so nothing of this makes much sense yet. Could you explain it "for dummies" style? Where in the code should what be added? As you did in your previous post. Even I understood that :)

dphilldphill

Same way you set the other fields, except specify what the RecordTypeId is instead.  Look at how you have Role='Delivery Contact'.  You need to do pretty much the same thing for RecordTypeId and assign it the Id that you queried for to fix your earlier issue.

 

for (Integer i = 0; i < 10; i++)
{
  ocr.add(new OpportunityContactRole(Role='Delivery Contact', OpportunityId = oppy[i].id, ContactId=c[i].id, IsPrimary = True));
}

 

Jill HedbergJill Hedberg

Ah, I see, thanks! I got all 4 test methods to pass again. However, I still have 0% code coverage. How do I solve that?

dphilldphill
It should be working, it's possible the coverage just isn't updating correctly. Try to click the 'compile all classes' link or the other link on the page you can view all of the classes. Setup -> Develop -> Apex Classes -> click link
Jill HedbergJill Hedberg

No it did not work :( It's still 0%, and when I click the link nothing is blue. The code covered should be blue right?

dphilldphill

Go to the trigger, and is the Status marked as Active?

Naidu PothiniNaidu Pothini
@isTest
public class test_Oppty_DeliveryContact_Required { public static String OppRectypeId = [SELECT Id, Name FROM RecordType WHERE Sobjecttype = 'Opportunity' AND Name = 'License Opportunity'].Id; public static testMethod void testoppyrequired1wodeliverycontact() {
test.StartTest();
List<Contact> c = new List<Contact>(); List<Opportunity> oppy = new List<Opportunity>(); List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
for (Integer i = 0; i < 10; i++) { oppy.add(new Opportunity(Name='nick_test'+i, StageName='A1 - Initiate', Contact_Required__c = true, RecordTypeId = OppRectypeId, CloseDate=System.Today())); c.add(new Contact(LastName='nick_test'+i)); } insert oppy; insert c; for(Integer i = 0; i < 10; i++) { ocr.add(new OpportunityContactRole(Role='Business User', OpportunityId=oppy[i].id, ContactId=c[i].id)); } insert ocr; for(Integer i = 0; i < 10; i++) { oppy[i].StageName='A6 - Closed Won'; } boolean caughtException = false; try { update oppy; } catch(System.DmlException e) { System.assert(e.getMessage().contains('No Delivery Contact exists.')); caughtException = true; } Test.stopTest(); System.assert(caughtException); } }

 Save the test class what you have right now and can you try with this test class.

 

 

 

Jill HedbergJill Hedberg

Actually, seemed to be some kind of delay. I now have 92% code coverage and are able to deploy. Woohoo!

Thank you so much for your help! I really appreciate you taking the time to help and teach me :)

 

Take care!