+ Start a Discussion
Michael MMichael M 
Why am I getting this error: "Static method cannot be referenced from a non static context: void EMedCalloutsExtension.makePostCallout1(List<Id>)" ?

The error appears when I try to save this test class:
@isTest
private class EmedscalloutTest2 {
     @isTest static void testCallout() {
         date d = date.today();
         lead l = new lead(firstname = 'test', lastname = 'test', patient_dob__c = d);
         insert l;
         list<string> refids = new list<string>();
         refids.add(l.id);
         
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new EmedsCalloutTest());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        EMedCalloutsExtension tw = new EMedCalloutsExtension();
        tw.makePostCallout1(refids);

    }
}


Here is my first test class/method:
@isTest
global class EmedsCalloutTest implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://example.com/example/test', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}


and my actual code:
trigger  ReferralCreateContact on Lead (after insert, after update) {
if(!Test.isRunningTest()) { 
    if (trigger.isInsert){
     List<string> leadIds = new List<string>();
    for (lead ref : trigger.new){
      if(System.IsBatch() == false && System.isFuture() == false){ 
        if (ref.Epaces_Checked__c != true){
          lead newl = new lead();
          newl.Id = ref.id;
          leadIds.add(newl.id);
        EMedCalloutsExtension.makePostCallout1(leadIds); 
        }
      }}} }
public class EMedCalloutsExtension {
    static string EmedrequestId;
    static string requestStatus;
    
@future(callout = true)
public static void  makePostCallout1(list<id> refIds) {
    
  List <Lead> refs =[Select Id, firstname, lastname, gender__c, patient_dob__c, patient_ssn__c, Epaces_Checked__c, Emed_Request_Id__c, medicaid_id__c, medicare_id__c from Lead where Id in :refIds]; 
     List<lead> refToUpdate = new List<Lead>();      
           for (lead ref : refs){

 //Set up reassignment of static resource string items              
   String ssnReplace; 
           if (ref.Patient_SSN__c != null){
            ssnReplace = ref.Patient_SSN__c.replace('-','');
           }
    String genderLetter;
           if (ref.Gender__c == 'Male'){
               genderLetter = 'M';
           } else if (ref.Gender__c == 'Female'){
               genderLetter = 'F';
           }
           
           String first;
           String second;
           String third;
            String d = String.valueOf(ref.Patient_DOB__c);
           system.debug('***dob string raw: ' + d);
                first = d.substring(0,4);
                second = d.substring(5,7);
                third = d.substring(8,10);
           String dob = first + second + third;
           system.debug('***dob formatted: ' + dob);

 
//REQUEST #1          
      string reqbody;
     StaticResource r =[Select Id,Body from StaticResource where Name='EMedCalloutBody' limit 1];
      reqBody=r.body.toString(); 
     // reqBody=reqBody.replace('{{FirstName}}', ref.firstname);     
     // reqBody=reqBody.replace('{{LastName}}', ref.lastname);  
               if (ref.Medicaid_ID__c != null){
     // reqBody=reqBody.replace('{{MedicaidId}}', ref.medicaid_id__c); 
      reqBody = reqBody.replace('{{residentInfo}}', '{"first_name": "'+ ref.firstname +'", "last_name": "' + ref.lastname +'", "id_type":"MI", "subscriber_id":"' + ref.medicaid_id__c + '"}');             
               } 
               else if (ref.gender__c != null && ref.Patient_DOB__c != null && ref.Patient_SSN__c != null){
                   reqBody = reqBody.replace('{{residentInfo}}', '{"first_name": "'+ ref.firstname +'", "last_name": "' + ref.lastname +'", "gender":"' + genderLetter + '", "birthdate": "' + dob + '", "social_security_number": "' + ssnReplace + '"}');    
               }
       HttpRequest req = new HttpRequest();
           req.setHeader('Content-Type', 'application/json');
                req.setMethod('POST');
                req.setBody(reqBody);
                req.setEndpoint('callout:Emed');
                req.setTimeout(2 * 60 * 1000);
                    system.debug('ENDPOINT: ' + req.getendpoint());
                       system.debug('BODY: '+ req.getBody());
         Http http = new Http();
           HttpResponse response = http.send(req);
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            system.debug(response.getstatuscode());
           System.debug(response.getBody());
             string requestId = response.getbody().substringAfter('"request_id": ').substringBefore(',');
      //      ref.Emed_Request_Id__c = requestId;
            EmedrequestId = requestId;
            

              string reqbodyResp;   
              StaticResource r2 =[Select Id,Body from StaticResource where Name='EmedResponseBody' limit 1];
               reqbodyResp=r2.body.toString();
              reqbodyResp=reqbodyResp.replace('{{requestId}}', EmedrequestId);
               
               HttpRequest req2 = new HttpRequest();
                  req2.setHeader('Content-Type', 'application/json');
                req2.setMethod('POST');
                req2.setBody(reqbodyResp);
                req2.setEndpoint('callout:Emed_Response');
                req2.setTimeout(2 * 60 * 1000);
                        system.debug('ENDPOINT2: ' + req2.getendpoint());
                        system.debug('BODY2: '+ req2.getBody());
                  Http http2 = new Http();
                 HttpResponse response2 = http2.send(req2);
               
        if (response2.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response2.getStatusCode() + ' ' + response2.getStatus());
        } else {
            system.debug(response2.getstatuscode());
           System.debug(response2.getBody());
            Id refId = ref.id;
            // instantiate a new instance of the Queueable class
            EmedFollowupCallout makeAnotherFollowUp = new EmedFollowupCallout(response2.getBody(), refId, requestId);
            // enqueue the job for processing
            ID jobID = System.enqueueJob(makeAnotherFollowUp);

           } 
 
        }
          return;
    } 
}
   
}


 
Best Answer chosen by Michael M
RituSharmaRituSharma
Static methods can not be referenced from a non-static context. makePostCallout1 is a static method of EMedCalloutsExtension class so to call it, you don't need to create an instance of EMedCalloutsExtension class.

