• Jaye Lowe
  • NEWBIE
  • 50 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 12
    Replies
Hey all, here's the deal. I have a long text area, which is basically a really long url that I need to cut everything after the question mark and then copy into a URL field. Preferrably, in a declarative fashion. Any ideas? 
I have a use case where we have a webform that is inserted leads in salesforce. The first submission from the webform is creating a lead with a name and number. Then the second submission is a survey. Both are creating leads in salesforce. I need some way, preferrably declarative way of matching the two records and then merging them, or copying all the details from record 2 in to record 1 and then deletiing record 2. Any ideas? 
I have a directive to update an email field on the Account Record called Primary Email with the contents of the standard Email field on a related Contact Record Contact when a checkbox, Primary Client Referral, on the same contact record is checked. Not sure what the best...easiest way to accomplish this is. Any thoughts would be supremely helpul and immensely appreciated.  Thanks in advance!
In my sandbox I am seeing that I have 75% code coverage on my class. When I deploy it to production it is 0. Can someone take a look at the class and test class and help me out. I need this deployed asap. Thanks!

/**
 *  About
 *  -----
 *  Create date: 21 Jan 2016
 *  
 *  Details
 *  -----
 *  Controller Extension for ReferOut VF Page
 *  
 *  Update History
 *  -----
 *  
 *  Issues / TODOs
 *  ----- 
 *
**/
public class ReferOutExtension{
    
    public Lead leadRecord {get;set;}
    public String selectedInsuranceType {get;set;}
    public String referOutReason {get;set;}
    public List<SelectOption> insuranceTypes {
        get {
            if (insuranceTypes == null){
                insuranceTypes = new List<SelectOption>();
                insuranceTypes.add (new SelectOption('','--None--'));
                insuranceTypes.add (new SelectOption('PPO','PPO'));
                insuranceTypes.add (new SelectOption('HMO','HMO'));
                insuranceTypes.add (new SelectOption('Medicare','Medicare'));
                insuranceTypes.add (new SelectOption('Medicaid','Medicaid'));
            }
            return insuranceTypes;
        }
        set;
    }
    public Opportunity associatedOpportunity {
        get {
            if (associatedOpportunity == null){
                List<Account> defaultBusinessAccount = [SELECT Id 
                                                            FROM Account
                                                            WHERE Name = 'Unknown'];
                associatedOpportunity = new Opportunity();
                if (defaultBusinessAccount.size() > 0){
                    associatedOpportunity.Business_Account__c= defaultBusinessAccount[0].Id;
                    if (defaultBusinessAccount.size() > 1)
                        associatedOpportunity.Refer_Out_Account__c= defaultBusinessAccount[1].Id;
                }
            }    
            return associatedOpportunity;
        }
        set;
        
    }
    
