• Andrew G
  • PRO
  • 2874 Points
  • Member since 2014
  • Salesforce Learner

  • Chatter
    Feed
  • 94
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 12
    Questions
  • 538
    Replies
Hi Experts,

Request you to provide some solution for me.

public class Test_insert {
    public map<String,Integer> EmpMap = new map<String, Integer>();
    public Test_insert(Integer preVetReviews,Integer preVetReviews_Tue,Integer preVetReviews_Wed,Integer preVetReviews_Thur,Integer preVetReviews_Fri)
    {
        Test__c acc= new Test__c();
        EmpMap.put('Monday',preVetReviews);
        EmpMap.put('Tuesday',preVetReviews_Tue);
        EmpMap.put('Wedneday',preVetReviews_Wed);
        EmpMap.put('Thursday',preVetReviews_Thur);
        EmpMap.put('Friday',preVetReviews_Fri);
        set<String> allKeys = EmpMap.keySet();
        list<Integer> allValues = EmpMap.Values();
        for(String k : EmpMap.keySet())
        {
           acc.Name = 'Test';
           acc.PrevetReview__c = EmpMap.get(k);
           System.debug('The Key is: ' +k+ ' and the value is: ' +EmpMap.get(k));
           insert acc;
        }
    }

}

Above is my code and I call it using

Test_insert a = new Test_insert(2,3,4,5,6);

Obseved output:
Record is inserted only once into my object for feild PrevetReview__c

Expected output:
I need record to be inserted five time for feild PrevetReview__c

Please help
Hi All, I picked up trigger 1 from trailhead (believing effeciently written ) where Map is used at point in the trigger but I was able to achieve what trigger 1 is doing by using list in trigger 2 (written by me) now what I wonder is I don't see any necessity of using Map in trigger 1.

I am curious to know if both the triggers are effeciently written or only one of them, if so why ?

Trigger - 1
 
trigger AddRelatedRecord1 on Account(after insert) {

    List<Opportunity> oppsToInsrt = new List<Opportunity>();
    // Get the related opportunities for the accounts in this trigger

    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
        [SELECT Id,Name,(SELECT Id,StageName,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
    
    // Add an opportunity for each account if it doesn't already have one.
    // Iterate through each account.
    for(Account a : Trigger.New) {
        System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
        // Check if the account already has a related opportunity.
        if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
        
            // If it doesn't, add a default opportunity
            oppsToInsrt.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       AccountId=a.Id));
        }           
    }
    if (oppsToInsrt.size() > 0) {
        insert oppsToInsrt;
    }
}

Trigger - 2
 
trigger AddRelatedRecord2 on Account(after insert) {
   
    List<Opportunity> oppList = new List<Opportunity>();  
    
    List<Account> acctsWithOpps = new List<Account>(
        [SELECT Id,Name,city__c,(SELECT Id,stageName,closeDate,city__c FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

    for(Account a : acctsWithOpps) {
           
        if (a.Opportunities.size() == 0) {
          
            oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       City__c = a.city__c,
                                       AccountId=a.Id));
        }           
    }
    if (oppList.size() > 0) {
        insert oppList;
    }
}

 
i am having 90% code coverage because atch block is not covered,can anyone help in writing code for catch block as well

Apex code -->
public class PickListHandler {
    @AuraEnabled
    public static List<String> getLevel1(){
    List<String> tempLst1 = new List<String>();
        for(AggregateResult  ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c  group by Level_1__c])
    {
        tempLst1.add(''+ar.get('Level_1__c'));
    }

    return tempLst1;
      
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel2(string strName){
    List<String> tempLst2 = new List<String>();
       for(AggregateResult  ar : [select Level_2__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName  group by Level_2__c])
    {
       tempLst2.add(''+ar.get('Level_2__c'));
    }

    return tempLst2;
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel3(string strName1,string strName2){
     List<String> tempLst3 = new List<String>();
      for(AggregateResult  ar : [select Level_3__c,COUNT(id) from Case_Type_Data__c  where Level_1__c=:strName1 and Level_2__c=:strName2 group by Level_3__c])
    {
       tempLst3.add(''+ar.get('Level_3__c'));
    }

    return tempLst3;
      
      
    } 
         
     @AuraEnabled
     Public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }
     
    catch(Exception ex){
            strMsg='error';
        }
     return strMsg;  
}

}

Test class code -->
@isTest
public class testGetAllLevels { 

static testMethod void testGetLevel1()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel1();

}
    
static testMethod void testGetLevel2()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel2('Test Level 1');

}
    
static testMethod void testGetLevel3()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
    List<String> s = PickListHandler.getLevel3('Test Level 1','Test Level 2');

}
    
    
static testMethod void testsaveCaseType(){
        // Create the Case Record.
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
        insert cas;
       
        ERT_Case_Type__c obj=new ERT_Case_Type__c();
        string one='one';
        string two='two';
        string three='three';
        test.startTest();
        String testing=PickListHandler.savecasetype(one,two,three,cas.id);
        test.stopTest();
    }
    
 
    
}

Thanks in advance
Carolyn
when there is a salesforce update, does your apex coding update as well?
Hi,
I am getting this error for this code ,how do i fix it
 
public with sharing class saveCaseType {
     
     @AuraEnabled
     Public  static List<String>  savecasetype(string level1,string level2,string level3,string caseid){
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Id =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     return obj;
     }
    
    
    

}

 
hey gurus,

need your help in writing test class code for below apex class
 
public with sharing class SaveRecord_Lightning{
    
	@AuraEnabled
	public static List<ERT_Case_Type> getAllrecords(){
	 
	 return [SELECT Id,Case__c,Level1__c,Level2__c,Level3__c from ERT_Case_Type];
	 }
	 
	 @AuraEnabled
	 public static ERT_Case_Type saveRecord(ERT_Case_Type recordDetail){
	   upsert recordDetail;
	   return recordDetail;
	   
	 
	 }
	
	
	}

Your help is highlyappreicated
Carolyn
Hello, 

I need help in getting  test coverage for this trigger. I am a newbie but I've looked at some trailheads and the type triggers they show as examples are much different then this trigger. I just need to know HOW I showd starte as this looks like it access a bunch of oother APEX classes. I really just want to deactivate it in production which is the only reason I need to push it from Dev to Prod. 
Thanks. 