Instead of below code:
EMedCalloutsExtension tw = new EMedCalloutsExtension();
tw.makePostCallout1(refids);

Write below code:
EMedCalloutsExtension.makePostCallout1(refids);
Marián ČekanMarián Čekan 
Hi, I am trying to import some sample data into Salesforce using data loader. But after trying to map the fields, all of my "File Column Header" are in one row, so I can only add one "Name" field. It is the same problem as mentioned here: https://developer.salesforce.com/forums/?id=906F0000000BKBAIA4 but I did not manage to success. Any advice please? thanks in advance
Best Answer chosen by Marián Čekan
AnudeepAnudeep (Salesforce Developers) 
Hi Marián - Can you try the solution listed here?
StaciStaci 
I have the following trigger to produce a canned response case comment when a option is picked from a picklist.  It works BUT if someone actually puts a case comment on a case after the picklist has been used, it errors:

Error:Apex trigger CW_DSS_CaseTrigger caused an unexpected exception, contact your administrator: CW_DSS_CaseTrigger: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CW_DSS_CaseTrigger: maximum trigger depth exceeded Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate: []: Trigger.CW_DSS_CaseTrigger: line 25, column 1


What is causing this?

 
trigger CW_DSS_CaseTrigger on Case (after update) {
    

   List<caseComment> caseCommentList = new List<caseComment>();
    for (Case c: Trigger.new)
    {
        
        caseComment cc = new caseComment();
        if(c.Macros__c == 'Application Support information'){
                cc.parentid = c.ID;
                cc.commentbody = 'For application (DSSi and Relay Server) support and troubleshooting requests, please provide the following information.'+'\n' +
                                    'Minimum DSS Ticket Information requirements:'+'\n' +
                                    'Site Name:' +'\n' +
                                    'Site Contact: (For possible Site IT related issues)' +'\n' +
                                    'DSSi Software Version:' +'\n' +
                                    'Problem/Inquiry:' +'\n' +
                                    'Troubleshooting Steps Taken:' +'\n' +
                                    'This information is required with all DSS support requests. Failure to provide this requested information may delay your request.';
                cc.ispublished = true;
                casecommentlist.add(cc);
               
        }

    }
            insert caseCommentList;
            
}

 
Best Answer chosen by Staci
RituSharmaRituSharma
It seems that trigger is stuck in the loop i.e. something is refiring the trigger again and again. Use a static variable to avoid reccursion.
Andrean Lobo 6Andrean Lobo 6 
Hello,

We have an API user in our org that inserts Leads. The user is receiving the following error: 

Error  DUPLICATES_DETECTED - XXXXXXX

The above message is part of a duplicate rule that we have set up in our org but it does not block the user when the record is created by front end. 

Is there some kind of limitation for an API user? How can this be overcome?