    public ReferOutExtension(ApexPages.StandardController std){
        List<String> fields = new List<String>();
        fields.add('Caller_No__c');
        fields.add('MobilePhone');
        fields.add('Email');
        fields.add('Street');
        fields.add('City');
        fields.add('State');
        fields.add('PostalCode');
        fields.add('Phone');
        fields.add('Email');
        fields.add('Primary_Policy_Holder_Same_as_client__c');
        fields.add('Client_Alias__c');
        fields.add('DOB__c');
        fields.add('Client_Other_Phone__c');
        fields.add('Age__c');
        fields.add('SSN__c');
        fields.add('Insured_Street_Address__c');
        fields.add('Insured_Name__c');
        fields.add('Insured_First_Name__c');
        fields.add('Insured_Last_Name__c');
        fields.add('Self_Pay_Amount__c');
        fields.add('Insured_City1__c');
        fields.add('Insured_Relation_To_Client__c');
        fields.add('Insured_State__c');
        fields.add('Insured_DOB__c');
        fields.add('Insured_Zip__c');
        fields.add('Insured_SSN__c');
        fields.add('Insurance_Company__c');
        fields.add('Relationship__c');
        fields.add('OTHER_Insurance_Co__c');
        fields.add('X_ID__c');
        fields.add('Group__c');
        fields.add('Insurance_Phone__c');
        fields.add('Detox_Days__c');
        fields.add('Treatment_Days__c');
        fields.add('Substance_of_Abuse_1__c');
        fields.add('Substance_of_Abuse_2__c');
        fields.add('Substance_Details_1__c');
        fields.add('Substance_Details_2__c');
        fields.add('OTHER_Substance_1__c');
        fields.add('OTHER_Substance_2__c');
        fields.add('SA_Amount_1__c');
        fields.add('SA_Amount_2__c');
        fields.add('SA_Route_1__c');
        fields.add('SA_Route_2__c');
        fields.add('SA_Use_Frequency_1__c');
        fields.add('SA_Use_Frequency_2__c');
        fields.add('SA_Date_of_Last_Use_1__c');
        fields.add('SA_Date_of_Last_Use_2__c');
        fields.add('SA_Use_Details_1__c');
        fields.add('SA_Use_Details_2__c');
        fields.add('Substance_of_Abuse_3__c');
        fields.add('Substance_of_Abuse_4__c');
        fields.add('Substance_Details_3__c');
        fields.add('Substance_Details_4__c');
        fields.add('OTHER_Substance_3__c');
        fields.add('OTHER_Substance_4__c');
        fields.add('SA_Amount_3__c');
        fields.add('SA_Amount_4__c');
        fields.add('SA_Route_3__c');
        fields.add('SA_Route_4__c');
        fields.add('SA_Use_Frequency_3__c');
        fields.add('SA_Use_Frequency_4__c');
        fields.add('SA_Date_of_Last_Use_3__c');
        fields.add('SA_Date_of_Last_Use_4__c');
        fields.add('SA_Use_Details_3__c');
        fields.add('SA_Use_Details_4__c');
        fields.add('Treatment_Program_1__c');
        fields.add('Treatment_Program_2__c');
        fields.add('OTHER_Program_1__c');
        fields.add('OTHER_Program_2__c');
        fields.add('Country_1__c');
        fields.add('Country_2__c');
        fields.add('State_1__c');
        fields.add('State_2__c');
        fields.add('Length_of_Stay_1__c');
        fields.add('Length_of_Stay_2__c');
        fields.add('Date_of_Stay_1__c');
        fields.add('Date_of_Stay_2__c');
        fields.add('Completed_Treatment_1__c');
        fields.add('Completed_Treatment_2__c');
        
        if (!Test.isRunningTest()){
            std.addFields(fields);
        }
        leadRecord = (Lead) std.getRecord();
    }
    
    public PageReference referOut(){
        
        Id convertedOpportunityId;
        List<Messaging.SingleEmailMessage> allEmails = new List<Messaging.SingleEmailMessage>();
            
            Account referredBusinessAccount = [SELECT Id, Name
                                                        FROM Account
                                                        WHERE Id = :associatedOpportunity.Business_Account__c
                                                        LIMIT 1];
            List<Account> referList = [SELECT Id, Name
                                                        FROM Account
                                                        WHERE Id = :associatedOpportunity.Refer_Out_Account__c];
            Account referredReferOutAccount;
            if(!referList.isEmpty()) {
                referredReferOutAccount = referList.get(0);
            }
        
        if (String.isBlank(selectedInsuranceType)){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, '\'Insurance Type\' is a mandatory field.'));
            return null;
        }
        if (String.isBlank(referOutReason)){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, '\'Why are we referring out?\' is a mandatory field.'));
            return null;
        }
        
        try {
            
            LeadStatus convertStatus = [SELECT MasterLabel 
                                        FROM LeadStatus 
                                        WHERE IsConverted = true
                                        LIMIT 1];
                                        
            List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
            
            Database.LeadConvert lc = new Database.LeadConvert();
            
            String oppName = leadRecord.Name;
            lc.setLeadId(leadRecord.Id);
            lc.setOpportunityName(oppName + ' - Referral');
            lc.setConvertedStatus(convertStatus.MasterLabel);
            leadConverts.add(lc);
            
            if (!leadConverts.isEmpty()) {
                List<Database.LeadConvertResult> leadConvertResults = Database.convertLead(leadConverts);
                
                for (Database.LeadConvertResult convertResult : leadConvertResults){
                    if (convertResult.isSuccess()){
                        convertedOpportunityId = convertResult.getOpportunityId();
                        
                        Map<String,Schema.RecordTypeInfo> recordTypeMap = Schema.SObjectType.Opportunity.getRecordTypeInfosByName();
                        Schema.RecordTypeInfo referralRecordType =  recordTypeMap.get('Referrals');
                        
                        
                        Opportunity convertedOpportunity = new Opportunity(Id = convertedOpportunityId);
                        if(referredReferOutAccount != null)
                            convertedOpportunity.Business_Account__c = referredBusinessAccount.id;
                        convertedOpportunity.Refer_Out_Account__c = referredBusinessAccount.Id;
                        convertedOpportunity.RecordTypeId = referralRecordType.getRecordTypeId();
                        
                        update convertedOpportunity;
                        
                        //Add Attachment
                        PageReference pdf = Page.AbandonedCallLeadDetails;
                        pdf.getParameters().put('id',leadRecord.Id);
                        pdf.setRedirect(true);
                        
                        Blob b;
                        
                        if (!Test.isRunningTest()){
                            b = pdf.getContentAsPdf();
                        } else {
                            b = Blob.valueof('Test Method');
                        }
                        
                        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                        efa.setFileName('LeadDetails.pdf');
                        efa.setBody(b);
                        
                        Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
                        String[] sendingTo = new String[]{OrgWide_Settings__c.getOrgDefaults().Refer_Out_Email_Recipient__c};
                        semail.setToAddresses(sendingTo);
                        String treatFacil = '';
                        if(referredReferOutAccount != null) {
                            treatFacil = ' and ' + referredReferOutAccount.Name;
                        }
                        semail.setSubject('Lead Referred Out to ' + referredBusinessAccount.Name + treatFacil);
                        String emailBody = 'A lead has been referred to ' 
                                            + referredBusinessAccount.Name + treatFacil
                                            + '. Please follow the opportunity to track it.'
                                            + URL.getSalesforceBaseUrl().toExternalForm()
                                            + '/' + convertedOpportunityId;
                                            
                        if (String.isNotBlank(selectedInsuranceType)){
                            emailBody += '<br/><br/><b>Insurance Type : </b><br/>' + selectedInsuranceType;
                        }
                        if (String.isNotBlank(referOutReason)){
                            emailBody += '<br/><br/><b>Why are we referring out? : </b><br/>' + referOutReason;
                        }
                                            
                        System.debug(emailBody);
                        semail.setHtmlBody(emailBody);
                        semail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
                        
                        allEmails.add(semail);
                        
                        if (!allEmails.isEmpty()){
                            try{
                                Messaging.sendEmail(allEmails);
                            } catch(Exception e){
                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Lead Referred out Successfully. But failed to send notification. Please inform manually.'));
                                return null;
                            }
                        }
                    } else {
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Failed to Convert Leads. ' + convertResult.getErrors().get(0).getMessage()));
                        return null;
                    }
                }
            }
        } catch (Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'ERROR : ' + e.getmessage()));
            return null;
        }
        return new PageReference('/'+convertedOpportunityId);
    }
}

TEST CLASS

/**
 *  About
 *  -----
 *  Create date: 1 Feb 2016
 *  
 *  Details
 *  -----
 *  Test class for ReferOutExtension Controller Extension
 *  
 *  Update History
 *  -----
 *  
 *  Issues / TODOs
 *  ----- 
 *
**/
@isTest
public class ReferOutExtensionTest{
    
    /**
     *  About
     *  -----
     *  Author: Cloud Nerd
     *  
     *  Details
     *  -----
     *  Setup Test data for the test class
    **/
    
    @TestSetup static void setUpTestData(){
        
        Id assignedTo = [SELECT Id FROM User WHERE IsActive = true Limit 1].Id;
        
        OrgWide_Settings__c orgWideDefaults = new OrgWide_Settings__c();
        orgWideDefaults.Abandoned_Call_Recipient__c = 'test@test.com';
        orgWideDefaults.Abandoned_Call_Task_Owner__c = assignedTo;
        orgWideDefaults.Refer_Out_Email_Recipient__c = 'test@test.com';
        insert orgWideDefaults;
        
        Account unknownAccount = new Account();
        unknownAccount.Name = 'Unknown';
        insert unknownAccount;
        
        Account unknownAccount2 = new Account();
        unknownAccount2.Name = 'Unknown2';
        insert unknownAccount2;
        
        Lead newLead = new Lead();
        newLead.LastName = 'Test Lead';
        newLead.Email = 'test@test.com';
        newLead.Phone = '1234567890';
        newLead.Company = 'Test Company';
        newLead.Status = 'New';
        newLead.Lead_Source__c = 'Abandoned Call';
        insert newLead;
        
    }
    
