0

I have read the developer guide and not sure what I am doing wrong. I am executing the following code:

public class LTRORequireAdditionalDocumentsCon {


    public LTRO_Document__c ltrodoc {get;set;}
    private String caseId;
    private String contId;
    public String contEmail {get; set;}
    public String contName {get; set;} 
    public String emailBody {get; set;}
    public String emailBodyTxt {get; set;}
    public String SandboxName;
    public String sfdcBaseURL;
    public String daURL;
    public Case LTROdauLink;



    public List<LTRO_Document__c> ltrodoclist {get; set;}

    public LTRORequireAdditionalDocumentsCon(){

        ltrodoc = new LTRO_Document__c();
        ltrodoclist = new List<LTRO_Document__c>();
        caseId = ApexPages.currentPage().getParameters().get('cid');
        contEmail = ApexPages.currentPage().getParameters().get('conemail');
        contName = ApexPages.currentPage().getParameters().get('conname');
        contId = ApexPages.currentPage().getParameters().get('conid');

    }

    // get the picklist values from Salesforce
    public List<SelectOption> getLtroDocTypes(){

        List<SelectOption> options = new List<SelectOption>();

        Schema.DescribeFieldResult fieldResult = LTRO_Document__c.Type__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();

        for( Schema.PicklistEntry f : ple){
            options.add(new SelectOption(f.getLabel(), f.getValue()));
        }  

        return options;
    }


    //add documents to the table
    public void addDocs(){
        if(ltrodoc.Summary__c !=''){
            LTRO_Document__c tmp = new LTRO_Document__c();
            tmp = ltrodoc.clone();
            ltrodoclist.add(tmp);

            System.debug('temp :' + tmp);

        }

        else{
            System.debug('No Documents have been assigned');
        }


        System.debug('Documents Type: ' +ltrodoclist);

    }

    //method that will display the page before it is send
    public PageReference previewEmail(){

      Disaster_LTRO_Damage_Assessment_URL__c DamageAssessmentURL = Disaster_LTRO_Damage_Assessment_URL__c.getValues('Damange Assessment');
      //system.debug('Custom Settings :' + DamageAssessmentURL);
      //System.debug('Info :' + DamageAssessmentURL.Damage_Assessment_URL__c);
      daURL = DamageAssessmentURL.Damage_Assessment_URL__c;
      System.debug('daURL :' + daURL);


        //identify the Name of the org, and the server name
        Organization org = [select id,IsSandbox from Organization];
        if (org.IsSandbox == true){
            if(UserInfo.getUserName().contains('.pi.')){
                SandboxName = UserInfo.getUserName().substringAfterLast('.pi.') + '-';
                sfdcBaseURL = System.URL.getSalesforceBaseURL().getHost().substringAfter('c.').substringBefore('.visual.force.com') + '.';
            }else {
                SandboxName = UserInfo.getUserName().substringAfterLast('.') + '-';
                sfdcBaseURL = System.URL.getSalesforceBaseURL().getHost().substringAfter('c.').substringBefore('.visual.force.com') + '.';
            }
        } else {
            sfdcBaseURL = 'secure.';
            SandboxName = '';

        }
        System.debug('SandboxName1 :' +SandboxName);
        System.debug('sfdcBaseURL1:' +sfdcBaseURL);

        //loop through the list and build a list string with all of the Documents and Notes
        String docsString = '';
        String docsStringText = '';

        //list of documents that will be inserted
        List<LTRO_Document__c> insertltrodocs = new List<LTRO_Document__c>();

        String[] strList = new String[0];
        for(LTRO_Document__c docs: ltrodoclist){

            //get all of the documents and add them to the insertltrodocs  
            docs.Case__c = caseId;
            insertltrodocs.add(docs);

            //building the string of documents
            strList.add(String.valueOf(docs));
            docsString += 'Document : '+ docs.type__c + '\n <br/> '+ ' Notes : ' + docs.Summary__c + '\n <br/> \n <br/>' ;
            docsStringText += 'Document : '+ docs.type__c + '\n'+ 'Notes : ' + docs.Summary__c + '\n  \n ' ;
        }

        // insert the ltro documents
        insert insertltrodocs;

        System.debug('docsString : ' + docsString);

        //build the email template
        emailBody = 'Hello '+contName+ ',\n  <br/><br/> We have identified that additional documents are required :\n  <br/><br/>' 
            + docsString +' \n <br/> Please navigate to the link below and re-upload the required file with the corrections. \n' ; //<br/></b>

        emailBodyTxt = ' Hello '+contName+ ',\nWe have identified that additional documents are required :\n \n' 
            + docsStringText +' \n  Please navigate to the link below and re-upload the required file with the corrections. \n' ;

        System.debug('emailBody : ' + emailBody);

        return Page.LTRORequireAddDocEmailReview;

    }