Thank-you,
Andréan
Best Answer chosen by Andrean Lobo 6
RituSharmaRituSharma
I am sure that in the duplicate rule Alert option is selected. If yes, when you create a duplicate record from the UI and click on save, it shows the duplicate error. You can again click the Save button to save the record. Incase of API, behaviour is different. If you want to bypass the duplicate rule, you will need to set the DMLOptions. Refer the below provided URL for details: 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Database_DMLOptions_DuplicateRuleHeader.htm#:~:text=For%20a%20duplicate%20rule%2C%20when,setting%20this%20property%20to%20false%20.
Syaiful Anuar Abdul LatifSyaiful Anuar Abdul Latif 

I would like to have a validation rule where a lead owner will need to write their reason in the 'Notes' section (located at the right side of the page) when they unqualify a lead. need a step by step guide for this, including the code.
Best Answer chosen by Syaiful Anuar Abdul Latif
Syaiful Anuar Abdul LatifSyaiful Anuar Abdul Latif
i wqas given another code by the support team and it works. this is the code given to me:

AND(
ISCHANGED(Status ),
ISPICKVAL( Status ,"Unqualified"),
ISBLANK( SFDC_Reasons__c )
)
ARUN JOYARUN JOY 
Hi ,I created a sharing rule for one of the custom object, and given read write access to role.Now when I tried to login on the behalf of that user , its not allowing to edit the record.CRED settings are turned on  .Its allowing me to read but not write
Best Answer chosen by ARUN JOY
RituSharmaRituSharma
It seems that the record is pending approval hence it's locked. If a record is pending for approval, only approver or admins can edit the record.
Jordan KindlerJordan Kindler 
I get the above error when deploying a trigger and its associated test class in production. I believe it has to do with either my creating a record that already exists via another trigger, or something that has been left null(?). Any and all help is much appreciated! Posting my trigger and test class below:

Trigger:
trigger closedTrigger on Opportunity (after update) {
    
    //create a list of related accounts and account Ids
    list<Id> acctIds = new list<Id>();
    list<Account> accts = new list<Account>();
    
    //get the accounts and oplineitems associated with the opportunity 
    for (opportunity o:trigger.new) {
        acctIds.add(o.accountId);    
    }
    
    //create a list of Opportunity Line Items 
   list<Id> prodOpIds = new list<Id>();
    
    Map<Id, Set<String>> mapProducts = new Map<Id, Set<String>>();
        for (opportunity op:trigger.new) {
            prodOpIds.add(op.Id);
            mapProducts.put(op.id, new Set<String>());
        }
    
    for (OpportunityLineItem z: [SELECT Id, Product2.Name, OpportunityId FROM OpportunityLineItem WHERE OpportunityId IN: prodOpIds]) {
        mapProducts.get(z.OpportunityId).add(z.Product2.Name);
    }
    
    //now we can loop over the associated account(s) and update the information with which we're concerned
    for (account a: [SELECT Id, Curriculum_Product__c, Past_Room_Scheduling_Product__c, Room_Scheduling_Product__c, 
                                                       Past_Curriculum_Product__c, Past_Event_Scheduling_Product__c, 
                                                       Event_Scheduler_Product__c,  Class_Schedule_Planning_Product__c, 
                                                       Past_Class_Scheduling_Product__c, Past_Catalog_Product__c, 
                                                       Catalog_Product__c, Account_Lifecycle_Status__c 
                     FROM account WHERE Id IN: acctIds]) {
        for (opportunity op:trigger.new) {
        Set<String> setProducts = mapProducts.get(op.Id);
            if (op.stageName=='Closed Won' && trigger.oldmap.get(op.Id).StageName != 'Closed Won') {
                //set status to Customer
                a.Account_Lifecycle_Status__c = 'Customer';
                //class 
                if(setProducts.contains('Class Scheduler') && a.Class_Schedule_Planning_Product__c != 'Coursedog')  {
                    a.Past_Class_Scheduling_Product__c = a.Class_Schedule_Planning_Product__c;
                    a.Class_Schedule_Planning_Product__c = 'Coursedog';                 
                } 
                //catalog
                if(setProducts.contains('Catalog Management') && a.Catalog_Product__c != 'Coursedog')  {
                    a.Past_Catalog_Product__c = a.Catalog_Product__c;
                    a.Catalog_Product__c = 'Coursedog';
                }
                //events
                if(setProducts.contains('Event Scheduler') && a.Event_Scheduler_Product__c != 'Coursedog')  {
                    a.Past_Event_Scheduling_Product__c = a.Event_Scheduler_Product__c;
                    a.Event_Scheduler_Product__c = 'Coursedog';
                }  
                //curriculum
                if(setProducts.contains('Curriculum Management') && a.Curriculum_Product__c != 'Coursedog')  {
                    a.Past_Curriculum_Product__c = a.Curriculum_Product__c;
                    a.Curriculum_Product__c = 'Coursedog';
                }
            accts.add(a);  
               
            }
            if (op.stageName=='Closed Lost' && trigger.oldmap.get(op.Id).StageName != 'Closed Lost') {
                a.Account_Lifecycle_Status__c = 'Recycled';
            accts.add(a);
            }
        }
    
    }
    update accts; 
}
Test class:
@istest
public class testClassForTrigger{
    @istest
    public static void triggerTest(){
        account acc = new account();
        acc.name='test'; //when you create an account you need a name 
        acc.Class_Schedule_Planning_Product__c = 'Astra Scheduler';
        acc.Curriculum_Product__c = 'Courseleaf CIM';
        acc.Catalog_Product__c = 'Courseleaf CAT';
        acc.Event_Scheduler_Product__c = 'EMS';
        insert acc; //now we have an ID
        
        Pricebook2 stdpb = new Pricebook2(Id = Test.getStandardPricebookId());
        update stdpb;

        Product2 p = new Product2(Name = 'Catalog Management', CanUseRevenueSchedule = true, IsActive = true);
        insert p;
        
        Product2 p2 = new Product2(Name = 'Curriculum Management', CanUseRevenueSchedule = true, IsActive = true);
        insert p2;
        
        Product2 p3 = new Product2(Name = 'Class Scheduler', CanUseRevenueSchedule = true, IsActive = true);
        insert p3;
        
        Product2 p4 = new Product2(Name = 'Event Scheduler', CanUseRevenueSchedule = true, IsActive = true);
        insert p4;

        PricebookEntry pbe = new PricebookEntry(Product2Id = p.Id, Pricebook2Id = stdpb.Id, IsActive = true, UnitPrice = 0);
        insert pbe;
        
        PricebookEntry pbe2 = new PricebookEntry(Product2Id = p2.Id, Pricebook2Id = stdpb.Id, IsActive = true, UnitPrice = 0);
        insert pbe2;
        
        PricebookEntry pbe3 = new PricebookEntry(Product2Id = p3.Id, Pricebook2Id = stdpb.Id, IsActive = true, UnitPrice = 0);
        insert pbe3;
        
        PricebookEntry pbe4 = new PricebookEntry(Product2Id = p4.Id, Pricebook2Id = stdpb.Id, IsActive = true, UnitPrice = 0);
        insert pbe4;
        
        opportunity opp = new opportunity();
        opp.name='test opp';
        opp.accountId = acc.Id; 
        opp.closedate = date.today().adddays(5);
        opp.stagename='Interest'; //when you create an op you need a stage, acocunt, name, and close date
        
        test.startTest();
        insert opp;
        
        
        OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = opp.Id, PricebookEntryId = pbe.Id, Quantity = 1, UnitPrice = 50);
        insert oli;
        
        OpportunityLineItem oli2 = new OpportunityLineItem(OpportunityId = opp.Id, PricebookEntryId = pbe2.Id, Quantity = 1, UnitPrice = 50);
        insert oli2;
        
        OpportunityLineItem oli3 = new OpportunityLineItem(OpportunityId = opp.Id, PricebookEntryId = pbe3.Id, Quantity = 1, UnitPrice = 50);
        insert oli3;
        
        OpportunityLineItem oli4 = new OpportunityLineItem(OpportunityId = opp.Id, PricebookEntryId = pbe4.Id, Quantity = 1, UnitPrice = 50);
        insert oli4;
        
        opp.closedate = date.today();
        opp.stageName = 'Closed Won';
        update opp; 
        account actTest = [SELECT Id, Account_Lifecycle_Status__c, Class_Schedule_Planning_Product__c, Past_Class_Scheduling_Product__c, 
                                                                   Curriculum_Product__c, Past_Curriculum_Product__c,
                                                                   Catalog_Product__c, Past_Catalog_Product__c,
                                                                   Event_Scheduler_Product__c, Past_Event_Scheduling_Product__c
                                                                   FROM Account WHERE ID = :acc.Id LIMIT 1];
        update actTest; 
        system.assertequals('Customer', actTest.Account_Lifecycle_Status__c,'Opportunity update did not set account status properly');
        system.assertequals('Coursedog', actTest.Curriculum_Product__c, 'Opportunity did not set curriculum product properly');
        system.assertequals('Courseleaf CIM', actTest.Past_Curriculum_Product__c, 'Opportunity did not set curriculum product properly');
        system.assertequals('Coursedog', actTest.Class_Schedule_Planning_Product__c, 'Opportunity did not set scheduling product properly');
        system.assertequals('Astra Scheduler', actTest.Past_Class_Scheduling_Product__c, 'Opportunity did not set scheduling product properly');
        system.assertequals('Coursedog', actTest.Event_Scheduler_Product__c, 'Opportunity did not set event product properly');
        system.assertequals('EMS', actTest.Past_Event_Scheduling_Product__c, 'Opportunity did not set event product properly');
        system.assertequals('Coursedog', actTest.Catalog_Product__c, 'Opportunity did not set catlog product properly');
        system.assertequals('Courseleaf CAT', actTest.Past_Catalog_Product__c, 'Opportunity did not set catalog product properly');

        test.stopTest();
        
       
    }
}

 
Best Answer chosen by Jordan Kindler
RituSharmaRituSharma
In line no. 59 of cd_OpportunityLineItemTriggerHandlerv2 class, logic is adding 0 days to the Contract_Start_Date__c date field. You need to set the value of this field for the opportunity that you are creating in the test class(line no. 47) to fix the error. 

Alternatively, you may update cd_OpportunityLineItemTriggerHandlerv2 class to check value of Contract_Start_Date__c field. If it's null then bypass the addDays logic.
swapna sree 3swapna sree 3 
write a child to parent query on opportunity and opportunity line item
Best Answer chosen by swapna sree 3
RituSharmaRituSharma
To query Opportunity data along with opportunity line items data using below Query:
Select Id,Name,(Select Id,Name from OpportunityLineItems) from Opportunity

To query Opportunity Line Item data along with Opportunity fields using below Query:
Select Id,Name,Opportunity.Name from OpportunityLineItem
 
degmodegmo 
Hi,
I am trying to create a test for a class that has if/else logic based on different lookup values for a field.  Below is a snippet of the code that I need to test.  I typcially would like to use Test Data Factory and testSetup when writing my unit tests.  I am trying to figure out the most efficient way to accomplish this.  

Should I create different student records with the different affliate lookup values in the Test Data Factory or is it more efficient to create one student record do a fetch a update with the different values in each test method?
 
if(student__c.affiliate__c == 'freshman') {
   // do stuff
}
else if(student__c.affiliate__c == 'sophomore') {
  // do stuff
}
else if (student__c.affiliate__c == 'junior') {
  // do stuff
}

Both student__c and affiliate__c are custom object.  There is a lookup r/ship b/n them.

 
Best Answer chosen by degmo
Andrew GAndrew G
In a way, it depends on what the code is doing.  

If part of the code behaviour to be tested is the transition from Freshman to Sophomore for the student record, then one Student record would be enough. And if you are only testing the assignment once, i would create the Affiliate record in each method.  But if there are multiple uses for each Affiliate record, then create them in the testSetup.  

If the code to be run is simply a doing something for each type of student, then a data creation of 3 x Student records each with a different associated Affiliate would do. And i would do that in the Testsetup.

If the code is to check some sort of insert event, then the data may need to be created an inserted in each test method.

Do a quick think or scribble on a pad, work out what are your test scenarios.  i.e. You want to test 6 things.  A positive and a negative for each affiliate relationship, then easy decision, all in Test setup.

Remember the main key for using @testSetup is the re-use of the test data.  It is quicker & more efficient for your test code to insert a record once and reset it in 2 test methods than it is to create that test record in 2 separate test methods.
If you find yourself building (or needing) the same data in each test method, then testSetup is where you want to be. 

HTH
Andrew
 
sfadm sfadmsfadm sfadm 

I have a custom text field "Field 1" 
User-added image
I've found the following link: https://developer.salesforce.com/forums/?id=9062I000000IHO4QAO
However, I'm not aware of how to view and edit the HTML source of the text field "Field 1".

How can I access the HTML source of "Field 1" in order to add the CSS style?

Best Answer chosen by sfadm sfadm
RituSharmaRituSharma
Hi sfadm,

From snapshot it seems that it's of standard page layout. If yes, you can't increase the size of the label. You may increae the label only if it's a custom lightning page.

Keep learning!