trigger MDP_Tgr_Opportunity_After on Opportunity (after insert, after update, after delete) {

    
    system.debug('in the MDP_Tgr_Opportunity_After trigger');
    
    if(!MDP_Utils.updateOpportunityfromSalesTeamHandler){

      
        if(!V2SA_Trg_Opportunity_Helper.isValidVPAccountOwner(Trigger.newMap)) return;

        
        if (trigger.isInsert) {
            system.debug('in the insert statement of MDP_Tgr_Opportunity_After trigger');
            
            system.debug('LR: AFTER VP VALIDATION');

           
            MDP_Tgr_Opportunity_Handler.CreateSharesOnInsert(trigger.new);
            
            
            
           
            system.debug('end of the insert statement of MDP_Tgr_Opportunity_After trigger');
     
        if(trigger.isUpdate){
            system.debug('in the update statement of MDP_Tgr_Opportunity_After trigger');
            
            MDP_Tgr_Opportunity_Handler.CreateSharesOnUpdate(trigger.new, trigger.oldMap);
            
            
            MDP_Tgr_Opportunity_Handler.sendOMSMessages(Trigger.new, Trigger.oldMap);
            
            MDP_Tgr_Opportunity_Handler.setPriceBookAfterUpdate(Trigger.new, Trigger.oldMap);
            system.debug('end of the update statement of MDP_Tgr_Opportunity_After trigger'); 
        }
    }
    system.debug('end of the MDP_Tgr_Opportunity_After trigger');

} // End: trigger MDP_Tgr_Opportunity_After
 
Hi,
I am tryin gto fetch a field value and below is the code,but i am getting below error in SForce
 
Illegal conversion from List<AggregateResult> to List<String>

here is apex code
public class PickListHandler {
    @AuraEnabled
    public static List<String> getLevel1(){
     
    
       List<AggregateResult> groupedLevel1
  = [select Level_1__c,COUNT(id) from Case_Type_Data__c  group by Level_1__c];
        
        for(AggregateResult  ar : groupedLevel1){                
           System.debug('Level Value Is' + ar.get('Level_1__c'));
        
        }
      
        return groupedLevel1;
    } 
   

}

 
Hi, I'm trying to add multiple accounts to one contact. Currently, I am unable to and this causes me to have to make multiple Contacts for the same person. The few things I've tried:

1. Adding a Custom Field & Relationship for Accounts. A Related List field shows up, but only allows me to add New Accounts, not Existing.

2. Enabled "Allow users to relate a contact to multiple accounts" under Account Settings. This creates a field under "Contact Detail" that allows me to add an Existing Acccount. However, when I open that Account, the Contact does not show up in the Related List section.

3. Spoke with a Salesforce Customer Service Rep and they said I may need Developer Assistance to achieve this, because it is a "one-to-many" (or something like that) relationship.

I'm new to Salesforce so any assistance would be greatly appreciated. I'd be happy to share screenshots or further explanation on any of the points above. Thank you! 
version 47.0

Trying to craft a unit test. Using @testSetup method, which instantiates some objects within a System.RunAs to avoid the DML problem. But (at least) one of my objects instantiated within the System.RunAs is not visible to the test method even tho it does indeed get instantiated and inserted in the test setup method
@isTest
public class TaskHandlerTest {
    public static Id profileId  = [SELECT Id FROM Profile WHERE Name ='ASUO API User Profile'].Id;
    public static User thisUser = [SELECT Id FROM User WHERE Name = 'API ASU EdPlus ASUO'];
    
    public static UserRole testUserRole_ASU;
    public static Contact contact_ASU;

    @testSetup
    static void setUpTest() {

        testUserRole_ASU = new UserRole(
            Name = 'ASU Local',
            OpportunityAccessForAccountOwner = 'Edit'
        );
        insert testUserRole_ASU;
        System.RunAs( thisUser) {
            contact_ASU = new Contact(
                FirstName = 'Pete',
                LastName = 'Townshend',
                Email = 'thewho1@who.com',
                Last_Contact_Method__c = 'text',
                Last_Contact_Attempt__c = Datetime.valueOf('2020-04-04 00:00:00')
            );
            insert contact_ASU;
            System.debug('contact_ASU inserted with Id: ' + contact_ASU.Id);
        }
    }

    @IsTest
    static void test_pass_new_EmailOutbound() {
        Test.startTest();
        TestDataFactory.createCustomSetting('Object Triggers');
        Task task = new Task(
            Description = 'pass_new_EmailOutbound',
            TaskSubType = 'Email',
            Email_Direction__c = 'Outbound',
            WhoId = contact_ASU.Id,  // <--- throws "dereferencing null value" msg here
            Actual_End__c = Datetime.valueOf( '2020-05-20 00:00:00')
        );
        insert task;  // should trigger TaskHandler after_insert()

        System.assertEquals( contact_ASU.Last_Contact_Method__c, 'Email');
        System.assertEquals( contact_ASU.Last_Contact_Attempt__c, task.Actual_End__c);
        Test.stopTest();
    }
}
contact_ASU is declared static outside of setUpTest().
The debug log shows my contact_ASU does get instantiated and inserted and has an Id.  Both setUpTest and test_pass_new_EmailOutbound() are declared static.

So I would expect contact_ASU to be visible to test_pass_new_EmailOutbound() --  what am I doing wrong/ not doing right ?

TIA,

Chris

 
Hi,

I'm using two objects: Cases and Agreements, each with two record types (NDA and MSA). I want to create a Case with a record type NDA that will create an NDA record type record in the Agreements object.

I can do this with Process Builder, except I can't seem to get the Case NDA request to create a NDA record type in Agreements - for some reason it defaults to MSA. 

Just wondering if it's possible to select various record types, (Case NDA  create Agreement NDA record) or does Process Builder only know how to create a new record in another object w/out being able to distinguish record types? If it's not possible, does anyone have any workarounds?

Thank you!
Hi - I am an admin that is trying to code something into our instance to calculate business hours between 2 date/time fields based on owner location to account for time zone changes. I was able to find and tweak the code from this website (https://www.tech-vision.us/salesforce-the-number-of-business-hours-between-two-date-time-fields/). I then wrote a Test Class but am only able to get to 55% code coverage and cannot figure out why. 

Trigger:
trigger Demo_Response_Biz_Hours_Time_Zones on Lead (before insert, before update) {
   
    //Selecting all active BusinessHours records
    List<BusinessHours> BusinessHours_List = [SELECT Id, Name FROM BusinessHours WHERE IsActive = true];
   
    //Adding map where BusinessHours Name will be the key
    Map<String, BusinessHours> LocationName_BusinessHours_Map = new Map<String, BusinessHours> ();
   
    //Filling the map | Location Name, BusinessHours Object
    for (BusinessHours b : BusinessHours_List) {
        LocationName_BusinessHours_Map.put(b.Name, b);
    }
    for (Lead leadObj : Trigger.new) {
        
        //This part of a trigger only works when we add new records
        if (Trigger.isInsert) {
            
            //We check if both Start Time & Completed Time fields are not empty
            if (leadObj.Demo_Form_Submission_Date__c != NULL && leadObj.First_Activity_Most_Recent_Demo_Request__c != NULL) {
                
                //Then we do another check if current record is tied to a location that has business hours record
                if (LocationName_BusinessHours_Map.containsKey(leadObj.Owner_Location__c)) {
                    decimal result = BusinessHours.diff(LocationName_BusinessHours_Map.get(leadObj.Owner_Location__c).Id, leadObj.Demo_Form_Submission_Date__c, leadObj.First_Activity_Most_Recent_Demo_Request__c);
                    Decimal resultingHours = result / (60 * 60 * 1000);
                    leadObj.APEXTEST_Demo_Response_Time_Zones__c = resultingHours.setScale(1);
                } else{
                    
                    //Just as a safety net, let's use default business hours in case there is no match between Location name and BH name
                    if(LocationName_BusinessHours_Map.get('Default').Id != NULL){
                        decimal result = BusinessHours.diff(LocationName_BusinessHours_Map.get('Default').Id, leadObj.Demo_Form_Submission_Date__c, leadObj.First_Activity_Most_Recent_Demo_Request__c);
                        Decimal resultingHours = result / (60 * 60 * 1000);
                        leadObj.APEXTEST_Demo_Response_Time_Zones__c = resultingHours.setScale(1);
                    }
                }
            }
        } else if (Trigger.isUpdate) {
            
            //This part of a trigger only works when we perform update
           
            //Checking if Start Time or Completed Time has been changed & if they are not empty
            if ((leadObj.Demo_Form_Submission_Date__c != NULL && leadObj.First_Activity_Most_Recent_Demo_Request__c != NULL) && ((leadObj.Demo_Form_Submission_Date__c != Trigger.oldMap.get(leadObj.id).Demo_Form_Submission_Date__c) || (leadObj.First_Activity_Most_Recent_Demo_Request__c != Trigger.oldMap.get(leadObj.id).First_Activity_Most_Recent_Demo_Request__c))) {
                if (LocationName_BusinessHours_Map.containsKey(leadObj.Owner_Location__c)) {
                    decimal result = BusinessHours.diff(LocationName_BusinessHours_Map.get(leadObj.Owner_Location__c).Id, leadObj.Demo_Form_Submission_Date__c, leadObj.First_Activity_Most_Recent_Demo_Request__c);
                    Decimal resultingHours = result / (60 * 60 * 1000);
                    leadObj.APEXTEST_Demo_Response_Time_Zones__c = resultingHours.setScale(1);
                } else{
                    if(LocationName_BusinessHours_Map.get('Default').Id != NULL){
                        decimal result = BusinessHours.diff(LocationName_BusinessHours_Map.get('Default').Id, leadObj.Demo_Form_Submission_Date__c, leadObj.First_Activity_Most_Recent_Demo_Request__c);
                        Decimal resultingHours = result / (60 * 60 * 1000);
                        leadObj.APEXTEST_Demo_Response_Time_Zones__c = resultingHours.setScale(1);
                    }
                }
            } else if (leadObj.Demo_Form_Submission_Date__c == NULL || leadObj.First_Activity_Most_Recent_Demo_Request__c == NULL) {
                
                //Another safety net that will reset Hours spent in case Start Time OR Completed time becomes empty after update.
               
                //That way you won't have old & inaccurate data from past calculations.
                leadObj.APEXTEST_Demo_Response_Time_Zones__c = NULL;
            }
        }
    }
}

Test Class:
@isTest

public class TestDemoResponseTime {

    Static testmethod void LeadTest() {
    
        //create a lead
        Lead leadObj = new Lead();
        leadObj.LastName = 'Test';
        leadObj.Company = 'Test ABC';
        leadObj.LeadSource = 'Sales Prospecting';
        leadObj.Lead_Source_Detail__c = 'Apex Test Class';
        leadObj.OwnerID = '0054G000008UaurQAC';
        leadObj.Demo_Form_Submission_Date__c = datetime.newInstance(2020, 04, 15, 14, 00, 00);
                
        insert leadObj;
        
        //business hours
        BusinessHours b = [SELECT Id FROM BusinessHours WHERE Name = 'Denver'];
        
        //update the lead
        leadObj = [SELECT Id, LastName, Company, LeadSource, Lead_Source_Detail__c, OwnerID, Owner_Location__c, Demo_Form_Submission_Date__c, First_Activity_Most_Recent_Demo_Request__c FROM Lead WHERE Id != NULL];
        leadObj.First_Activity_Most_Recent_Demo_Request__c = datetime.newInstance(2020, 04, 16, 19, 00, 00);
        
        update leadObj;
   }
}

I've checked the developer console and the sections that aren't covered are:
if (LocationName_BusinessHours_Map.containsKey(leadObj.Owner_Location__c)) {
                    decimal result = BusinessHours.diff(LocationName_BusinessHours_Map.get(leadObj.Owner_Location__c).Id, leadObj.Demo_Form_Submission_Date__c, leadObj.First_Activity_Most_Recent_Demo_Request__c);
                    Decimal resultingHours = result / (60 * 60 * 1000);
                    leadObj.APEXTEST_Demo_Response_Time_Zones__c = resultingHours.setScale(1);

Does anyone have any ideas on what I'm missing? Thank you!
Hi there,

Please help with this class where I am getting an error upon saving the test class below:
 
@isTest
public class APTS_ResendCreditMemoEmailTest{
    static testMethod  void creditMemoDocumentGenerationTest(){

        Profile profileSO = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
        
        User userSO = APTS_TestDataFactory.getUser('LastName123','medidate', profileSO.ID);
        insert userSO;
        System.runAs(userSO){
            EmailTemplate emailTemplateSO1 = APTS_TestDataFactory.getEmailTemplate('APTS Non Japan Invoice','APTS_Non_Japan_Invoice', userSO.ID);
            List<EmailTemplate> listEmailTemplate = new List<EmailTemplate>();
            listEmailTemplate.add(emailTemplateSO1);
            insert emailTemplateSO1;
        }

        insert APTS_TestDataFactory.getTaxConnectorConfigSetting();

        //Create & Insert Core Currency
        appirio_core__Currency__c coreCurrencyUSD = APTS_TestDataFactory.getCoreCurrency('U.S. Dollar','USD', TRUE);
        LIst<appirio_core__Currency__c> coreCurrencylist = new List<appirio_core__Currency__c>();
        coreCurrencylist.add(coreCurrencyUSD);
        insert coreCurrencylist;
        
        APTS_Legal_Entity__c legalEntitySO= APTS_TestDataFactory.getLegalEntity('Japan', coreCurrencyUSD.ID, FALSE);
        legalEntitySO.APTS_LE_Company_Code__c = 'ABC';
        legalEntitySO.APTS_LE_Country__c  = 'DEF';
        insert legalEntitySO;

        Apttus_Config2__PaymentTerm__c paymentTermSO = APTS_TestDataFactory.createPaymentTerm('Net 120', 'Net 120 Days', 120 , TRUE);
        insert paymentTermSO;

        APTS_Invoice_Number_Settings__c invoiceNumberSettingSO = APTS_TestDataFactory.getInvoiceNumberSetting(legalEntitySO.ID);
        insert invoiceNumberSettingSO;

        //Create & Insert Account
        Account accSO = APTS_TestDataFactory.getAccount('Test Account');
        accSO.APTS_Global_MSA__c = TRUE;
        insert accSO;
        
        Contact contactSO1 = APTS_TestDataFactory.getContact(accSO.ID, 'Japan', 'Last1', 'Japan');
        Contact contactSO2 = APTS_TestDataFactory.getContact(accSO.ID, 'Esker', 'Last2', 'Japan');
        List<Contact> listContact = new List<Contact>();
        listContact.add(contactSO1);
        listContact.add(contactSO2);
        insert listContact;

        Apttus_Config2__AccountLocation__c accountLocationSO1 = APTS_TestDataFactory.getAccountLocation('USA Account Location', accSO.ID, 'USA');
        accountLocationSO1.Apttus_Config2__DefaultInvoiceTemplate__c = 'APTS Non Japan Invoice';
        Apttus_Config2__AccountLocation__c accountLocationSO2 = APTS_TestDataFactory.getAccountLocation('USA Account Location', accSO.ID, 'USA');
        List<Apttus_Config2__AccountLocation__c> accountLocationList = new List<Apttus_Config2__AccountLocation__c>();
        accountLocationList.add(accountLocationSO1);
        accountLocationList.add(accountLocationSO2);
        insert accountLocationList;

        Opportunity oppSO1 = APTS_TestDataFactory.getOppty(accSO.ID, 'USA Opp');
        Opportunity oppSO2 = APTS_TestDataFactory.getOppty(accSO.ID, 'USA Opp');
        List<Opportunity> oppList = new List<Opportunity>();
        oppList.add(oppSO1);
        oppList.add(oppSO2);
        insert oppList;

        Apttus_Config2__Order__c orderSo = APTS_TestDataFactory.getOrder(accSO.Id, oppSO1.ID, accountLocationSO1.ID);
        orderSo.Apttus_Config2__PaymentTermId__c = paymentTermSO.ID;
        orderSo.APTS_Invoice_Delivery_Method_Email__c = true;
        orderSo.APTS_Invoice_Delivery_Method_Print__c = true;
        insert orderSo;

        Apttus_Billing__Invoice__c invoiceSO1 = APTS_TestDataFactory.getInvoice(accSO.ID, paymentTermSO.ID);
        invoiceSO1.APTS_Legal_Entity__c = legalEntitySO.ID;
        invoiceSO1.Apttus_Billing__LocationId__c = accountLocationSO1.ID;
        invoiceSO1.APTS_Order__c = orderSo.ID;
        
        Apttus_Billing__Invoice__c invoiceSO2 = APTS_TestDataFactory.getInvoice(accSO.ID, paymentTermSO.ID);
        invoiceSO2.APTS_Legal_Entity__c = legalEntitySO.ID;
        invoiceSO2.Apttus_Billing__LocationId__c = accountLocationSO2.ID;
        invoiceSO2.APTS_Order__c = orderSo.ID;

        List<Apttus_Billing__Invoice__c> invoiceList = new List<Apttus_Billing__Invoice__c>();
        invoiceList.add(invoiceSO1);
        invoiceList.add(invoiceSO2);
        insert invoiceList;

        Apttus_Billing__CreditMemo__c creditMemoSO = APTS_TestDataFactory.getCreditMemmo(accSO.ID, invoiceSO1.ID);
        creditMemoSO.APTS_Legal_Entity__c = legalEntitySO.ID;
        creditMemoSO.Apttus_Billing__LocationId__c = accountLocationSO1.ID;
        creditMemoSO.APTS_Shipping_Location__c = accountLocationSO1.ID;
        //creditMemoSO.Apttus_Billing__Status__c = 'Approved';
        creditMemoSO.Apttus_Billing__DeliveryStatus__c = 'Pending';
        creditMemoSO.APTS_Order__c = orderSo.ID;

        List<Apttus_Billing__CreditMemo__c>creditMemolist = new List<Apttus_Billing__CreditMemo__c>();
        creditMemolist.add(creditMemoSO);
        insert creditMemolist;
        
        Attachment attachmentSO = APTS_TestDataFactory.getAttachment(creditMemoSO.ID,'CreditMemo Attachment');
        List<Attachment> listAttachment = new List<Attachment>();
        listAttachment.add(attachmentSO);
        insert listAttachment;


        Apttus_Billing__RelatedARTransaction2__c relatedARTransactionSO = APTS_TestDataFactory.getRelatedARTransaction(invoiceSO1.ID);
        relatedARTransactionSO.Apttus_Billing__TxnType__c = 'Refund';
        relatedARTransactionSO.Apttus_Billing__DestinationCreditMemoId__c = creditMemoSO.ID;
        insert relatedARTransactionSO;
        
        Test.startTest();
        Test.setCurrentPageReference(new PageReference('Page.myPage'));
        System.currentPageReference().getParameters().put('creditMemoID', creditMemoSO.ID);
        System.currentPageReference().getParameters().put('status', 'Approved');

        APTS_ResendCreditMemoEmail resendCreditMemoEmail = new APTS_ResendCreditMemoEmail();
        resendCreditMemoEmail.resendEmail();
        
        Test.stopTest();

    }
}

The error is:

Error: Compile Error: Method does not exist or incorrect signature: void getOrder(Id, Id, Id) from the type APTS_TestDataFactory at line 62

Any guidance would be most appreciated. Thank you!
 
Hi All,

When Record is submitted as Draft. Profile should have edit access for that Draft.
Two profile: P1 and P2. Two page layout created for both profile one is read only and other Read/Write access. When P1 submit a record as status is saved as Draft . P1 should have access to Edit that record.

Page layout in detail page if I had Edit button. It assign to both the page layout. Is there any other way around to achieve this.

Thanks for the help in advance
public with sharing class FieldnotEmptycontrl {

    public static Property__c field {get; set;}

    public FieldnotEmptycontrl(){
    field = new Property__c();

    }

    public static void fieldNotEmpty(List<Property__c> prop){

        if(field.Business__c == null || field.Contact__c == null){

            field.Business__c.addError('You must enter a value!');
            field.Contact__c.addError('You must enter a value!');

        if(field.Business__c != null && field.Contact__c != null){

            field.Business__c.addError('Cannot use two fields at the same time. Please choose only one field Business or Contact');
            field.Contact__c.addError('Cannot use two fields at the same time. Please choose only one field Business or Contact');
        }

        }
    }
}
Here is the Trigger calling the above class and method, but it shows the error • triggers/fieldNotEmpty.trigger: ERROR at line 1, column 1 - Must specify the metadata file 
trigger fieldNotEmpty on Property__c (before insert, before update, after insert) {

    if (Trigger.isBefore) {
        if(Trigger.isInsert){

            FieldnotEmptycontrl.fieldNotEmpty(Trigger.new);
          
        }
    }
}
Please help me to resolve the issue
 
The below batch class will be processing a little over 2.5 million records. The START method will be sending in the whole 2.5 million records to the execute method and the execute method does the processing on each of the 2.5 million records inside a for loop. 
Also the for loop has a SOQL inside which I believe cannot be avoided to get the right numbers. 
Is this the right way of doing this or are there any other better ways. Please help!

Also when the running the below batch class I get the First Error: Too many query rows error.
 
global class MDUSquadRawDataBatchTest implements Database.Batchable<sObject>, Database.Stateful {  
    List<Address_Master__c> addressList = new List<Address_Master__c>();
    Set<String> addresses = new Set<String>();
   
    // Start Method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator('SELECT Street_Address__c,City_Name__c FROM MDU_Squad_Raw_Data__c');
    }   
    
    // Execute method
    global void execute(Database.BatchableContext BC, List<MDU_Squad_Raw_Data__c> rawData) {        
        for(MDU_Squad_Raw_Data__c mduRawData: rawData) {
            List<MDU_Squad_Raw_Data__c> addressData = [SELECT Street_Address__c,City_Name__c,Province_Code__c,Postal_Code__c,Internet_Service__c,Video_Service__c,Phone_Service__c FROM MDU_Squad_Raw_Data__c WHERE Street_Address__c=:mduRawData.Street_Address__c AND City_Name__c=:mduRawData.City_Name__c];
            String fullAddress = addressData[0].Street_Address__c+' '+addressData[0].City_Name__c+' '+addressData[0].Province_Code__c+' '+addressData[0].Postal_Code__c;
            
            Address_Master__c theAddress = new Address_Master__c();
            if(!addresses.contains(fullAddress.substringBeforeLast(' '))) {
                theAddress.Name = addressData[0].Street_Address__c;
                theAddress.City_Name__c = addressData[0].City_Name__c;
                theAddress.Province_Code__c = addressData[0].Province_Code__c;
                theAddress.Postal_Code__c = addressData[0].Postal_Code__c; 
                fullAddress = addressData[0].Street_Address__c+' '+addressData[0].City_Name__c+' '+addressData[0].Province_Code__c+' '+addressData[0].Postal_Code__c;
                theAddress.Full_Address_Ext_Id__c = fullAddress;

                addresses.add(fullAddress.substringBeforeLast(' '));
                addressList.add(theAddress); 
            }                                                     
        }            
        Database.Upsert(addressList, Address_Master__c.Fields.Full_Address_Ext_Id__c, true);
    }
    // Finish Method    
    global void finish(Database.BatchableContext BC) {
        
    } 
}

I request if someone could please help me with this, as I am dealing with this for some time, with no idea on how to fix this.
Hello all. I am making a class that ensures that there is an attachment on an Opp whenever its closed won. Below is my class that actually does the logic. Below that is the test class. The logic works fine but I can only get 42% coverage though. The underlined code is what is not being covered, this is in a Lightning instance fyi. Thanks for the help!

public class OpportunityHandler {
    public static void checkOppForAttachment (List<Opportunity> oppList){
        
        for(Opportunity opp : oppList){
            if(opp.stageName == 'Closed Won' || opp.stageName == 'Closed Won (R)'){
                ContentDocumentLink cdl = null;
                List<ContentDocumentLink> cdl2 = [Select Id from ContentDocumentLink where LinkedEntityId =:opp.Id];
                   
                if (cdl2.isEmpty()){

                    opp.addError('Please ensure the contract is attached prior to closing this Opportunity');
                }
            }
        }
    }
}

Test Class
@isTest
public class OpportunityHandlerTest {
    @isTest public static void validateAttachment() {
        //Create Account and Opportunity
    List<RecordType> acctRecType = [Select Id from RecordType where developerName = 'Company' and sObjectType = 'Account'];
    List<RecordType> oppRecType  = [Select Id from RecordType where developerName = 'AM_Channel' and sObjectType = 'Opportunity'];
            Test.startTest();
        try{
    Account acct      = new Account();
    acct.name         = 'Test Account1';
    acct.RecordTypeId = acctRecType.get(0).id;
    insert acct;
        
    Opportunity opp     = new Opportunity();
        opp.Name        = 'test opp';
        opp.CloseDate   = system.today()+1;
        opp.StageName   = 'Initial Pitch/Demo';
        opp.Use_Case__c = 'Brand Tracker';
        opp.AccountId   = acct.Id;
        opp.RecordTypeId = oppRecType.get(0).id;
        insert opp;
        
    Opportunity opp2     = new Opportunity();
        opp2.Name        = 'test opp2';
        opp2.CloseDate   = system.today()+1;
        opp2.StageName   = 'Initial Pitch/Demo';
        opp2.Use_Case__c = 'Brand Tracker';
        opp2.AccountId   = acct.Id;
        opp2.RecordTypeId = oppRecType.get(0).id;
        insert opp2;
       

    ContentVersion contentVersion = new ContentVersion(
          Title          = 'a picture',
          PathOnClient   = 'Pic.jpg',
          VersionData    = Blob.valueOf('Test Content'),
          IsMajorVersion = true);
        insert contentVersion; 
        
List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];

//create ContentDocumentLink  record 
    ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = opp.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        cdl.visibility = 'AllUsers';
        insert cdl;
        
List<Opportunity> updateList = new List<Opportunity>();

List<ContentDocumentLink> cdl2 = [Select Id from ContentDocumentLink where LinkedEntityId =:opp.Id];
            List<Opportunity> oldOpp = [Select id from Opportunity where Name = 'test opp'];
                for (Opportunity runUpdate : oldOpp){
                    runUpdate.stageName = 'Closed Won (R)';
                    updateList.add(runUpdate);
                    system.debug(runUpdate.stageName);
                    update updateList;
                    System.assertEquals(documents.size(), 1);
                }
             }
        catch(Exception e){
            System.Assert(e.getMessage().contains('Please ensure the contract is attached prior to closing this Opportunity'));
        }
            test.stopTest();
    }

}
Hey..

I have 4-5 workflows which do the same function on the Account object. They all put a Date Stamp based on different fileds in a picklist. Since we have 5 options in a picklist and we are tracking the date of every option, I have to create 5 different workflows. 

I have little to no experience working with Triggers. Is it possible to achieve this with 1 trigger?


Thanks 
Hey all!

With some help I wrote this custom trigger that allows our reps to list some additional contacts and their information on Lead records that then transform into Contact records on lead convert.
 
trigger CreateMoreLeadContacts on Lead (after update) {

list < Contact > listContacts = new List < Contact>();

for(Lead objLead : trigger.new) {

if(objlead.IsConverted && !trigger.oldMap.get(objLead.Id).IsConverted) {

Contact c1=New Contact(
LastName=objLead.Secondary_Lead_Contact_Name__c,
Phone=objLead.Secondary_Lead_Phone__c,
Email=objLead.Secondary_Lead_Email__c);

c1.AccountId = objLead.ConvertedAccountId;
listContacts.add(c1);

Contact c2=New Contact(
LastName=objLead.Tertiary_Lead_Contact_Name__c,
Phone=objLead.Tertiary_Lead_Phone__c,
Email=objLead.Tertiary_Lead_Email__c);

c2.AccountId = objLead.ConvertedAccountId;
listContacts.add(c2);

     }
        
    }
    
    if ( listContacts.size() > 0 )
        insert listContacts;

}
The trigger works just fine and as expected... however, i've now indentified an issue when trying to convert a Lead when no data is present in both "Secondary Contact Lead Name" & "Tertiary Contact Lead Name".

Only way to get around this with the current trigger is to list dummy Contact name data in the custom lead fields before the Lead gets converted.

What would be the best way to encapsulate the trigger so that it doesn't fire when names aren't listed / just when one additional contact is listed? 



 
The situation: I spun off a sandbox, and within that sandbox, I commented out large portions of code in order to disable a feature we're not going to use, and was linked to an installed package we wished to uninstall.  I ran the entire suit of Apex tests and everything passed with flying colors.

The problem: When I try to deploy the resulting change set into production, I get told "Dependent class is invalid and needs recompilation" for every single item of the change set.  It points to a method in one particular class as the source of the error - a method that I comment out, and I made sure every piece of code referring to that method was commented out too.

According to the help files, the solution was to recompile all Apex classes.  Very well.  Did this in Production, did this in Sandbox, started a new change set and deployment.  Still no dice, the error pops up again.  But I can't recompile any more than what I've already done, so what gives?

How am I supposed to get rid of this error and complete my deployment into production?
Hi all

I understand the concepts and best practice for process builders, but i want to deepen my understanding.
This help file:
https://help.salesforce.com/articleView?id=process_limits.htm&type=5
states:
"Each Create a Record action uses one DML statement. Each Quick Action action uses one DML statement. Each Update Records action uses one SOQL query and one DML statement. "

With reference to the terms "Quick Action" and "Update Records", what is the difference? Is a Quick Action an update to the record that starts the process builder, and an Update Records is an update to a related record? (hence the SOQL to find the record, before we update it  - the DML)

Am I to assume that the Update Record action consumes one SOQL because I need to find the record first?  Does the SOQL occur if the Update Record is happening to the record that started the Process Builder? 

Consider this Process Builder :
User-added image

Do I assume that in Decision Point 1 , since I am doing 3 x Immediate Actions (IA) with each being an Update , that this Decision Point will result in 3 x DML and 3 x SOQL ?  Or is an update to the record which started it a Quick Action and hence only 3 x DML?

Next question to consider, if I have criteria around a IA which is an update, and the IA does not meet that criteria, and therefore does not execute the update, does this count as a SOQL?  but obviously no DML.


This is in consideration that I have inherited a process builder which is getting a too many SOQL query or CPU timeout errors.  I have reviewed the process builder, but before i start a rebuild (it is quite complex), i just want to get some clarity.

Regards
Andrew
Hi

I have a need to be able to create 2 different types of Cases on our Community Portal.

Basically, I have 2 global actions that each create a Case but with a different Record Type.  I have created the buttons on the home page of my community site.  I know they throw to the Create Record Page and I have created 2 x page variations, but when I try the preview and try the buttons, I get which ever page variation is set to Default.

Surely i'm not the first to try this.  Is there some documenation that clearly descibes how to do this?  Or if someone can give me some direction it would be appreciated

Regards
Andrew G
Hi

On the Visualforce page, there is a check box to select to enable the visualforce page to be available under Lightning.
User-added image

Since we use GitHub, how do I see this change in the Git Repository?  Is there an XML tag that is set to true when this check box is enabled?

Regards
Andrew
 
Hello

We are using the FSL managed package.  Needing to write some test coverage for the Maintenance Plan.  In the test class, I am trying to create the Maintenance Plan record as such:
MaintenancePlan maintPlan 
		= new MaintenancePlan( AccountId = testaccs[0].Id,
						Billing_Account__c = testaccs[0].Id,
						WorkTypeId = mpWt[0].Id,
						StartDate = tempDate,
						Customer_Purchase_Order_No__c = 'dummy data',
						Invoicing_Method__c = 'One Invoice per Work Order',
						Crew_Size__c = 2,
						Frequency = 1,
						FrequencyType = 'Months',
						GenerationTimeframe = 1,
						GenerationTimeframeType = 'Months',
						NextSuggestedMaintenanceDate = tempDate,
						WorkOrderGenerationMethod = 'One work order line item per asset',
						SvcApptGenerationMethod = 'One service appointment per work order',
						MaintenancePlanTitle = 'Dummy Title',
						Description = 'Dummy Description'
						);

But on Save, I get an error:
Result: [OPERATION FAILED]: classes/CS_WorkOrderTriggerHandler_Test.cls: Field does not exist: WorkOrderGenerationMethod on MaintenancePlan (Line: 313, Column: 5)
classes/CS_WorkOrderTriggerHandler_Test.cls: Field does not exist: SvcApptGenerationMethod on MaintenancePlan (Line: 313, Column: 5)
(bold added for highlights)
Now in my field list for Maintenance Plan I see :
Snippet showing the offending field names which error message says 'doesn't exist'

So, I've copy pasted the Names but same error.
I have check Field Level Security  - System Admin plus others are listed.
Thoughts or feedback?

Regards
Andrew
 
Hi
In the FSL managed package, from a Maintenance Plan there is an action "Generate Work Orders". 
Shows action menu for Generate Work Orders action
I have done some customisation which rely on the Work Order being generated from the Maintenance Plan.

For my test coverage, how do I invoke the "Generate Work Orders" action in a test class?

Regards
Andrew
Hi
I'm doing a trigger that is triggered from the Assigned Resource.  The trigger works in the UI, however, I'm having an issue with the Test Code.

I receive an error:
FIELD_CUSTOM_VALIDATION_EXCEPTION, Cannot change status from New to Scheduled: []

Now, if i do the same from the UI, there is no error regarding the status change.  The status change is allowed in the FSL administration.  I can assign using the dispatcher console - all good.  And I can mimic the process i'm using in the test code in the UI (editing the SA directly) with out error.  
Wondering if any one has seen this error before?
Code is included below:
@isTest static void test_AssignedResource_Insert() {
		List<AssignedResource> toInsert = new List<AssignedResource>();

		//retrieve a service resource
		List<ServiceResource> listSR = new List<ServiceResource>([SELECT Id, Name FROM ServiceResource WHERE Name = 'Technician One']);
		ServiceResource sr1 = listSR[0];

		// retrieve the Service Appointment created by test data
		List<WorkOrder> workOrders = new List<WorkOrder>([SELECT Id FROM WorkOrder WHERE Subject ='Test Subject1']);
		List<Id> woIds = new List<Id>();
		for (WorkOrder wo : workOrders ) {
			woIds.add(wo.Id);
		}
		if (woIds.size() > 0 ) {
			List<ServiceAppointment> appts = new List<ServiceAppointment> ();
			appts = [SELECT Id FROM ServiceAppointment WHERE Work_Order__c IN :woIds];
			//for all the appts - should be one - create an assigned resource
			if(appts.size()>0) {
				for( ServiceAppointment sa : appts ) {
					sa.SchedStartTime = datetime.newInstance(2019, 4, 19, 11, 00, 0);
					sa.SchedEndTime = datetime.newInstance(2019, 4, 19, 11, 30, 0);

					AssignedResource ar = new AssignedResource(ServiceAppointmentId=sa.Id,ServiceResourceId=sr1.Id);
					toInsert.add(ar);
				}
				update appts;

				insert toInsert;

				List<ServiceAppointment> assignedSA = new List<ServiceAppointment>([SELECT Id,Technician_Name__c FROM ServiceAppointment WHERE Work_Order__c IN :woIds]);
				System.assertEquals(assignedSA.size(), 1);
				System.assertEquals(assignedSA[0].Technician_Name__c,sr1.Name);

			} else {

			}


		} else {
			//exception
			System.assertNotEquals(woIds.size(), 0);
		}


	}
the error occurs on the insert of the assigned resources
insert toInsert;
IF i change the code such that I manually do the status change in the code example:
sa.SchedStartTime = datetime.newInstance(2019, 4, 19, 11, 00, 0);
sa.SchedEndTime = datetime.newInstance(2019, 4, 19, 11, 30, 0);
sa.Status = 'Scheduled';
the error is returned for the update of the service appointments.
update appts;

Feed back greatly appreciated.

Andrew




 
Hi
I'm playing with an Apex trigger for Work Order Object.   In the trigger,I have a need to reference a list of Work Types on multiple occassions, in different parts of the trigger.  The question relates to how do I minimise the number of times I do a SOQL to get those work types.
Example of Trigger
trigger cs_workorderTrigger on WorkOrder (before insert, after insert, after update) {
    if ( trigger.isBefore ) {
        if ( trigger.isInsert ) {
            CS_WorkOrderTriggerHandler.handleBeforeInsert( trigger.new );
	}
    } else {  //trigger is after
        if ( trigger.isInsert ) {
            CS_WorkOrderTriggerHandler.handleAfterInsert( trigger.new );
        } else {
            CS_WorkOrderTriggerHandler.handleAfterUpdate( trigger.new );
	}
    }
}
And my (cut down) hanlder looks like:
public with sharing class CS_WorkOrderTriggerHandler {
			
	public static void handleBeforeInsert(List<WorkOrder> newWorkOrders) {
		populateWorkOrder( newWorkOrders );
	}

	public static void handleAfterInsert(List<WorkOrder> workOrders){
		//declare some variables 
		List<Id> listWorkTypeIds = new List<Id>();

		//List of Ids where their is an auto generate feature enabled
		List<Worktype> workTypes = new List<WorkType>([SELECT Id FROM WorkType WHERE ShouldAutoCreateSvcAppt = TRUE]);

		for ( WorkOrder workOrder : workOrders ) {
			//do some stuff with work Order - like checking the work type Id
		}
	}


	public static void handleAfterUpdate(List<WorkOrder> oldWorkOrders, List<WorkOrder> workOrders, Map<Id,WorkOrder> newValues, Map<Id,WorkOrder> oldValues) {
		//declare some variables 
		List<Id> listWorkTypeIds = new List<Id>();

		//List of Ids where their is an auto generate feature enabled - HEY , THIS IS THE SAME AS THE AFTER INSERT QUERY

		for ( WorkOrder workOrder : workOrders ) {
			//do some other stuff with the work orders, and I still need the work type ids, but this work here is different to the after Insert stuff so i can't combine into a single method.
		}
	}

	public static void populateWorkOrder(List<WorkOrder>workOrders) {
		System.debug('DEBUG: populate Work Order');
		//Here I am going to do some other stuff, and I need that slightly different list of that Work Type Ids
		//something like 
		List<workType> workTypes = new List<WorkType>([SELECT Id,Customer_Type__c,Name FROM WorkType WHERE ShouldAutoCreateSvcAppt = TRUE]);
		//and play with the list a bit differently
	}

	public static void createServiceAppointments(WorkOrder workOrder, Integer saToCreate ) {
		//Create some records here
	}
	
}

I tried doing a constructor at the top of the trigger handler, but I was getting errors like "non static method can be called form static method" or something like that.  It basically broke the other methods I have within the trigger handler.

Any pointers appreciated.

Andrew G
Hello

I'm doing a bit of code where I'm checking if a Work Type Id in a Work Order is in a List for Work Type Ids, but the contains method does not seem to be detecting the match:
Code snippet 
List<ServiceAppointment> svcAppts = new List<ServiceAppointment>();

		//List of Ids where their is an auto generate feature enabled
		List<Id> listWorkTypeIds = new List<Id>();
		for ( WorkType wt : [SELECT Id FROM WorkType WHERE ShouldAutoCreateSvcAppt = TRUE] )  {
			listWorkTypeIds.add(wt.Id);
		}
		System.debug('DEBUG : Worktype count ' + listWorkTypeIds.size());

		
		for ( WorkOrder workOrder : workOrders ) {
			tempDecimal = workOrder.Crew_Size__c;
			crewSize  = tempDecimal.intValue();
			System.debug('DEBUG : crewSize: ' + crewSize);
			
			tempDecimal = workOrder.ServiceAppointmentCount;
			System.debug('DEBUG : RAW service count : ' + tempDecimal);
			System.debug('****DEBUG : list work type : ' + listWorkTypeIds[0]);
			System.debug('****DEBUG : WO work type : ' + workOrder.workTypeId);

			if (listWorkTypeIds.contains(workOrder.workTypeId)) {
				apptCount = tempDecimal.intValue() + 1;		
				System.debug('DEBUG : ADJUSTED service count : ' + tempDecimal);				
			} else {
				apptCount = tempDecimal.intValue();
				System.debug('DEBUG : SAME service count : ' + tempDecimal);
			}
Now, the debug looks like this:
08:10:49.875 (1834107162)|SOQL_EXECUTE_BEGIN|[92]|Aggregations:0|SELECT Id FROM WorkType 
08:10:49.875 (1848717624)|SOQL_EXECUTE_END|[92]|Rows:1
08:10:49.875 (1849133376)|USER_DEBUG|[95]|DEBUG|DEBUG : Worktype count 1
08:10:49.875 (1849315483)|USER_DEBUG|[101]|DEBUG|DEBUG : crewSize: 1
08:10:49.875 (1849418406)|USER_DEBUG|[104]|DEBUG|DEBUG : RAW service count : 0
08:10:49.875 (1849462073)|USER_DEBUG|[105]|DEBUG|****DEBUG : list work type : 08q0l00000001jtAAA
08:10:49.875 (1849543426)|USER_DEBUG|[106]|DEBUG|****DEBUG : WO work type : 08q0l00000001jtAAA
08:10:49.875 (1849692808)|USER_DEBUG|[113]|DEBUG|DEBUG : SAME service count : 0

So, the debug shows that the Ids are apparently the same, but the IF statement using the the contains does resolve to TRUE.

Any thoughts on what I am missing?

Regards
Andrew
 
Hello

Playing with Work Types and the Auto Create feature.  I know there is a check box to tick which will auto create the Service Appointments.
However, I have a need to generate multiple Service Appointments for a single Work Order.  The multiple appointments will have the same parameters as a crew will come together to do that particular piece of work.  (Note: the Service Crew feature in FSL does not meet the needs of the business).

Now, I have played with Process Builder to action this, but I get unusual results when the auto create feature is enabled.  (And yes, we do need the auto create feature for other business processes).
In process builder I can populate the address for the Work Order from the Case, and then address to Service Appointment from Work Order.  I can get the multiple service appointments by using the recursive feature of the Process Builder. 
However, if I set the WorkType to a type with Auto Create, I get extra Service Appointments and/or Service Appointments without addresses.

So, the question is, in the execution process of events, (i.e. before trigger, after triggers, process builder...etc), where does the Auto Create feature kick in ?  It is obviously part of the managed package and can't be viewed by us mere mortals, but it is happening, but when/where?
And a slight aside, when does the standard field Service Appointment Count (in Work Order) populate in that series of events?  As understanding that may also provide an option for a solution.

Part of the reason for asking is that I am looking to take this to a trigger, but I'm thinking i may run into the same issues there.

Regards
Andrew
Potentially silly question.

We have purchased Community Licenses and intend to have/offer our customers to use the Salesforce App to access our community page. (As well as being browser based).
With Community License there is an API limit.
The question would be "Does the Salesforce App interactions count against the API limits for the Community License?"

LIttle background - our company was considering constructing a custom App using RESTful API to interacts, and these I know would count.  Just curious if the Salesforce App operated in the same manner.

Regards
Andrew
Hello

Having an issue implementing some code which is to create a PDF document from a trigger.  I have used this as a reference/start point :
https://jungleeforce.wordpress.com/2014/06/11/generate-a-pdf-and-attach-it-to-record-from-a-trigger-in-salesforce-restful/comment-page-1/
The code:
public with sharing class SvcApptTriggerController {
	@Future(callout=true)
	public static void addPDFAttach(string sessionId, list<id> svcApptIdList){
		System.debug('@@@@@ in addPDFAttach of SvcApptTriggerController');

		HttpRequest req = new HttpRequest();
		req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/apexrest/AddPDFtoSvcAppt/');
		req.setMethod('POST');
		req.setBody('{"svcApptIdList":'+JSON.serialize(svcApptIdList)+'}');
		req.setHeader('Authorization', 'Bearer '+ sessionId);
		req.setHeader('Content-Type', 'application/json');
		Http http = new Http();
		System.debug('@@@@@ before TEST if');
		if(!test.isRunningTest()){
			System.debug('@@@@@ in TEST if');
			HTTPResponse res = http.send(req);
		}
	}
}
The debug log snippet:
Error message from debug log - Unauthorised
Screenshot of remote Site settings:
Remote Site Settings

So the endpoint reported in the debug logs is in the remote site settings.
The PDF creation code works from the workbench - which obviously uses a different authentication model (name/password).

Feeling that I have missed something obvious.

Regards
Andrew
 
Hello
I am doing an inline table as a lightning component, but after the save event the button will not disappear.
I have found a post that mentions clearing the default values,
component.find("SADataTable").set("v.draftValues", null);
but playing with that line will cause the button to hide, but the table data does not reload after save.
I have also played with firing a refreshview, but no luck either
$A.get('e.force:refreshView').fire();
My component
<aura:component controller="ServiceAppointmentListController" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="WorkOrder" type="WorkOrder" />
    <aura:attribute name="ServiceAppointments" type="ServiceAppointment" />
	<aura:attribute name="Columns" type="List" />
    <aura:attribute name="saveDraftValues" type="Object" />
    <aura:handler name="init" value="{!this}" action="{!c.myAction}" />
    <force:recordData aura:id="workOrderRecord" recordId="{!v.recordId}" targetFields="{!v.WorkOrder}" layoutType="FULL" />
    <lightning:card title="{! 'Service Appointment List for ' + v.WorkOrder.WorkOrderNumber}">
        <!-- Service Appointment list goes here -->
        <lightning:datatable 
                aura:id="SADataTable"
                keyField="Id" 
        		data="{! v.ServiceAppointments }" 
                columns="{! v.Columns }" 
                onsave="{!c.handleSave}" />
    </lightning:card> 
</aura:component>
The JS controller
({
	myAction : function(component, event, helper) {
        component.set("v.Columns", [
            {label:"Appt Id", fieldName:"AppointmentNumber", type:"text"},
            {label:"Duration", fieldName:"Duration", type:"number", editable : 'true'},
            {label:"Duration Type", fieldName:"DurationType", type:"text", editable : 'true'}
        ]);
		var action = component.get("c.getServiceAppointments");
        action.setParams({
            recordId: component.get("v.recordId")
        });
        action.setCallback(this, function(data) {
            component.set("v.ServiceAppointments", data.getReturnValue());
        });
        $A.enqueueAction(action);
	},
    handleSave: function (component, event, helper ) {
		helper.saveDataTable(component, event, helper);
    }
})
The helper manages the save and posts toast messages.
({
    saveDataTable : function(component, event, helper) {
        var editedRecords =  component.find("SADataTable").get("v.draftValues");
        var totalRecordEdited = editedRecords.length;
        var action = component.get("c.updateServiceAppointments");
        action.setParams({
            'editedSAList' : editedRecords
        });
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                //***if update is successful ***
                if(response.getReturnValue() === true){
                    helper.showToast({
                        "title": "Record Update",
                        "type": "success",
                        "message": totalRecordEdited+" Service Appointment Records Updated"
                    });
                    helper.reloadDataTable();
                } else{ //***if update failed ***
                    helper.showToast({
                        "title": "Error!!",
                        "type": "error",
                        "message": "Error in update"
                    });
                }
            }
        });
        $A.enqueueAction(action);
    },

    //*** Show toast with provided params ***
    showToast : function(params){
        var toastEvent = $A.get("e.force:showToast");
        if(toastEvent){
            toastEvent.setParams(params);
            toastEvent.fire();
        } else{
            alert(params.message);
        }
    },
    //*** reload data table ***
    reloadDataTable : function(){
    var refreshEvent = $A.get("e.force:refreshView");
        if(refreshEvent){
            refreshEvent.fire();
        }
    }
})
For completeness, my Server Side controller
public class ServiceAppointmentListController {
    @AuraEnabled
    public static List<ServiceAppointment> getServiceAppointments(Id recordId) {
       return [SELECT Id, AppointmentNumber, Duration, DurationType  FROM ServiceAppointment WHERE ParentRecordId = :recordId];
    }
    