    //method that send the email to the client. 
    public PageReference sendClientEmail(){

        //Create a Task placeholder
        Task ltroEmailTask = new Task();
        //ltroEmailTask.Description = taskcomments;
        ltroEmailTask.Type = 'Email';
        ltroEmailTask.TaskSubtype = 'Email';
        ltroEmailTask.status = 'Not Started';
        ltroEmailTask.WhatId = caseid;
        ltroEmailTask.WhoId = contId;
        ltroEmailTask.Priority = 'Normal';
        ltroEmailTask.Subject = 'Temporary Task for LTRORequireAdditionalDocumentsCon';

        insert ltroEmailTask;

        id taskId= ltroemailTask.id;

        OrgWideEmailAddress[] owea = [Select id from OrgWideEmailAddress where DisplayName = 'Red Cross Disaster Relief'];

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        String[] toAddresses = new String[] {contEmail};
            //String[] ccAddresses = new String[] {'[email protected]'};

            mail.setToAddresses(toAddresses); 

        mail.setReplyTo('[email protected]');

        //mail.setSenderDisplayName('American Red Cross Disaster Services');

        if (owea.size() > 0) {
            mail.setOrgWideEmailAddressId(owea.get(0).id);
        }

        mail.setSubject('American Red Cross Disaster Assessment Application - Additional Documents are Required ');

        mail.setBccSender(false);


        EmailTemplate emailTemplate = [select Id, DeveloperName, HtmlValue, Body, BrandTemplateId From EmailTemplate where DeveloperName = 'LTRO_Additional_Documents_Required'];

        //Specify the text content of the email.
        String plainBody = emailTemplate.Body;
        plainBody = plainBody.replace('LTRORequireAdditionalDocumentsCon.apxc', emailBodyTxt + 
                                      '<a href="'+daURL+'ltrodamageuploadstep?ret=1&cid='+caseid+'&taskid='+taskid+'">Red Cross Disaster Documentation Upload</a>'+
                                      '<a href="https://'+SandboxName+'redcross.'+sfdcBaseURL+'force.com/DisasterAssessment/ltrodamageuploadstep?ret=1&cid='+caseid+'&taskid='+taskid+'">Red Cross Disaster Documentation Upload</a>');

        mail.setPlainTextBody(plainBody);
        // mail.setTemplateId(emailTemplate.id);

        // Specify the content of the HTML email        
        String htmlBody = emailTemplate.HTMLValue;
        htmlBody = htmlBody.replace('LTRORequireAdditionalDocumentsCon.apxc', emailBody + 
                                    '<a href="'+daURL+'ltrodamageuploadstep?ret=1&cid='+caseid+'&taskid='+taskid+'">Red Cross Disaster Documentation Upload</a>'+
                                    '<br><br><a href="https://'+SandboxName+'redcross.'+sfdcBaseURL+'force.com/DisasterAssessment/ltrodamageuploadstep?ret=1&cid='+caseid+'&taskid='+taskid+'">Red Cross Disaster Documentation Upload</a>');
        //!LTRO_Document__c.Type__c   NewEmail
        mail.setHtmlBody(htmlBody);
        //mail.setTemplateId(emailTemplate.id);


        // Send the email you have created.
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


        id suser = [Select id from User where firstname ='Disaster LTRO Damage Assessment' and lastname = 'Site Guest User' Limit 1].id;
        //Update the Case's task        
        ltroEmailTask.Description = plainBody;//plainBody taskcomments
        ltroEmailTask.status = 'Sent';
        ltroEmailTask.Subject = 'American Red Cross Disaster Assessment Application - Additional Documents are Required'; 
        ltroEmailTask.Ownerid = suser;
        update ltroEmailTask;


        return Page.LTROReqAddDocThankYou;

    }