    private static testMethod void initialPageLoad(){
        
        Lead associatedLead = [SELECT Id FROM Lead where LastName = 'Test Lead'];
        List<Account> unknownAccountList = [SELECT Id FROM Account WHERE Name = 'Unknown'];
        
        
        Test.startTest();
        
        PageReference referOutPage = Page.ReferOut;
        referOutPage.getParameters().put('id',associatedLead.Id);
        
        Test.setCurrentPage(referOutPage);
        
        ApexPages.StandardController std = new ApexPages.StandardController(associatedLead);
        ReferOutExtension extn = new ReferOutExtension(std);
        
        Test.stopTest();
        System.assertEquals(null, extn.selectedInsuranceType);
        System.assertEquals(null, extn.referOutReason);
        System.assertEquals(5, extn.insuranceTypes.size());
        System.assertEquals(unknownAccountList.get(0).id, extn.associatedOpportunity.Business_Account__c);


        
        
    }
    
    private static testMethod void referringOut(){
        
        Lead associatedLead = [SELECT Id, Name FROM Lead where LastName = 'Test Lead'];
      
        
        PageReference referOutPage = Page.ReferOut;
        referOutPage.getParameters().put('id',associatedLead.Id);
        
        Test.setCurrentPage(referOutPage);
        
        ApexPages.StandardController std = new ApexPages.StandardController(associatedLead);
        ReferOutExtension extn = new ReferOutExtension(std);
        
        
        Test.startTest();
        
        extn.selectedInsuranceType = 'PPO';
        extn.referOutReason = 'Test Reason';
        extn.referOut();
        
        Test.stopTest();
        
    }
}

 
I inherited this code and it seems to be causing a lead conversion to fail, but only becuase it's stopping at too many soql queries. Can anyone help me optimize this code to prevent this issue. Thanks. 
 
public with sharing class OpportunityStageHandler {
    
    public OpportunityStageHandler() {
    }

    public static void init(List<Opportunity> opportunities){
        
        String debug = 'Opportunity Stage Handler';
        
        insertOpportunityStageDurations(opportunities);
    }

    public static void insertOpportunityStageDurations(List<Opportunity> opportunities){

        List<Opportunity_Stage_Duration__c> existing = new List<Opportunity_Stage_Duration__c>();
        Map<Id, Opportunity_Stage_Duration__c> existingMap = new Map<Id, Opportunity_Stage_Duration__c>();
        Map<Id, String> existingStageMap = new Map<Id, String>();
        List<Opportunity_Stage_Duration__c> inserts = new List<Opportunity_Stage_Duration__c>();
        DateTime stageStart = DateTime.now();

        existing = [SELECT Id, 
                           Stage__c,
                           Stage_Started__c,
                           Stage_Ended__c,
                           Opportunity__r.Id
                    FROM Opportunity_Stage_Duration__c
                    WHERE Opportunity__c IN :opportunities
                    AND Stage_Ended__c = null];
        
        for(Opportunity_Stage_Duration__c opportunityStageDuration : existing){            
            existingMap.put(opportunityStageDuration.Opportunity__r.Id, opportunityStageDuration);
            existingStageMap.put(opportunityStageDuration.Opportunity__r.Id, opportunityStageDuration.Stage__c);
        }       
        
        for(Opportunity opportunity : opportunities){
            if(existingStageMap.get(opportunity.Id) == null || existingStageMap.get(opportunity.Id) != opportunity.StageName){
                Opportunity_Stage_Duration__c osd = new Opportunity_Stage_Duration__c();

                Integer stageLength = opportunity.StageName.length() + 3;
                Integer nameLength = opportunity.Name.length();

                if(stageLength + nameLength > 80){                    
                    Integer trim = stageLength + nameLength - 80;
                    Integer endIndex = nameLength - trim - 1;
                    osd.Name = (opportunity.Name.substring(0, endIndex)) + ' - ' + opportunity.StageName;
                }else{
                    osd.Name = opportunity.Name + ' - ' + opportunity.StageName;
                }
                
                osd.Opportunity__c = opportunity.Id;        
                osd.Stage_Started__c = stageStart;
                osd.Stage__c = opportunity.StageName;
                inserts.add(osd);
            }
        }

        insert inserts;

        updateOpportunityStageDurations(opportunities, existingMap);
    }

    public static void updateOpportunityStageDurations(List<Opportunity> opportunities,
                                                       Map<Id, Opportunity_Stage_Duration__c> existingMap){
        
        List<Opportunity_Stage_Duration__c> updates = new List<Opportunity_Stage_Duration__c>();
        DateTime stageEnded = DateTime.now();

        for(Opportunity opportunity : opportunities){
            if(existingMap.get(opportunity.Id) != null &&
               existingMap.get(opportunity.Id).Stage__c != opportunity.StageName){
                
                Opportunity_Stage_Duration__c osd = existingMap.get(opportunity.Id);

                osd.Stage_Ended__c = stageEnded;
                Date startDay = Date.newInstance(osd.Stage_Started__c.year(), osd.Stage_Started__c.month(), osd.Stage_Started__c.day());
                Date endDay = Date.newInstance(stageEnded.year(), stageEnded.month(), stageEnded.day());
                osd.Stage_Duration__c = startDay.daysBetween(endDay);
                updates.add(existingMap.get(opportunity.Id));
            }
        }

        update updates;
    }

}

 
I have Date/Time Field that I need to update the first time an Opportunity stage changes and only the first time. Any idea how to accomplish this? Thanks, 
I have a Date/Time Field and I am trying to build a formula to update our task Subject with the words "Check-In" plus the date time field (Check-In Time) value. So, it should look like this: Check-In 10/26/2021 06:42pm EDT 
I've tried several different formuls, but I feel like it's something simple I'm missing. Pleas help! :) 
Hey, all I am looking to have a formula field that looks at Record ID and then checks to see if the picklist field level of care is blank and if it is blank than to return a null value in the field. Here is my code. 
IF(
AND(
RecordType.Id = "012j0000000poaT",
TEXT( Level_of_Care__c ) =""
), NULL,

It doesn't seem to be working. Any help would be greatly appreciated. Thanks! 
Hey all, here's the deal. I have a long text area, which is basically a really long url that I need to cut everything after the question mark and then copy into a URL field. Preferrably, in a declarative fashion. Any ideas? 
I have a use case where we have a webform that is inserted leads in salesforce. The first submission from the webform is creating a lead with a name and number. Then the second submission is a survey. Both are creating leads in salesforce. I need some way, preferrably declarative way of matching the two records and then merging them, or copying all the details from record 2 in to record 1 and then deletiing record 2. Any ideas? 
I have a directive to update an email field on the Account Record called Primary Email with the contents of the standard Email field on a related Contact Record Contact when a checkbox, Primary Client Referral, on the same contact record is checked. Not sure what the best...easiest way to accomplish this is. Any thoughts would be supremely helpul and immensely appreciated.  Thanks in advance!
In my sandbox I am seeing that I have 75% code coverage on my class. When I deploy it to production it is 0. Can someone take a look at the class and test class and help me out. I need this deployed asap. Thanks!

/**
 *  About
 *  -----
 *  Create date: 21 Jan 2016
 *  
 *  Details
 *  -----
 *  Controller Extension for ReferOut VF Page
 *  
 *  Update History
 *  -----
 *  
 *  Issues / TODOs
 *  ----- 
 *
**/
public class ReferOutExtension{
    
    public Lead leadRecord {get;set;}
    public String selectedInsuranceType {get;set;}
    public String referOutReason {get;set;}
    public List<SelectOption> insuranceTypes {
        get {
            if (insuranceTypes == null){
                insuranceTypes = new List<SelectOption>();
                insuranceTypes.add (new SelectOption('','--None--'));
                insuranceTypes.add (new SelectOption('PPO','PPO'));
                insuranceTypes.add (new SelectOption('HMO','HMO'));
                insuranceTypes.add (new SelectOption('Medicare','Medicare'));
                insuranceTypes.add (new SelectOption('Medicaid','Medicaid'));
            }
            return insuranceTypes;
        }
        set;
    }
    public Opportunity associatedOpportunity {
        get {
            if (associatedOpportunity == null){
                List<Account> defaultBusinessAccount = [SELECT Id 
                                                            FROM Account
                                                            WHERE Name = 'Unknown'];
                associatedOpportunity = new Opportunity();
                if (defaultBusinessAccount.size() > 0){
                    associatedOpportunity.Business_Account__c= defaultBusinessAccount[0].Id;
                    if (defaultBusinessAccount.size() > 1)
                        associatedOpportunity.Refer_Out_Account__c= defaultBusinessAccount[1].Id;
                }
            }    
            return associatedOpportunity;
        }
        set;
        
    }
    
    public ReferOutExtension(ApexPages.StandardController std){
        List<String> fields = new List<String>();
        fields.add('Caller_No__c');
        fields.add('MobilePhone');
        fields.add('Email');
        fields.add('Street');
        fields.add('City');
        fields.add('State');
        fields.add('PostalCode');
        fields.add('Phone');
        fields.add('Email');
        fields.add('Primary_Policy_Holder_Same_as_client__c');
        fields.add('Client_Alias__c');
        fields.add('DOB__c');
        fields.add('Client_Other_Phone__c');
        fields.add('Age__c');
        fields.add('SSN__c');
        fields.add('Insured_Street_Address__c');
        fields.add('Insured_Name__c');
        fields.add('Insured_First_Name__c');
        fields.add('Insured_Last_Name__c');
        fields.add('Self_Pay_Amount__c');
        fields.add('Insured_City1__c');
        fields.add('Insured_Relation_To_Client__c');
        fields.add('Insured_State__c');
        fields.add('Insured_DOB__c');
        fields.add('Insured_Zip__c');
        fields.add('Insured_SSN__c');
        fields.add('Insurance_Company__c');
        fields.add('Relationship__c');
        fields.add('OTHER_Insurance_Co__c');
        fields.add('X_ID__c');
        fields.add('Group__c');
        fields.add('Insurance_Phone__c');
        fields.add('Detox_Days__c');
        fields.add('Treatment_Days__c');
        fields.add('Substance_of_Abuse_1__c');
        fields.add('Substance_of_Abuse_2__c');
        fields.add('Substance_Details_1__c');
        fields.add('Substance_Details_2__c');
        fields.add('OTHER_Substance_1__c');
        fields.add('OTHER_Substance_2__c');
        fields.add('SA_Amount_1__c');
        fields.add('SA_Amount_2__c');
        fields.add('SA_Route_1__c');
        fields.add('SA_Route_2__c');
        fields.add('SA_Use_Frequency_1__c');
        fields.add('SA_Use_Frequency_2__c');
        fields.add('SA_Date_of_Last_Use_1__c');
        fields.add('SA_Date_of_Last_Use_2__c');
        fields.add('SA_Use_Details_1__c');
        fields.add('SA_Use_Details_2__c');
        fields.add('Substance_of_Abuse_3__c');
        fields.add('Substance_of_Abuse_4__c');
        fields.add('Substance_Details_3__c');
        fields.add('Substance_Details_4__c');
        fields.add('OTHER_Substance_3__c');
        fields.add('OTHER_Substance_4__c');
        fields.add('SA_Amount_3__c');
        fields.add('SA_Amount_4__c');
        fields.add('SA_Route_3__c');
        fields.add('SA_Route_4__c');
        fields.add('SA_Use_Frequency_3__c');
        fields.add('SA_Use_Frequency_4__c');
        fields.add('SA_Date_of_Last_Use_3__c');
        fields.add('SA_Date_of_Last_Use_4__c');
        fields.add('SA_Use_Details_3__c');
        fields.add('SA_Use_Details_4__c');
        fields.add('Treatment_Program_1__c');
        fields.add('Treatment_Program_2__c');
        fields.add('OTHER_Program_1__c');
        fields.add('OTHER_Program_2__c');
        fields.add('Country_1__c');
        fields.add('Country_2__c');
        fields.add('State_1__c');
        fields.add('State_2__c');
        fields.add('Length_of_Stay_1__c');
        fields.add('Length_of_Stay_2__c');
        fields.add('Date_of_Stay_1__c');
        fields.add('Date_of_Stay_2__c');
        fields.add('Completed_Treatment_1__c');
        fields.add('Completed_Treatment_2__c');
        
        if (!Test.isRunningTest()){
            std.addFields(fields);
        }
        leadRecord = (Lead) std.getRecord();
    }
    
    public PageReference referOut(){
        
        Id convertedOpportunityId;
        List<Messaging.SingleEmailMessage> allEmails = new List<Messaging.SingleEmailMessage>();
            
            Account referredBusinessAccount = [SELECT Id, Name
                                                        FROM Account
                                                        WHERE Id = :associatedOpportunity.Business_Account__c
                                                        LIMIT 1];
            List<Account> referList = [SELECT Id, Name
                                                        FROM Account
                                                        WHERE Id = :associatedOpportunity.Refer_Out_Account__c];
            Account referredReferOutAccount;
            if(!referList.isEmpty()) {
                referredReferOutAccount = referList.get(0);
            }
        
        if (String.isBlank(selectedInsuranceType)){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, '\'Insurance Type\' is a mandatory field.'));
            return null;
        }
        if (String.isBlank(referOutReason)){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, '\'Why are we referring out?\' is a mandatory field.'));
            return null;
        }
        
        try {
            
            LeadStatus convertStatus = [SELECT MasterLabel 
                                        FROM LeadStatus 
                                        WHERE IsConverted = true
                                        LIMIT 1];
                                        
            List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
            
            Database.LeadConvert lc = new Database.LeadConvert();
            
            String oppName = leadRecord.Name;
            lc.setLeadId(leadRecord.Id);
            lc.setOpportunityName(oppName + ' - Referral');
            lc.setConvertedStatus(convertStatus.MasterLabel);
            leadConverts.add(lc);
            
            if (!leadConverts.isEmpty()) {
                List<Database.LeadConvertResult> leadConvertResults = Database.convertLead(leadConverts);
                
                for (Database.LeadConvertResult convertResult : leadConvertResults){
                    if (convertResult.isSuccess()){
                        convertedOpportunityId = convertResult.getOpportunityId();
                        
                        Map<String,Schema.RecordTypeInfo> recordTypeMap = Schema.SObjectType.Opportunity.getRecordTypeInfosByName();
                        Schema.RecordTypeInfo referralRecordType =  recordTypeMap.get('Referrals');
                        
                        
                        Opportunity convertedOpportunity = new Opportunity(Id = convertedOpportunityId);
                        if(referredReferOutAccount != null)
                            convertedOpportunity.Business_Account__c = referredBusinessAccount.id;
                        convertedOpportunity.Refer_Out_Account__c = referredBusinessAccount.Id;
                        convertedOpportunity.RecordTypeId = referralRecordType.getRecordTypeId();
                        
                        update convertedOpportunity;
                        
                        //Add Attachment
                        PageReference pdf = Page.AbandonedCallLeadDetails;
                        pdf.getParameters().put('id',leadRecord.Id);
                        pdf.setRedirect(true);
                        
                        Blob b;
                        
                        if (!Test.isRunningTest()){
                            b = pdf.getContentAsPdf();
                        } else {
                            b = Blob.valueof('Test Method');
                        }
                        
                        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                        efa.setFileName('LeadDetails.pdf');
                        efa.setBody(b);
                        
                        Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
                        String[] sendingTo = new String[]{OrgWide_Settings__c.getOrgDefaults().Refer_Out_Email_Recipient__c};
                        semail.setToAddresses(sendingTo);
                        String treatFacil = '';
                        if(referredReferOutAccount != null) {
                            treatFacil = ' and ' + referredReferOutAccount.Name;
                        }
                        semail.setSubject('Lead Referred Out to ' + referredBusinessAccount.Name + treatFacil);
                        String emailBody = 'A lead has been referred to ' 
                                            + referredBusinessAccount.Name + treatFacil
                                            + '. Please follow the opportunity to track it.'
                                            + URL.getSalesforceBaseUrl().toExternalForm()
                                            + '/' + convertedOpportunityId;
                                            
                        if (String.isNotBlank(selectedInsuranceType)){
                            emailBody += '<br/><br/><b>Insurance Type : </b><br/>' + selectedInsuranceType;
                        }
                        if (String.isNotBlank(referOutReason)){
                            emailBody += '<br/><br/><b>Why are we referring out? : </b><br/>' + referOutReason;
                        }
                                            
                        System.debug(emailBody);
                        semail.setHtmlBody(emailBody);
                        semail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
                        
                        allEmails.add(semail);
                        
                        if (!allEmails.isEmpty()){
                            try{
                                Messaging.sendEmail(allEmails);
                            } catch(Exception e){
                                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Lead Referred out Successfully. But failed to send notification. Please inform manually.'));
                                return null;
                            }
                        }
                    } else {
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Failed to Convert Leads. ' + convertResult.getErrors().get(0).getMessage()));
                        return null;
                    }
                }
            }
        } catch (Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'ERROR : ' + e.getmessage()));
            return null;
        }
        return new PageReference('/'+convertedOpportunityId);
    }
}

TEST CLASS

/**
 *  About
 *  -----
 *  Create date: 1 Feb 2016
 *  
 *  Details
 *  -----
 *  Test class for ReferOutExtension Controller Extension
 *  
 *  Update History
 *  -----
 *  
 *  Issues / TODOs
 *  ----- 
 *
**/
@isTest
public class ReferOutExtensionTest{
    
    /**
     *  About
     *  -----
     *  Author: Cloud Nerd
     *  
     *  Details
     *  -----
     *  Setup Test data for the test class
    **/
    
    @TestSetup static void setUpTestData(){
        
        Id assignedTo = [SELECT Id FROM User WHERE IsActive = true Limit 1].Id;
        
        OrgWide_Settings__c orgWideDefaults = new OrgWide_Settings__c();
        orgWideDefaults.Abandoned_Call_Recipient__c = 'test@test.com';
        orgWideDefaults.Abandoned_Call_Task_Owner__c = assignedTo;
        orgWideDefaults.Refer_Out_Email_Recipient__c = 'test@test.com';
        insert orgWideDefaults;
        
        Account unknownAccount = new Account();
        unknownAccount.Name = 'Unknown';
        insert unknownAccount;
        
        Account unknownAccount2 = new Account();
        unknownAccount2.Name = 'Unknown2';
        insert unknownAccount2;
        
        Lead newLead = new Lead();
        newLead.LastName = 'Test Lead';
        newLead.Email = 'test@test.com';
        newLead.Phone = '1234567890';
        newLead.Company = 'Test Company';
        newLead.Status = 'New';
        newLead.Lead_Source__c = 'Abandoned Call';
        insert newLead;
        
    }
    
    private static testMethod void initialPageLoad(){
        
        Lead associatedLead = [SELECT Id FROM Lead where LastName = 'Test Lead'];
        List<Account> unknownAccountList = [SELECT Id FROM Account WHERE Name = 'Unknown'];
        
        
        Test.startTest();
        
        PageReference referOutPage = Page.ReferOut;
        referOutPage.getParameters().put('id',associatedLead.Id);
        
        Test.setCurrentPage(referOutPage);
        
        ApexPages.StandardController std = new ApexPages.StandardController(associatedLead);
        ReferOutExtension extn = new ReferOutExtension(std);
        
        Test.stopTest();
        System.assertEquals(null, extn.selectedInsuranceType);
        System.assertEquals(null, extn.referOutReason);
        System.assertEquals(5, extn.insuranceTypes.size());
        System.assertEquals(unknownAccountList.get(0).id, extn.associatedOpportunity.Business_Account__c);


        
        
    }
    
    private static testMethod void referringOut(){
        
        Lead associatedLead = [SELECT Id, Name FROM Lead where LastName = 'Test Lead'];
      
        
        PageReference referOutPage = Page.ReferOut;
        referOutPage.getParameters().put('id',associatedLead.Id);
        
        Test.setCurrentPage(referOutPage);
        
        ApexPages.StandardController std = new ApexPages.StandardController(associatedLead);
        ReferOutExtension extn = new ReferOutExtension(std);
        
        
        Test.startTest();
        
        extn.selectedInsuranceType = 'PPO';
        extn.referOutReason = 'Test Reason';
        extn.referOut();
        
        Test.stopTest();
        
    }
}

 
I have Date/Time Field that I need to update the first time an Opportunity stage changes and only the first time. Any idea how to accomplish this? Thanks, 
Hey, all I am looking to have a formula field that looks at Record ID and then checks to see if the picklist field level of care is blank and if it is blank than to return a null value in the field. Here is my code. 
IF(
AND(
RecordType.Id = "012j0000000poaT",
TEXT( Level_of_Care__c ) =""
), NULL,

It doesn't seem to be working. Any help would be greatly appreciated. Thanks! 
Hi, 

  Do we have any option to disable trigger during data loader mass update? Please suggest me if we have any options to disable. 

Thanks
Sudhir