    @AuraEnabled
    public static boolean updateServiceAppointments(List<ServiceAppointment> editedSAList) {
        try {
            update editedSAList;
            return true;
        } catch(Exception e){
            return false;
        }
    }
}

Any assistance appreciated.  I have been troubleshooting this for a day, but seem to be going around in circles.
Regards
Andrew 





 
I am trying to let the following validation rule work:
 
AND(
AND($User.vub_Bypass_Validation_Rules__c = false, $Profile.Name = 'Profile A'),
OR(AND(OR(ISCHANGED(CaseOwner), ISCHANGED(ContactName), ISCHANGED(Status), ISCHANGED(Internal Comments)),
))
Unfortunately the syntax is not correct.
What I want is to prevent users with the Profile A (for example) to change/edit the standard fields Case Owner, Contact Name (lookup), Status and Internal Comments.

You can not set such fields as read only on page layout level. Users with this profile should be able to edit when Cases are of Record Type "Claim", but not cases of type "Only Information". So I see the only way is with a validation rule.

I would appreciate any help.
 
Hi - I am over my head here trying to inactivate this trigger that is no longer working.  It cannot be moved in a change set as we keep getting errors that we have zero code coverage.  We do not have a developer resource at our company.  It was created by a consultant and slowly starting to fail.  One thing I noticed in the Error Messages (we have 17) is that 7 of them state the same/similar thing:
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, To create or update users for this profile, go to Setup > Communities Settings and select Allow using standard external profiles for self-registration and user creation.: [ProfileId]

And then the classes:
Stack Trace: Class.UFeedCommentTest.testFeedCommentCustomerCommunityLoginUser: line 14, column 1
Stack Trace: Class.ContactUserSyncServicesTest.setUpCS: line 26, column 1

Another 6 also have very similar error messages:
System.DmlException: SObjectFactory Create failed. State: {"Count":"1","Template":"Community_User","SObjectType":"User"}, Cause: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, To create or update users for this profile, go to Setup > Communities Settings and select Allow using standard external profiles for self-registration and user creation.: [ProfileId]
Stack Trace: Class.SObjectFactory.create: line 126, column 1 Class.SObjectBuilder.create: line 129, column 1 Class.WebhookResourceTest.setupCommunityUser: line 57, column 1

Is there any chance there is a "simple" fix to all of these since it is the same errors?  Here is the code from the first class getting the error on line 26:
User-added image

Thanks in advance!
Hi and thanks for help in advance.

I need help to get better coverage.  I am at 73%.  There's about 6 lines i need help with.

///These 6 lines in the Apex Class below  arent covered.
                            cs.SendtoTMW__C = false;
                            result= 'There is no valid TMW Surrogate ID for this case';
                            return result;

                        }
                    }else{
                        cs.SendtoTMW__C = false;
                        result= 'There is no valid TMW Surrogate ID for this case';
                        return result; 


Apex Class:

public with sharing class SendtoTMW {
    
    @AuraEnabled  
    public static String getCurCase(Id caseId)
    {
        //Query current user profile id
        String result;
        Case cs =  [select id,SendtoTMW__c,SendtoTMWPerm__c,SFtoTMWSent__c,Origin,AccountId
                    FROM Case WHERE id = :caseId];
        System.debug('#### cs = '+ cs);
        if(cs != null){
            
            if (cs.AccountId == null) {
                cs.SendtoTMW__C = false;
                result= 'Order cannot be submitted to TMW.  Please enter an Account on the Case.';
                return result;
            } else{
                // Check if TMW surrogate ID exists in translation table
                //Id surrogateIds = '';
                //var surrogateIds = sforce.connection.query("SELECT Surrogate_ID__c FROM Translation_Table__c where IntegratedSite__c = '{!Case.AccountId}'"); //Commented this line out because it if user did not have rights to TT then would fail. This next line runs for all.
                List<Translation_Table__c> listTranslationTable = TMWSendOrderService.GetSurrogates(cs.AccountId);
                // I need to pass the case id here.  I'm getting a null return value.  This is what passes it to TMWSendOrderService and sends to TMW 
               // csid = TMWSendOrderService.SendOrderToTmw(cs.Id);
                System.debug('#### list trans table = '+ listTranslationTable);
                if(!listTranslationTable.isEmpty()){
                    if(null !=  listTranslationTable[0].Surrogate_ID__c){
                        String surrogateId = listTranslationTable[0].Surrogate_ID__c;
                        if(surrogateId.substring(0, 3) != 'TMW'){
///These 6 lines arent covered.
                            cs.SendtoTMW__C = false;
                            result= 'There is no valid TMW Surrogate ID for this case';
                            return result;

                        }
                    }else{
                        cs.SendtoTMW__C = false;
                        result= 'There is no valid TMW Surrogate ID for this case';
                        return result; 

                    }
                    
                }else{
                    cs.SendtoTMW__C = false;
                    result = 'There is no valid TMW Surrogate ID for this case';
                    return result;
                }
                if ((cs.Origin == 'TMWUI To Case' || cs.Origin == 'TMWFIX To Case' || cs.Origin == 'TMWFRCST To Case' || cs.Origin == 'TMWCarrierHUB To Case')) {
                    result= 'Order already submitted to or received from TMW. All updates are managed in TMW interface';
                    return result;
                }
                
                if ((cs.Origin != 'TMWUI To Case')) {
                    if (cs.Origin != 'TMWFIX To Case') {
                        if (cs.Origin != 'TMWFRCST To Case') {
                            if (cs.Origin != 'TMWCarrierHUB To Case') {
                                if (cs.SendtoTMW__C == true) {
                                    cs.SendtoTMW__C = false;
                                    result = 'Order already submitted to or received from TMW. All updates are managed in TMW interface.';
                                    return result;
                                }
                            }
                        }
                    }
                }
                Profile pr =  [Select Id, Name from Profile Where Id =: UserInfo.getProfileId() LIMIT 1]; 
                if(pr.Name == 'Transportation Mgmt'|| pr.Name == 'Transportation Team' || pr.Name == 'System Administrator')
                {
                    
                   System.debug('#### profile name = '+ pr);
                   System.debug('### test is running' + cs.SendtoTMW__C);
                    
                    if(Test.isRunningTest()){
                        System.debug('### test is running ' + cs.SendtoTMW__C);
                        cs.SendtoTMW__C = true;
                    }
                    
                    if (cs.SendtoTMW__C == false) {
                        
                        try
                        {
                            result =TMWSendOrderService.SendToTmw(cs.Id);
                           // System.debug('### send to tmw ' + cs.SendtoTMW__C);
                            return result;
                            
                            
                        }
                        catch(Exception ex)
                        {
                            result = ex.getMessage();
                           // System.debug('### send to tmw catch ' + cs.SendtoTMW__C);
                            return result;                            
                        }
                    }
                }                
            }           
        }else{            
        }        
        return null;
    }    
}

Test Class

@isTest
private class SendtoTMWTest 
{    
    // create test case
    @testSetup
    static void setupTestData(){
        test.startTest();
        Account ac=new Account(name='Test Account');
        Insert ac;
        Translation_Table__c translation_table_Obj = new Translation_Table__c(Integration_Status__c = false, IntegratedSite__c= ac.id, 
                                                                              Surrogate_ID__c='TMW-Test123');
        Insert translation_table_Obj; 
        test.stopTest();
    }
    
    //create Account and TT entry 
    @isTest
    static void getCurCase(){
        Account ac=new Account(name='Test Account');
        Insert ac;
        List<Translation_Table__c> translation_table_Obj  =  [SELECT Integration_Status__c, Name from Translation_Table__c];
        System.assertEquals(true,translation_table_Obj.size()>0);
        TMWSendOrderService obj01 = new TMWSendOrderService();
        TMWSendOrderService.OrderResponse obj11 = new TMWSendOrderService.OrderResponse();
        TMWSendOrderService.FuelOrdered obj21 = new TMWSendOrderService.FuelOrdered();
        TMWSendOrderService.TmwOrder obj31 = new TMWSendOrderService.TmwOrder();
        
        
        Case caseObj = new Case(accountId = ac.id, status='Open', 
                                Fuel_Order_Status__c = 'Pending',  
                                Origin = 'Phone',
                                RQ_Delivery_Date__c=system.Today(), 
                                RQ_Delivery_Timeframe__c='9am-3pm',
                                Description='testing fuel order');
        // Add all required field here
        insert  caseObj;
        SendtoTMW.getCurCase(caseObj.id);
        caseObj.AccountId = null;
        update caseObj;
        SendtoTMW.getCurCase(caseObj.id);
        
        caseObj.AccountId = ac.id;
        update caseObj;
        for(Translation_Table__c trans: translation_table_Obj){
            trans.IntegratedSite__c = ac.Id;
        }
        update  translation_table_Obj;
        SendtoTMW.getCurCase(caseObj.id);
       
        
        caseObj.SendtoTMW__c = true;
        update CaseObj;
        SendtoTMW.getCurCase(caseObj.id);
        
        caseObj.Origin ='TMWUI To Case';
        update caseObj;
        SendtoTMW.getCurCase(caseObj.id);
        
        caseObj.SendtoTMW__c = true;
        update CaseObj;
        SendtoTMW.getCurCase(caseObj.id);
        
         
        for(Translation_Table__c trans: translation_table_Obj){
            trans.IntegratedSite__c = ac.Id;
            trans.Surrogate_ID__c = null;
        }
        update  translation_table_Obj;
        SendtoTMW.getCurCase(caseObj.id);
        
        TMWSendOrderService obj = new TMWSendOrderService();
        TMWSendOrderService.SendToTmw(caseObj.id);
        
        Case cs =  [select id,SendtoTMW__c,SendtoTMWPerm__c,SFtoTMWSent__c,Origin,AccountId
                    FROM Case WHERE id = :caseObj.id];
        
        if(cs != null)
        {
            if (cs.AccountId == null)
            {
                cs.SendtoTMW__C = false;
                //result= 'Order cannot be submitted to TMW.  Please enter an Account on the Case.';
            }    
        }   // end if(cs != null)
    } //end static testMethod void getCurCase()
    
    @isTest
    static void getCurCase1(){
        Account ac=new Account(name='Test Account');
        Insert ac;
        List<Translation_Table__c> translation_table_Obj  =  [SELECT Integration_Status__c, Name from Translation_Table__c];
        System.assertEquals(true,translation_table_Obj.size()>0);
        
        
        Case caseObj = new Case(accountId = ac.id, status='Open', 
                                Fuel_Order_Status__c = 'Pending',  
                                Origin = 'Phone',
                                RQ_Delivery_Date__c=system.Today(), 
                                RQ_Delivery_Timeframe__c='9am-3pm',
                                Description='testing fuel order');
        // Add all required field here
        insert  caseObj;
        for(Translation_Table__c trans: translation_table_Obj){
            trans.IntegratedSite__c = ac.Id;
        }
        update  translation_table_Obj;
                SendtoTMW.getCurCase(caseObj.id);

        caseObj.SendtoTMW__c = true;
        update CaseObj;
        SendtoTMW.getCurCase(caseObj.id);                
    } //end static testMethod void getCurCase()       
}
 
Hello All, 

I am getting error in test class is ''List index out of bound 0" . And I getting 36% code coverage in my test class. Please help me both are class are there 

apex class.
public class CaseMergeApexClass {
    Public String textEnter {get;set;}
    public List<sObjectWrapper> wrappers {get;set;} 
    public List<case> lstcas {get;set;}
    public String selectMasterCase {get;set;}
    public boolean addOnChkbx {get;set;}  
    public boolean isSelected{get;set;}
    public boolean flagmerged;
    Public String caseId {get;set;} 
    public List<case>mappsub {get;set;}
    public CaseMergeApexClass(ApexPages.StandardController stdController) {
       caseId = apexpages.currentpage().getparameters().get('id');  
       lstcas = new List<case>();
      wrappers=new List<sObjectWrapper>();
        
        flagmerged =true;
        mappsub =new List<case>();
        for(case cs:[select id,Account.name,Contact.name,RecordType.name,owner.name,subject from case where id=:caseId limit 1])
        {
          mappsub.add(cs);
        }
    }
    public void mergeCase()
    {
       
      list<Case>lstgetcas=[select zGloblal_Total_attachments__c, RecordType.name,CaseNumber,id,subject,account.name,contact.name from case where RecordType.name=:mappsub.get(0).RecordType.name and Contact.name=:mappsub.get(0).Contact.name and Subject like :'%'+mappsub.get(0).subject+'%' and status!='Closed Duplicate' ];
        
          
        for(case cs:lstgetcas)
        {
           
            if(flagmerged){
          wrappers.add(new sObjectWrapper(cs,addOnChkbx));
         }
        
    }
        
    
    
        flagmerged=false;
    } 
    public void selectForMaster()
    {
        lstcas.clear();
         for(sObjectWrapper wrap : wrappers){  
       /*Check if record is selected*/  
       if(wrap.isSelected==true){
         
           
         lstcas.add(wrap.cas);  
        
    }
    }  
    }
    
    public void mergedTicket()
    {
        list<case> updcase=new List<case>();
        list<caseComment> NewCaseCommet=new List<caseComment>();
        list<caseComment> lstComment= [select id ,commentbody,parentid from casecomment where parentId in:lstcas];
        for(casecomment cmt:lstComment)
        {
           caseComment newcmt=new casecomment();
           newcmt.ParentId=caseId; 
           newcmt.CommentBody=cmt.CommentBody; 
           NewCaseCommet.add(newcmt);
        }
       insert NewCaseCommet;
         List<attachment> newAttachment =new list<attachment>();
   List<attachment> lstAttachments=[select id,Body,Name,ParentId from attachment where parentId in:lstcas];
        for(attachment att:lstAttachments)
        {
            attachment newattch=new attachment();
            newattch.parentId=caseId;
            newattch.Body=att.body;
            newattch.name=att.name;
            newAttachment.add(newattch);
        }
       insert newAttachment; 
    closedDuplicate();
      urlre();   
    }
    
    public void closedDuplicate()
    {
        List<case> closedcase =new List<case>();
        for(case cs:lstcas)
        {
            cs.Status='Closed Duplicate';
            closedcase.add(cs);
        }
       update closedcase; 
        
    }
    
    public pagereference urlre()
{
caseId = apexpages.currentpage().getparameters().get('id');
pagereference pg =new pagereference('/'+caseId);

return pg;   
}

    public class sObjectWrapper
  {
    public boolean isSelected{get;set;}  
    public case cas{get;set;} 
        
    public sObjectWrapper(case cas,Boolean isSelected){  
    this.cas = cas;      
    this.isSelected = isSelected;  
     }  
    }
}

and my test class is
@isTest
public class CaseMergeApexClassTest {
    
      static testMethod void testMerge(){        
       
        Account testAccount = new Account(Name='Test Company Name123');
        insert testAccount;
       
         Contact con  = new Contact(LastName='Testcont' ,Email='sss@test.com', AccountId=testAccount.id);
        insert con;
          list<case>lstcase =new LIst<case>();
             Case caseObj1 = new Case();
            caseObj1.AccountId = testAccount.Id;
            caseObj1.contactId=con.id;
            caseObj1.Status = 'Action-Automated Escalation';
            caseObj1.Origin ='Email';
          lstcase.add(caseObj1);
          
           Case caseObj2 = new Case();
            caseObj2.AccountId = testAccount.Id;
            caseObj2.contactId=con.id;
            caseObj2.Status = 'Closed Duplicate';
            caseObj2.Origin ='Email';
          lstcase.add(caseObj2);
       test.startTest(); 
        insert lstcase;

        
            string casId=lstcase[0].id;
        
        ApexPages.StandardController sc = new ApexPages.StandardController(lstcase[0]);
       
        CaseMergeApexClass testCon = new CaseMergeApexClass(sc);
        
          testCon.CaseId = lstcase[0].id ;
   
        PageReference pageRef = Page.CaseMergePage;
        pageRef.getParameters().put('id', String.valueOf(lstcase[0].id));
        Test.setCurrentPage(pageRef);
          testCon.addOnChkbx=true;
          testCon.closedDuplicate();
          testCon.textEnter='899898';
          testCon.selectMasterCase='89898';
         testCon.flagmerged=true;
         testCon.isSelected=true;
          
          testCon.urlre();
          testCon.mergeCase();          
          testCon.selectForMaster();
          testCon.mergedTicket();

      test.stopTest();
    }
}

​​​​​​​
Hello,

I've been struggling with creating a test class for a custom controller with if statements for a Visualforce page. I have no idea what I'm doing wrong and have looked all over these forums and google for an answer with no luck. If someone could give this a shot and let me know what I am doing wrong that would be amazing.

Here is my controller:
public class SuspectListController {
	public final Account act;
    public SuspectListController(ApexPages.StandardController stdController) {
        this.act = (Account)stdController.getRecord();
    }

    public Id AccountId = ApexPages.currentPage().getParameters().get('id');

    public List<HealthCloudGA__EhrEncounter__c> EHRRecords = [SELECT Name, CreatedDate, HealthCloudGA__HospitalizeDischargeDiagnosis__c
                                                       FROM HealthCloudGA__EhrEncounter__c WHERE HealthCloudGA__Account__c = :AccountId AND CreatedDate = LAST_N_DAYS:365 ORDER BY CreatedDate desc];

    public List<String> RType = new List<String>();
    public List<String> Name = new List<String>();
    public List<String> CDate = new List<String>();
    public List<String> Code = new List<String>();
    public List<String> Description = new List<String>();

    public List<String> getType() {
        for (HealthCloudGA__EhrEncounter__c encounter : EHRRecords) {
             if (!Description.contains(encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c) && encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c != null) {
                RType.add('EHR Encounter');
                Name.add(encounter.Name);
                Cdate.add(encounter.CreatedDate.format('MM/dd/yyyy'));
                Code.add('');
                Description.add(encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c);
            }
        }    
        
        return RType;
    }

    public List<String> getName() {
        return Name;
    }
    
    public List<String> getCDate() {
        return CDate;
    }
    
    public List<String> getCode() {
        return Code;
    }
    
    public List<String> getDescription() {
        return Description;
    }
This controller was created to add field values to a list if they are not on the list already and pass that list to an html table on a Visualforce page (Adding to every list in the first function is a bit funky but it saves from looping through each record in each function). My test class currently passes everything except for the if statement and its contents.

Here is my current test class:
@isTest
private class SuspectListTestClass {
    @testSetup static void testSetup() {
        Account testaccount = new Account();
        testaccount.name = 'Zander Test';
        testaccount.Primary_Insurance__c = 'Test Insurance Company';
        testaccount.Gender__c = 'Male';
        testaccount.County__c = 'Maricopa';
        testaccount.RecordTypeId = '012360000004FEPAA2';
        insert testaccount;
    }

    @isTest static void testEHREncounterPass() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        HealthCloudGA__EhrEncounter__c testencounter1 = new HealthCloudGA__EhrEncounter__c();
        testencounter1.HealthCloudGA__Account__c = act.Id;
        testencounter1.HealthCloudGA__HospitalizeDischargeDiagnosis__c = 'Test';
        insert testencounter1;
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.Description.add('');
        String[] record = testcontroller.getType();
        System.assertEquals('EHR Encounter',record[0]);
    }
    
    @isTest static void testEHREncounterFail() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        HealthCloudGA__EhrEncounter__c testencounter2 = new HealthCloudGA__EhrEncounter__c();
        testencounter2.HealthCloudGA__Account__c = act.Id;
        testencounter2.HealthCloudGA__HospitalizeDischargeDiagnosis__c = 'Test';
        insert testencounter2;
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.Description.add('Test');
        testcontroller.getType();
    }

    @isTest static void testSuspectListController() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.getName();
        testcontroller.getCDate();
        testcontroller.getCode();
        testcontroller.getDescription();
    }
}
From what I understand you need to have one test where it is meant to pass and one where it is meant to fail. I have made 2 test methods but no matter what I do I can not seem to get one to pass. I get an error from the assertEquals() saying that the index is out of range meaning it did not add "EHR Encounter" to the RType list.

Am I missing something here??
I feel like I have inserted a record that should pass but I guess not.
Please help!

Thanks in advance!

 
Hi Experts,

Request you to provide some solution for me.

public class Test_insert {
    public map<String,Integer> EmpMap = new map<String, Integer>();
    public Test_insert(Integer preVetReviews,Integer preVetReviews_Tue,Integer preVetReviews_Wed,Integer preVetReviews_Thur,Integer preVetReviews_Fri)
    {
        Test__c acc= new Test__c();
        EmpMap.put('Monday',preVetReviews);
        EmpMap.put('Tuesday',preVetReviews_Tue);
        EmpMap.put('Wedneday',preVetReviews_Wed);
        EmpMap.put('Thursday',preVetReviews_Thur);
        EmpMap.put('Friday',preVetReviews_Fri);
        set<String> allKeys = EmpMap.keySet();
        list<Integer> allValues = EmpMap.Values();
        for(String k : EmpMap.keySet())
        {
           acc.Name = 'Test';
           acc.PrevetReview__c = EmpMap.get(k);
           System.debug('The Key is: ' +k+ ' and the value is: ' +EmpMap.get(k));
           insert acc;
        }
    }

}

Above is my code and I call it using

Test_insert a = new Test_insert(2,3,4,5,6);

Obseved output:
Record is inserted only once into my object for feild PrevetReview__c

Expected output:
I need record to be inserted five time for feild PrevetReview__c

Please help
Dear Gurus,

This is about a Apex DML exception which is troubling
23:43:49:014 EXCEPTION_THROWN [49]|System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Level 1, Case]: [Level 1, Case]

Here is apex code-->
public class PickListHandler {
    @AuraEnabled
    public static List<String> getLevel1(){
    List<String> tempLst1 = new List<String>();
        for(AggregateResult  ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c  group by Level_1__c])
    {
        tempLst1.add(''+ar.get('Level_1__c'));
    }

    return tempLst1;
      
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel2(string strName){
    List<String> tempLst2 = new List<String>();
       for(AggregateResult  ar : [select Level_2__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName  group by Level_2__c])
    {
       tempLst2.add(''+ar.get('Level_2__c'));
    }

    return tempLst2;
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel3(string strName1,string strName2){
     List<String> tempLst3 = new List<String>();
      for(AggregateResult  ar : [select Level_3__c,COUNT(id) from Case_Type_Data__c  where Level_1__c=:strName1 and Level_2__c=:strName2 group by Level_3__c])
    {
       tempLst3.add(''+ar.get('Level_3__c'));
    }

    return tempLst3;
      
      
    } 
         
     @AuraEnabled
     public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }
     
    catch(Exception ex){
            strMsg='error';
        }
     return strMsg;  
}
    
     
    
    

}

Hereis working Test class for above apex-->
@isTest
public class testGetAllLevels { 

static testMethod void testGetLevel1()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel1();

}
    
static testMethod void testGetLevel2()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel2('Test Level 1');

}
    
static testMethod void testGetLevel3()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
    List<String> s = PickListHandler.getLevel3('Test Level 1','Test Level 2');

}
    
    
static testMethod void testsaveCaseType(){
        // Create the Case Record.
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
        insert cas;
       
        ERT_Case_Type__c obj=new ERT_Case_Type__c();
        string one='one';
        string two='two';
        string three='three';
        test.startTest();
        String testing=PickListHandler.savecasetype(one,two,three,cas.id);
        test.stopTest();
    }
    

    
 
    
}

Here is lightning component JS -->
({
    doInit : function(component, event, helper) {
        var action = component.get("c.getLevel1");
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                component.set("v.lstLevel1",result);
            }
        });
        $A.enqueueAction(action);
    },    
    getLvl1:function(component, event, helper){
       
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var action = component.get("c.getLevel2");
        //alert('called'+picklistvalue);
        action.setParams({  'strName' : picklistvalue  });//
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                component.set("v.lstLevel2",result);
            }
        });
        $A.enqueueAction(action);
        //  alert(picklistvalue);
    },
    getSelectedValue:function(component, event, helper){
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var picklistdep=component.find('ddLevel2');
        var picklistvaluedep2=picklistdep.get('v.value');
        var action = component.get("c.getLevel3");
       // alert(picklistvaluedep2+' called'+picklistvalue);
        action.setParams({  'strName1' : picklistvalue,
                         'strName2' : picklistvaluedep2});//
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                component.set("v.lstL3",result);
            }
        });
        $A.enqueueAction(action);
       // alert(picklistvalue+'  '+picklistvaluedep);
    },
    onConfirm:function(component, event, helper){
        var picklist=component.find('ddLevel1');
        var picklistvalue=picklist.get('v.value');
        var picklistdep=component.find('ddLevel2');
        var picklistvaluedep2=picklistdep.get('v.value');
       
        var picklistdep3=component.find('ddLevel3');
        var picklistvaluedep3=picklistdep3.get('v.value');
        var action = component.get("c.savecasetype");
        
        action.setParams({  'strName1' : picklistvalue,
                          'strName2' : picklistvaluedep2,
                          'strName3' : picklistvaluedep3,
                          'id' : component.get("v.recordId")});//
                          
        
        var toastEvent = $A.get("e.force:showToast");
       //alert('abcd');
        action.setCallback(this, function(e) {
            if(e.getState()=='SUCCESS'){
                var result=e.getReturnValue();
                // alert(result);
                if(result==='successfull'){
                    toastEvent.setParams({
                        "title": "Success!",
                        "message": "The record has been inserted  successfully."
                    });
                    toastEvent.fire();
                }else{
                    toastEvent.setParams({
                        "title": "Error",
                        "message": "The record has not been inserted  successfully."
                    });
                    toastEvent.fire();
                }
            }
        });
        $A.enqueueAction(action);
       
    }
})

Here is Apex handler -->
<aura:component controller="PickListHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <!-- Actions-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <!-- variable-->
    <aura:attribute name="lstLevel1" type="String[]" />
     <aura:attribute name="lstLevel2" type="String[]" />
      <aura:attribute name="lstL3" type="String[]" />
    <span> Level 1</span>
    <ui:inputSelect aura:id="ddLevel1" change="{!c.getLvl1}">
        <ui:inputSelectOption label="-Select-" value="true"/>        
        <aura:iteration items="{!v.lstLevel1}" var="value">          
            <ui:inputSelectOption label="{!value}" text="{!value}" />
        </aura:iteration>
    </ui:inputSelect>
    <span>Level 2</span>
    <ui:inputSelect aura:id="ddLevel2" change="{!c.getSelectedValue}">
        <ui:inputSelectOption label="-Select-" value="true"/>        
        <aura:iteration items="{!v.lstLevel2}" var="value">          
            <ui:inputSelectOption label="{!value}" text="{!value}" />
        </aura:iteration>
    </ui:inputSelect>
     <span>Level 3</span>
    <ui:inputSelect aura:id="ddLevel3" >
        <ui:inputSelectOption label="-Select-" value="true"/>        
        <aura:iteration items="{!v.lstL3}" var="value">          
            <ui:inputSelectOption label="{!value}" text="{!value}" />
        </aura:iteration>
    </ui:inputSelect>
    <lightning:button variant="brand" label="Save" onclick="{!c.onConfirm}" />
</aura:component>
Now when i run test class basically create a case and pass the id to apex class,i see no issues but issue comes only when i click 'Save',i see ""The record has not been inserted successfully."" On checking Logs i found DML exception as below
23:43:49:014 EXCEPTION_THROWN [49]|System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Level 1, Case]: [Level 1, Case]

Please note in this scenarion Each case can have multiple ERT_Case_Type__c and each ERT_Case_Type__c can have multiple Case_Type_Data__c

Please help in finding  resolution.

Thanks in Advance
Carolyn
 
Hi All, I picked up trigger 1 from trailhead (believing effeciently written ) where Map is used at point in the trigger but I was able to achieve what trigger 1 is doing by using list in trigger 2 (written by me) now what I wonder is I don't see any necessity of using Map in trigger 1.

I am curious to know if both the triggers are effeciently written or only one of them, if so why ?

Trigger - 1
 
trigger AddRelatedRecord1 on Account(after insert) {

    List<Opportunity> oppsToInsrt = new List<Opportunity>();
    // Get the related opportunities for the accounts in this trigger

    Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
        [SELECT Id,Name,(SELECT Id,StageName,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
    
    // Add an opportunity for each account if it doesn't already have one.
    // Iterate through each account.
    for(Account a : Trigger.New) {
        System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
        // Check if the account already has a related opportunity.
        if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
        
            // If it doesn't, add a default opportunity
            oppsToInsrt.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       AccountId=a.Id));
        }           
    }
    if (oppsToInsrt.size() > 0) {
        insert oppsToInsrt;
    }
}

Trigger - 2
 
trigger AddRelatedRecord2 on Account(after insert) {
   
    List<Opportunity> oppList = new List<Opportunity>();  
    
    List<Account> acctsWithOpps = new List<Account>(
        [SELECT Id,Name,city__c,(SELECT Id,stageName,closeDate,city__c FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

    for(Account a : acctsWithOpps) {
           
        if (a.Opportunities.size() == 0) {
          
            oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
                                       StageName='Prospecting',
                                       CloseDate=System.today().addMonths(1),
                                       City__c = a.city__c,
                                       AccountId=a.Id));
        }           
    }
    if (oppList.size() > 0) {
        insert oppList;
    }
}

 
i am having 90% code coverage because atch block is not covered,can anyone help in writing code for catch block as well

Apex code -->
public class PickListHandler {
    @AuraEnabled
    public static List<String> getLevel1(){
    List<String> tempLst1 = new List<String>();
        for(AggregateResult  ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c  group by Level_1__c])
    {
        tempLst1.add(''+ar.get('Level_1__c'));
    }

    return tempLst1;
      
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel2(string strName){
    List<String> tempLst2 = new List<String>();
       for(AggregateResult  ar : [select Level_2__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName  group by Level_2__c])
    {
       tempLst2.add(''+ar.get('Level_2__c'));
    }

    return tempLst2;
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel3(string strName1,string strName2){
     List<String> tempLst3 = new List<String>();
      for(AggregateResult  ar : [select Level_3__c,COUNT(id) from Case_Type_Data__c  where Level_1__c=:strName1 and Level_2__c=:strName2 group by Level_3__c])
    {
       tempLst3.add(''+ar.get('Level_3__c'));
    }

    return tempLst3;
      
      
    } 
         
     @AuraEnabled
     Public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }
     
    catch(Exception ex){
            strMsg='error';
        }
     return strMsg;  
}

}

Test class code -->
@isTest
public class testGetAllLevels { 

static testMethod void testGetLevel1()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel1();

}
    
static testMethod void testGetLevel2()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel2('Test Level 1');

}
    
static testMethod void testGetLevel3()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
    List<String> s = PickListHandler.getLevel3('Test Level 1','Test Level 2');

}
    
    
static testMethod void testsaveCaseType(){
        // Create the Case Record.
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
        insert cas;
       
        ERT_Case_Type__c obj=new ERT_Case_Type__c();
        string one='one';
        string two='two';
        string three='three';
        test.startTest();
        String testing=PickListHandler.savecasetype(one,two,three,cas.id);
        test.stopTest();
    }
    
 
    
}

Thanks in advance
Carolyn
when there is a salesforce update, does your apex coding update as well?
Hi All

Is there are any way of updaing quote lines of an opportunity based on opportunity stage update? I can do that using a trigger but i am pretty much like if it can be done through an configuration rather than coding.
Hi,
I am getting this error for this code ,how do i fix it
 
public with sharing class saveCaseType {
     
     @AuraEnabled
     Public  static List<String>  savecasetype(string level1,string level2,string level3,string caseid){
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Id =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     return obj;
     }
    
    
    

}

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
trigger OppPusher on Opportunity (before update) {
Date dNewCloseDate;
Date dOldCloseDate;
Boolean bPushed=false;

for (Opportunity oIterator : Trigger.new) { //Bulk trigger handler so that you can mass update opportunities and this fires for all'
                                            // gets new values for updated rows
    dNewCloseDate = oIterator.CloseDate; // get the new closedate 
    dOldCloseDate = System.Trigger.oldMap.get(oIterator.Id).CloseDate; //get the old closedate for this opportunity
    if (dOldCloseDate<dNewCloseDate) { //if the new date is after the old one, look if the month numbers are different
        if (dOldCloseDate.month()<dNewCloseDate.month()) { // the month number is higher, it's been pushed out
            bPushed=true;
        }
        else {
            if (dOldCloseDate.year()<dNewCloseDate.year()) { // the month wasn't higher, but the year was, pushed!
                bPushed=true;
                }
            }
        
    }
    if (bPushed==true) { // let's go make them sorry
        if (oIterator.PushCount__c==null) {
            oIterator.PushCount__c=1;
        }
        else {
        oIterator.PushCount__c++;           
        }
    }
}
}
hey gurus,

need your help in writing test class code for below apex class
 
public with sharing class SaveRecord_Lightning{
    
	@AuraEnabled
	public static List<ERT_Case_Type> getAllrecords(){
	 
	 return [SELECT Id,Case__c,Level1__c,Level2__c,Level3__c from ERT_Case_Type];
	 }
	 
	 @AuraEnabled
	 public static ERT_Case_Type saveRecord(ERT_Case_Type recordDetail){
	   upsert recordDetail;
	   return recordDetail;
	   
	 
	 }
	
	
	}

Your help is highlyappreicated
Carolyn
Trying to update a formula for a royalty calculation field, we've added a new option this field needs to account for. 

1. Business Unit
2. Cover Type

I'm new to formuals and think (maybe) I setup a basic shell correctly. But it's giving me a syntex error - so now I'm hoping the experts here can help.

Here's what I did...

IF(
   AND(
       Business_Unit__c = '1',
       ISPICKVAL( Cover_Type__c ,'Hardcover'),(0/100),IF(ISPICKVAL( Cover_Type__c ,'Paperback'),(0/100)
       )

IF(
   AND(
       Business_Unit__c = '2',
       ISPICKVAL( Cover_Type__c ,'Hardcover'),(0/100),IF(ISPICKVAL( Cover_Type__c ,'Paperback'),(0/100)
       )

NULL))))

Thanks in advance for your help!!! 
Hello, Please me on this requirement.

Count Account with Different Industry(on account picklist fields is there)(e,g. For Industry Electronics we have 3 Accounts) using Map.

plz help me i am new in apex collection.

We are happy to provide a space for you to list developer and admin openings that may be of interest to the Force.com community. Please ensure your posts are effectively titled with the position and location you're looking for, and don't forget to include instructions for applying or getting in touch with you when you post. 

 

If you are a developer looking for work, you are allowed to post that here, however you are not allowed to post the same information repeatedly (spamming). You also may not use this space for advertising your business. 

 

This board is offered as a service to our community and those found to be abusing it will be banned from posting. Examples of abuse include posting blanket generic responses to job listings & starting new topics that only serve to advertise your business.

 

I welcome your feedback and suggestions!