    public PageReference returntocase(){

        Pagereference caPage = new Pagereference('/' + caseId);

        System.debug('caseId :' +caseId);
    return caPage;

    }

        public PageReference returntoContact(){

        Pagereference contPage = new Pagereference('/' + contId);

        System.debug('contId :' +contId);
    return contPage;

    }



}

When I run my test class, I get Null values. If I execute in Execute Anonymous I get the custom setting. If I update my test class with SeeAllData = true, I can see the custom setting. Now, if I execute my apex class and try to get the custom setting, it is still showing as null. I am using List custom setting. What could prevent the code from seeing the Custom Setting?

8
  • So if I understand this correct, you are able to get the values in a test class when seealldata=true and when executed from anonymous window. When you mention this -- [if I execute my apex class] -- how are you executing your apex class?
    – Jayant Das
    Commented Nov 16, 2018 at 16:26
  • I am executing it manually. In this case, my custom setting is populated with an URL. I take the URL and put it into a string. Then I send an email from Apex referencing the string, and it shows null. That is how I know it is not pulling the value from the custom setting.
    – Ivo Dimov
    Commented Nov 16, 2018 at 16:39
  • If I run the exact same code in Anonymous, I am getting the URL from the custom setting.
    – Ivo Dimov
    Commented Nov 16, 2018 at 16:41
  • Still not following - how do you execute it manually, as how are you sending an email from Apex which is trying to get custom setting values? There's no issue in the code itself, so as long as your Apex runs fine, it should be able to pull the values. Is the code here and in your apex exactly the same?
    – Jayant Das
    Commented Nov 16, 2018 at 16:43
  • I am sorry for the confusion, and thank you for willing to look into this. I essentially have a class which purpose is to build an email. In the email, I am also trying to display a link. I am trying to get that link in my apex email template from a custom setting. So essentially, I am trying to access the Custom Setting, so I can take the value and put in into my email template. I am executing my class by clicking on a button that is triggering sending the email. When I get the email it shows null.
    – Ivo Dimov
    Commented Nov 16, 2018 at 16:48

1 Answer 1

1

By default, test classes do not see any data, and that includes "Custom Settings". What you can do, is prepare your test class with some sample values that your test code can then read.

For example, you can add this snippet to your test class

@TestSetup
private static void setup() {
    Disaster_LTRO_Damage_Assessment_URL__c DamageAssessmentURL = new Disaster_LTRO_Damage_Assessment_URL__c();

     //Put all your default values here
     DamageAssessmentURL.xxx =xxx;

     insert DamageAssessmentURL;
}

I would like to add that List Custom Settings are slowly being phased out. It probably makes sense for you to invest a little time and merge all of this to Custom Metadata, which can both be deployed and be available for tests without doing the setup.

5
  • Thank you Sebastian for the feedback. Yes, I do understand the situation with my Test class, but would you happen to know for a reason why Apex class controller may not be able to read a custom setting. In my class I am still getting null for a value.
    – Ivo Dimov
    Commented Nov 16, 2018 at 16:14
  • You're welcome. If this happened to help you, feel free to upvote and mark as accepted so other people looking for the same can benefit. Commented Nov 16, 2018 at 16:14
  • For example I am tying this: Disaster_LTRO_Damage_Assessment_URL__c DamageAssessmentURL = Disaster_LTRO_Damage_Assessment_URL__c.getValues('Damange Assessment'); daURL = DamageAssessmentURL.Damage_Assessment_URL__c; System.debug('daURL :' + daURL); I get null for my string in my class
    – Ivo Dimov
    Commented Nov 16, 2018 at 16:17
  • String DamageAssessmentURL; Disaster_LTRO_Damage_Assessment_URL__c DamageAssessmentURL = Disaster_LTRO_Damage_Assessment_URL__c.getValues('Damange Assessment'); daURL = DamageAssessmentURL.Damage_Assessment_URL__c; System.debug('daURL :' + daURL); In my apex controller I am trying to execute the above, but getting FATAL_ERROR System.NullPointerException: Attempt to de-reference a null object. If I exeute the same code in Apex Anonymus all is working fine.
    – Ivo Dimov
    Commented Nov 16, 2018 at 16:22
  • Ivo, it is not possible for me to understand what you are saying and experiencing by you posting in comments. Can you please update your original post? Please include any code that you have added, including my snippet. Commented Nov 16, 2018 at 16:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .