• Robert Davis 1
  • NEWBIE
  • 60 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 9
    Questions
  • 17
    Replies
I have a trigger on the Account that looks into a Custom Metadata Type and if the User Id is there they are allowed to delete the record otherwise they receive an error message.

The trigger acts as expected in testing my problem is I do not understand how to write the test code.

Account Trigger:
trigger AccountTrigger2 on Account ( before delete) 
{
    Account_Trigger_Handler handler = new Account_Trigger_Handler();    
    if(Trigger.IsDelete)
    {
        handler.OnDelete_Account(Trigger.old);
        
    }//End if
}//End class
Trigger Handler:
public with sharing class Account_Trigger_Handler {

    public void OnDelete_Account(List<Account> acct)
    {
        //get user id for current user
        Id uid = UserInfo.getUserId();
        system.debug('User id : '+uid);
        //create a map to put in all the users who are authorized to delete
        Map<Id,Account_Delete_User__mdt> mapAcctDeleteUser = new Map<Id, Account_Delete_User__mdt>(); 
        //loop through the users who are authorized to delete and put them in the map we created just before this
        for(Account_Delete_User__mdt AcctDeleteUser : [SELECT id, UserId__c FROM Account_Delete_User__mdt])
        {
            mapAcctDeleteUser.put(AcctDeleteUser.Userid__c, AcctDeleteUser);
        }//end for
        
        //loop through the records in the trigger and see if the current user is authorized to delete.
        for(Account a: acct)
        {
            if(mapAcctDeleteUser.keyset().contains(uid)== false)
            {
            a.addError('You are not authorized to remove Accounts from Salesforce. Please email Salesforce.admin@XXXXX.net to have record removed.');
            }//end if
        }//end for           
     }//end method
  }
The following is the test class I have so far, but it gets the error: System.AsyncException: Metadata cannot be deployed from within a test

But I do not know how to fix:
@isTest
public class Account_Trigger_HandlerTest {
  
    public static testMethod void OnDelete_AccountTest()
    {
        Profile p2 = [SELECT id FROM Profile WHERE Name ='Standard User'];
        
        User usr2 = new User (LastName ='Boris',
                              FirstName ='Badenov',
                              Email = 'boris.badenov@bullwinkleshow.com',
                              Username = 'boris.badenov@bullwinkleshow.com',
                              Alias = 'boris',
                              Profileid = p2.Id,
                              TimeZoneSidKey ='GMT' ,
                              LanguageLocaleKey = 'en_US',
                              EmailEncodingKey = 'UTF-8',
                              LocaleSidKey = 'en_US');
        insert usr2;
    //---------------------------------------------------------------------
    //https://ashwanisoni.wordpress.com/2017/05/02/create-or-update-custom-metadata-type-via-apex-code-salesforce-summer-17/
        // Set up custom metadata to be created in the subscriber org.
    Metadata.CustomMetadata customMetadata =  new Metadata.CustomMetadata();
    customMetadata.fullName = 'Account_Delete_User';
    customMetadata.label = 'User';

    Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
    customField.field = 'UserId__c';
    customField.value = usr2.id;

    customMetadata.values.add(customField);

    Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
    mdContainer.addMetadata(customMetadata);

    // Setup deploy callback, MyDeployCallback implements
    // the Metadata.DeployCallback interface (code for
    // this class not shown in this example)
    CustomMetadataCallback callback = new CustomMetadataCallback();

    // Enqueue custom metadata deployment
    // jobId is the deployment ID
    Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
    //----------------------------------------------------------------------
        Profile p = [SELECT id FROM Profile WHERE Name ='Standard User'];
        
        User usr1 = new User (LastName ='Fatale',
                              FirstName ='Natasha',
                              Email = 'natasha.fatele@bullwinkleshow.com',
                              Username = 'natasha.fatele@bullwinkleshow.com',
                              Alias = 'natas',
                              Profileid = p.Id,
                              TimeZoneSidKey ='GMT' ,
                              LanguageLocaleKey = 'en_US',
                              EmailEncodingKey = 'UTF-8',
                              LocaleSidKey = 'en_US');
        insert usr1;
        Account acct2 = New Account(Name='Snagglepuss', Type='Prospect', SSN__c = '12385678', CreatedById = usr1.id);
        insert acct2;
        Test.startTest();
            Database.DeleteResult result = Database.delete(acct2,false);
            System.assert(!result.isSuccess());
        Test.stopTest();
        
        
    }
}
The following is the callback function that the test code references:
public class CustomMetadataCallback implements Metadata.DeployCallback {
    public void handleResult(Metadata.DeployResult result,
                             Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            System.debug('success: '+ result);
        } else {
            // Deployment was not successful
            System.debug('fail: '+ result);
        }                       
    }
//https://ashwanisoni.wordpress.com/2017/05/02/create-or-update-custom-metadata-type-via-apex-code-salesforce-summer-17/  
}
I am just missing the boat on how to fix this.

Really would appreciate any help.

 
I have a batch class that I have tested in a Sandbox with 10,000 records and it appears to be functioning as it should. My issue now is I can not seem to figure out the Test Class.

What basically happens is we have Sales Agents that are created as part of a custom Object. I go to the Account that these Sale Agents records are related to and create Accounts for each one and match the original Sales Agent record to the new Account.

I store the id for the Account in a Custom Setting.

The Batch Process:
global class CreateAccountsNewlyCreatedDSS implements 
    Database.Batchable<sObject>, Database.Stateful {
    
    public disc2__c disc2 = disc2__c.getValues('DSS Agent Codes Account ID');
    global ID AcctID = disc2.DSS_AccountID__c;
    
    // instance member to retain state across transactions
    global Integer recordsProcessed = 0;
    global Database.QueryLocator start(Database.BatchableContext bc) 
    {
        return Database.getQueryLocator(
            'SELECT id ,'               +
                    'ssn__c,'           +
                    'agent__c,'         + 
                    'ag_first_name__c,' +
                    'ag_last_name__c,'  +
                    'agent_name__c '    +
            'FROM agent_code__c '       +
            'WHERE agent__c =: AcctID'
        ); 
    }
    global void execute(Database.BatchableContext bc, List<Agent_Code__c> scope)
    {
        // process each batch of records
        map<string, account> ma = new map<string, account>();
        for (agent_code__c ac: scope) 
        {
            
                account a = new account();
                a.AG_First_Name__c = ac.ag_first_name__c;
                a.AG_Last_Name__c  = ac.ag_last_name__c;
                a.Name             = ac.Agent_Name__c;
                a.SSN__c           = ac.ssn__c;
                ma.put(a.SSN__c, a);
                
                
                
                recordsProcessed = recordsProcessed + 1;
        }
        Database.UpsertResult[] upsAgtCode = Database.upsert(ma.values(),account.fields.ssn__c, false);
        for(agent_code__c ac1: scope)
        {
            ac1.agent__c=ma.get(ac1.ssn__c).id;
        }
        database.update(scope, false);
        
        
    }
       
        
    global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + ' records processed. Shazam!');
        List<Agent_Code__c> AgtCde = [SELECT id, Agent__c, Name FROM Agent_Code__c WHERE Agent__c =: AcctID];
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems,
            CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for(User usr: [SELECT id, email FROM User WHERE Profile.Name = 'System Administrator'])
        {
            
            
            System.debug('User Array of the System Administrators '+ usr);
            Messaging.SingleEmailMessage mail2 = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            sendTo.add(usr.Email);
            mail2.setToAddresses(sendTo);
            List<String> ccTo = new List<String>();
            ccTo.add('robert.d@XXX.com');
            mail2.setCcAddresses(ccTo);
            mail2.setSubject('Apex Batched Job - Move Contacts from Distribution Supply Source Account');
            string body = 'The Apex Batch Job named \'CreateAccountsNewlyCreatedDSS.apxc\' moves agent codes ';
                   body += 'from the DSS Account and creates them as their own accounts. This process runs daily ';
                   body += 'and was once a manual process. ';
                   body += 'Below are the specifics of this batch job : <br/><br/>';
            body += 'Apex Job '+ job + '<br/><br/>';
            if(AgtCde.size() > 0)
            {
                body += 'List of Agent Codes that were not moved and need to be investigated : <br/><br/> ';
                for(Agent_Code__c ac: AgtCde)
                {
                    body += '    This record id <b>' + ac.Id + '</b> was not moved. <br/>';
                    body += '    This is the Agent Code that did not process <b>'+ ac.Name+'</b>.<br/><br/>';
                }
            } else 
            {
                body += '<b>No Records were left behind</br>. All records matched the requirements to create Accounts. ';    
            }
            
            body += '<br/><br/>For more information on this process and how it should work go to the Admin Routines in ';
            body += 'New Parts Salesforce Org and go to #NewAgentCodes:MovefromTheNewAgentCodeAccountBucket .';
            mail2.setHtmlBody(body);
            mails.add(mail2);
            
        }
        Messaging.sendEmail(mails);
    }    
}

Batch Schedule:
global class MoveAgentCodesBatchScheduler  implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
       
        // We now call the batch class to be scheduled
        CreateAccountsNewlyCreatedDSS b = new CreateAccountsNewlyCreatedDSS();
       
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,2000);
    }
   
}
Test Class that not only seems to have to many DML statements but also de-reference a null object.
@isTest
public class CreateAccountsNewlyCreatedDSS_Batch_Test 
{
    
    @testSetup
    
    static void setup()
    {
        Account acct = New Account(Name= 'Test Account'
        );
        insert acct;
        
        List<Agent_Code__c> lstAgtCd = new List<Agent_Code__c>();
        for(Integer i=0; i<20; i++)
        {
            lstAgtCd.add(new Agent_Code__c(Agent__c = acct.id,
                                           Name = 'AgentTestCode'+i,
                                           ag_first_name__c = 'AgentFirstTestName'+i,
                                           ag_last_name__c = 'AgentLastTestName'+i,
                                           ssn__c = i+'2341'
            ));
        }
        
        insert lstAgtCd;      
    }
            static testmethod void test()
        {
            Test.startTest();
            CreateAccountsNewlyCreatedDSS testBatch = new CreateAccountsNewlyCreatedDSS();
            Id batchprocessId = Database.executeBatch(testBatch,10000);
            Test.stopTest();
            
        }
    
}
Your help is appreciated. Thank you in advance for any insight.

Robert

 
I would like to create a Completed Tasks for when an Email is sent from the Contact Page. The reason being is we capture particular values in custom fields when the email is sent based on the different profiles. I think my problem is that I am unable to capture the Contact ID which then means I am unable to capture the Account ID for the Task.
 
Trigger:

trigger Create_Task_Trigger on EmailMessage (after insert) {
    
    Create_Task_TriggerHandler.After_Insert(Trigger.new);

}

Trigger Handler:

public class Create_Task_TriggerHandler {
    
    public static void After_Insert(List<EmailMessage> EmailMessage){
        List<Task> tsk = new List<Task>();
        for(EmailMessage em: EmailMessage){
            System.debug('EmailMessage.RelatedtoID '+em.RelatedToId);
            for(Contact cont : [SELECT Accountid, id FROM Contact WHERE id=: em.RelatedToId]){
                Task tsk1 = new Task();
                tsk1.WhatId = cont.AccountId;
                system.debug('Account ID '+ cont.AccountID);
                tsk1.WhoId = cont.Id;
                system.debug('Contact ID '+cont.id);
                tsk1.Subject = 'EMAIL SENT : '+ em.Subject;
                tsk1.OwnerId = UserInfo.getUserId();
                tsk1.Sales_Activity__c = 'SENT EMAIL';
                tsk.add(tsk1);
             }
        }
        Insert tsk;
        
    }

}

It appears that the EmailMessage.RelatedToID is null. Any ideas on how I might solve this issue?

Your help is appreciated.

Robert
I am certain that I am missing something, and am hoping someone can point me to the correct instructions. I did the Trailhead to create a custom homepage, Lightning App Builder, Building a Custom Home Page for Lightning Experience. But ever since then the Home icon on the sidebar is gone and the user goes directly to the Opportunity tab / page.

Can anyone help. I looked and looked but could not find anything that worked for me. Thanks in advance.

Robert
 
I am reading the Trailhead module about Lightning and it advises that the navigation withing Lightning should be done with events using the sforce.one object which is Javascript. It then says sforce.one isn't available in Classic Salesforce.

So am I understanding this correctly, that there will be one method for writing navigation in Visualforce pages in Classic Salesforce and another for Lightning Salesforce?

Thank you, I am kinda new to all of this.

Robert 
I am attempting to add a tab to a custom visual force page someone put together from what appears is this article http://ttps://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_quick_start_tabs.htm

When I go to the classic Salesforce view the object shows in as a related list to Accounts.
When I remove any of the other tabs in the code they disappear, but when I copy a tab's code and copy it into the code with a new id name it does not appear as a new tab.
I have checked object permissions and pagelayout assignment and they seem correct.

Question : Why is my tab (named CS_Division) not showing up? I am not sure how much of the code you need to see so I will put the tab code and then the entire code in hopes it makes it easier to read.
 
<apex:tab label="C S Div" name="CS_Division" id="CSD">
        <apex:relatedList subject="{!account}" list="CS_Rev_Div2s__r"
               rendered="{!$ObjectType.CS_Rev_Div2__c.accessible}"/>
</apex:tab>

The entire page code:
 
<apex:page standardController="Account" action="{!IF(NOT(CONTAINS($Profile.Name,'LEX')),
    null, 
    urlFor($Action.Account.View, account.id,
    null, true))}"
    showHeader="true" tabStyle="account" >
<apex:form >
<apex:inputfield value="{!Account.hidden__c}" style="width:1px; height: 1px" required="false" onfocus="true" />
</apex:form>
<!-- chatter component for follow link only - using the feed component instead
<chatter:follow entityId="{!Account.ID}"/>
-->
<chatter:feedWithFollowers entityId="{!Account.Id}" />
   <style>
      .activeTab {background-color: #236FBD; color:white; 
         background-image:none}
      .inactiveTab { background-color: lightgrey; color:black; 
         background-image:none}
   </style>
   
  
      <apex:sectionheader title="{!account.Name}"/> 

        <apex:outputpanel rendered="{!CASESAFEID(Account.RecordTypeId)='012000000003LLAAQ'}">

      <apex:tabPanel switchType="client" selectedTab="tabdetails" id="AccountTabPanel" tabClass="activeTab" inactiveTabClass="inactiveTab">   
      <apex:tab label="{!$Label.Details}" name="AccDetails" id="tabdetails" >
    
          <apex:detail subject="{!account.Id}" relatedList="false" title="false" inlineEdit="true"/>

       
          <apex:relatedList subject="{!account}" list="Interviews__r" 
                     rendered="{!$ObjectType.Exit_Interview__c.updateable}"/>
                      <apex:outputLink value="/{!Account.PreviousMORID__c}/e?clone=1&retURL=%2F" id="theLink" rendered="{!account.PreviousMORBID__c != ''}" target="_parent" >MOR from Previous</apex:outputLink>

 <apex:outputLink value="/apex/morbnew?CF00N00N3030303000000008stWP={!account.Name}&CF00N3030303009stWP_lkid={!account.Id}&scontrolCaching=1&retURL=%2Fapex%2FtabbedAccount%3Fid%3D{!account.Id}%26sfdc.override%3D1&sfdc.override=1" rendered="{!account.PreviousmorBID__c == ''}" target="_parent" >Monthly Operations Report</apex:outputLink>
&nbsp;
<apex:outputLink value="/apex/EditableContactList?ID={!Account.ID}" id="SurveyPLan" rendered="{!account.Submit_Survey_Plan_October_2015__c != TRUE}" target="_parent" >Survey</apex:outputLink>
      </apex:tab>
      
     
     <apex:tab label="{!$Label.Account_Team}" name="AccountTeamMembers" id="tabAccountTeam">
      <apex:relatedList subject="{!account}" list="accountteammembers" />
      </apex:tab>
      

      <apex:tab label="{!$Label.Contacts}" name="Contacts" id="tabContact">
      <apex:relatedList subject="{!account}" list="contacts" 
       rendered="{!$ObjectType.contact.accessible}"/>
      </apex:tab>
      
      
      
       <apex:tab label="{!$Label.Opportunities}" name="Opportunities" id="tabOpp">
         <apex:relatedList subject="{!account}" list="opportunities" 
         rendered="{!$ObjectType.opportunity.accessible}"/>
      </apex:tab>
      
      <apex:tab label="{!$Label.Notes_and_Attachments}" name="NotesAttachments" id="tabNotesAttachments">
      <apex:relatedList subject="{!account}"  list="CombinedAttachments" />
      </apex:tab>
      
      <apex:tab label="{!$Label.Open_Activities}" name="OpenActivities" id="tabOpenAct">
         <apex:relatedList subject="{!account}" list="OpenActivities" />
      </apex:tab>
      
      <apex:tab label="{!$Label.Activity_History}" name="History" id="tabActivityHistory">
         <apex:relatedList subject="{!account}" list="ActivityHistories" />
            </apex:tab>
            
            <apex:tab label="Account History" name="Field History" id="fieldhistory">
      <apex:outputLink value="/_ui/common/history/ui/EntityHistoryFilterPage?id={!account.id}">Click to view Account History</apex:outputLink>
        </apex:tab>

           

       <apex:tab label="Account Alerts" name="AcctAlerts" id="tabAccountAlerts">
         <apex:relatedList subject="{!account}" list="AcctAlerts__r" 
             rendered="{!$ObjectType.Acct_Alert__c.accessible}"/>
         
      </apex:tab>
      <apex:tab label="Wallet Share" name="WalletShare" id="tabWalletShare">
         <apex:relatedList subject="{!account}" list="Wallet__r" 
         rendered="{!$ObjectType.WalletShare__c.accessible}"/>
      </apex:tab>
      
      
      <apex:tab label="Client Concerns" name="CSurveys" id="CSurveys">
         <apex:relatedList subject="{!account}" list="CSurveys__r" 
            rendered="{!$ObjectType.CSurvey__c.accessible}"/> 
            <apex:relatedList subject="{!account}" list="CPlans__r" 
            rendered="{!$ObjectType.CPlan__c.accessible}"/>
              <apex:relatedList subject="{!account}" list="CForms__r" 
            rendered="{!$ObjectType.CForm__c.accessible}"/>
      </apex:tab>    

    <apex:tab label="Monthly Operations Reporting" name="Weekly_Account_Updates1" id="MOR">
     <center>

<!-- NEW CODE BELOW -->
    <apex:tab label="C S Div" name="CS_Division" id="CSD">
        <apex:relatedList subject="{!account}" list="CS_Rev_Div2s__r"
               rendered="{!$ObjectType.CS_Rev_Div2__c.accessible}"/>
    </apex:tab>
</apex:page>
I appreciate you taking a look at this and would appreciate all feedback.

Thank you.

Robert
 
I am attempting to create a Visualforce page that allows the user to select a contact from a lookup field on a custom object to the contacts object. I am surely missing something silly. Your help would be super.
 
<apex:page standardController="Contact_Plan__c">
    <apex:pageBlock >
        <apex:pageBlockSection>
            <apex:form>
            
                <apex:inputField value="{! Contact_Plan__c.name}"/>     
                <apex:inputField value="{! Contact_Plan__r.Contact.Name}"/>
            </apex:form>
       </apex:pageBlockSection>
</apex:page>

The page would allow for the individual to enter the Contact Plan Name and then Select a Contact from the Contact Object. I have created a custom object called Contact_Plan__c.

Your help is greatly appreciated in advance.

Robert
I am new to the Apex and am see if someone can help me understand how I go about testing a method that gets its data from a List that is an sObject when the parameter that I pass in is the String of the query. I am having trouble figuring out how to get the execute method to test successfully.

The following is my Apex Batchable Class:
 
global class MyBatchJob implements Database.Batchable<sObject>{

    global string query;

       
    global MyBatchJob(){
        String query = 'SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                              
                                   'FROM Opportunity';     
    } 

    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('Started the Batch job to copy key Opportunity Record fields.');
        System.debug('The current Batch unique identifier for this job is : '+ BC.getJobId());
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<Opportunity> scope) {
        System.debug('Executed the Batch job to copy Opportunity Records.');
        System.debug('The current Batch unique identifier for this job is : '+ BC.getJobId());
        List<Opportunity_Snapshot__c> snapList = new List<Opportunity_Snapshot__c>();

                 //Assuming the snapshots you want are of Contact data
		        for(Opportunity opp: scope) {
                 //create a sObject NOT an sObject List to hold the data until I add to the List with snapList.add(snap)
                 //This is a lot like creating a JSON framework in Javascript
                    Opportunity_Snapshot__c snap = new Opportunity_Snapshot__c();
            
                    //start adding to the snap variable from the query results
                    snap.Ss_Account_Id__c                       = opp.AccountId;
                    snap.Ss_Account_Industry__c                 = opp.Account.Industry;
                    snap.Ss_Account_Name__c                     = opp.Account.Name;
                    snap.Ss_Account_Owner_Id__c                 = opp.Account.OwnerId;
                    snap.Ss_Account_Owner_Name__c               = opp.Account.Owner.Firstname + ' ' + opp.Owner.Lastname;
                    snap.Ss_Account_Recordtype_Id__c            = opp.account.recordtypeid;
                    snap.Ss_Account_Recordtype_Name__c          = opp.account.recordtype.name;
                    snap.Ss_Account_Type__c                     = opp.Account.Type;
                    snap.Ss_Opportunity_Amount__c               = opp.Amount;
                    snap.Ss_Opportunity_Annualized_Revenue__c   = opp.Annualized_Revenue__c;
                    snap.Ss_Opportunity_Level_of_Effort__c      = opp.Level_of_Effort__c;
                    snap.Ss_Opportunity_Name__c                 = opp.Name;
                    snap.Ss_Opportunity_Owner_Id__c             = opp.Ownerid;
                    snap.Ss_Opportunity_Owner_Name__c           = opp.Owner.firstname + ' ' + opp.Owner.lastname;
                    snap.Ss_Opportunity_Solution_Complexity__c  = opp.Solution_Complexity__c;
                    snap.Ss_Opportunity_Stage_Name__c           = opp.StageName;
                    snap.Ss_Opportunity_Total_FTE__c            = opp.FTEs__c;
                    snap.Ss_Opportunity_Total_Seats__c          = opp.TotalNumberofSeats__c;

                    //Let's now add these variables to the list to be inserted at the end of the loop.
                    snapList.add(snap); 
  
          
        } 
        insert snapList; 
   }

   global void finish(Database.BatchableContext BC) {
        System.debug(LoggingLevel.WARN,'Batch Job is Complete!!!!!');
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'any@gmail.com', 'any@outlook.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Email Batch Worked');
        mail.setPlainTextBody ('Batch Job worked');
    }
}
So far I have 29% successfully tested.
 
@isTest
public class TestMyBatchJob {
    public static testmethod void TestBatchJob(){
        Test.startTest();
        MyBatchJob bj = new MyBatchJob();
        bj.query=      'SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                                
                                   'FROM Opportunity';        
        ID batchprocessid = Database.executeBatch(bj);

        Test.stopTest();
   
       }


	public static void testBatch() 
	     {
	        List<Opportunity_Snapshot__c> testSnaplist = new List<Opportunity_Snapshot__c>();
        
            Opportunity_Snapshot__c testSnap = new Opportunity_Snapshot__c();
		    for(Integer i = 0 ; i < 200; i++){
		        testSnap.Ss_Account_Id__c                       = 'ID123425'+i;
                testSnap.Ss_Account_Industry__c                 = 'Offshoring and Nearshoring Test';
                testSnap.Ss_Account_Name__c                     = 'Test Account Name'+i;
                testSnap.Ss_Account_Owner_Id__c                 = 'Account Owner Test '+i;
                testSnap.Ss_Account_Owner_Name__c               = 'Test J Tester '+i*157469;
                testSnap.Ss_Account_Recordtype_Id__c            = 'Record Type Id123456789012345678901234567890123456789' +i;
                testSnap.Ss_Account_Recordtype_Name__c          = 'Record Type Name ' +i;
                testSnap.Ss_Account_Type__c                     = 'Account Prospect '+i;
                testSnap.Ss_Opportunity_Amount__c               =  451+i;
                testSnap.Ss_Opportunity_Annualized_Revenue__c   = 12+i;
                testSnap.Ss_Opportunity_Level_of_Effort__c      = 26+i;
                testSnap.Ss_Opportunity_Name__c                 = 'Test Opportunity Name ' +i;
                testSnap.Ss_Opportunity_Owner_Id__c             = 'Opportunity Owner Test ID'+i;
                testSnap.Ss_Opportunity_Owner_Name__c           = 'Sammy the Tester';
                testSnap.Ss_Opportunity_Solution_Complexity__c  = 'High';
                testSnap.Ss_Opportunity_Stage_Name__c           = 'Test Opportunity Stage ' +i;
                testSnap.Ss_Opportunity_Total_FTE__c            = 12;
                testSnap.Ss_Opportunity_Total_Seats__c          = 37;    
            
                testSnaplist.add(testSnap);

		}

		insert testSnaplist;
	   
		Test.StartTest();
               MyBatchJob bj2 = new MyBatchJob();
        
		ID batchprocessid = Database.executeBatch(bj2);
		   
		Test.StopTest();
		
		
	}
}
Your help is greatly appreciated.

Robert

 
Hello,

I am trying to pull data from the Account and Opportunity Objects and insert into a Custom Object named RD_SnapShot_Opportunity. I have the SOQL Query assigned to a list. I think I need to loop through the list and assign the elements in that list to another list and when done insert with a DML statement.

I can not figure out how to take a sObject of Opportuntity that results from the SOQL query and assign to a new List to insert into the table.

Please point me in the right direction. Have I assigned the Opportunity list resulting from the SOQL to the wrong type of sObject?
 
public class RD_SnapshotOpportunityAggregation {
    //To take key information from the Opportunity Object on a schedule to store in the OpportunitySnapshot Object
    
    public static void transferOpportunityData() {
        List<Opportunity> oppList = [ SELECT account.id, 
                                   account.name, 
                                   account.type, 
                                   account.industry, 
                                   account.recordtypeid, 
                                   account.recordtype.name, 
                                   account.ownerId, 
                                   Owner.firstname, 
                                   Owner.lastname, 
                                   Name, 
                                   StageName, 
                                   FTEs__c, 
                                   TotalNumberofSeats__c, 
                                   Amount, 
                                   Annualized_Revenue__c   
                                   FROM Opportunity
                                   ];
        
        // is the RD_Snapshot_Opportunity__c the correct object 
        for(RD_Snapshot_Opportunity__c snap: oppList) {
            //not sure how to assign values to the appropriate field in the snap sObject        
            snap.SsAccountId = oppList[1];
            snap.SsAccountName = oppList[2];
            snap.SsAccountType = oppList[3];
            snap.SsAccountIndustry = oppList[4];
            
            //and each field as we go down the list.
            
        }
        insert opp
    }
}

Any help would be appreciated. Thank you

Thanks in advance,
Robert
I have a trigger on the Account that looks into a Custom Metadata Type and if the User Id is there they are allowed to delete the record otherwise they receive an error message.

The trigger acts as expected in testing my problem is I do not understand how to write the test code.

Account Trigger:
trigger AccountTrigger2 on Account ( before delete) 
{
    Account_Trigger_Handler handler = new Account_Trigger_Handler();    
    if(Trigger.IsDelete)
    {
        handler.OnDelete_Account(Trigger.old);
        
    }//End if
}//End class
Trigger Handler:
public with sharing class Account_Trigger_Handler {

    public void OnDelete_Account(List<Account> acct)
    {
        //get user id for current user
        Id uid = UserInfo.getUserId();
        system.debug('User id : '+uid);
        //create a map to put in all the users who are authorized to delete
        Map<Id,Account_Delete_User__mdt> mapAcctDeleteUser = new Map<Id, Account_Delete_User__mdt>(); 
        //loop through the users who are authorized to delete and put them in the map we created just before this
        for(Account_Delete_User__mdt AcctDeleteUser : [SELECT id, UserId__c FROM Account_Delete_User__mdt])
        {
            mapAcctDeleteUser.put(AcctDeleteUser.Userid__c, AcctDeleteUser);
        }//end for
        
        //loop through the records in the trigger and see if the current user is authorized to delete.
        for(Account a: acct)
        {
            if(mapAcctDeleteUser.keyset().contains(uid)== false)
            {
            a.addError('You are not authorized to remove Accounts from Salesforce. Please email Salesforce.admin@XXXXX.net to have record removed.');
            }//end if
        }//end for           
     }//end method
  }
The following is the test class I have so far, but it gets the error: System.AsyncException: Metadata cannot be deployed from within a test

But I do not know how to fix:
@isTest
public class Account_Trigger_HandlerTest {
  
    public static testMethod void OnDelete_AccountTest()
    {
        Profile p2 = [SELECT id FROM Profile WHERE Name ='Standard User'];
        
        User usr2 = new User (LastName ='Boris',
                              FirstName ='Badenov',
                              Email = 'boris.badenov@bullwinkleshow.com',
                              Username = 'boris.badenov@bullwinkleshow.com',
                              Alias = 'boris',
                              Profileid = p2.Id,
                              TimeZoneSidKey ='GMT' ,
                              LanguageLocaleKey = 'en_US',
                              EmailEncodingKey = 'UTF-8',
                              LocaleSidKey = 'en_US');
        insert usr2;
    //---------------------------------------------------------------------
    //https://ashwanisoni.wordpress.com/2017/05/02/create-or-update-custom-metadata-type-via-apex-code-salesforce-summer-17/
        // Set up custom metadata to be created in the subscriber org.
    Metadata.CustomMetadata customMetadata =  new Metadata.CustomMetadata();
    customMetadata.fullName = 'Account_Delete_User';
    customMetadata.label = 'User';

    Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
    customField.field = 'UserId__c';
    customField.value = usr2.id;

    customMetadata.values.add(customField);

    Metadata.DeployContainer mdContainer = new Metadata.DeployContainer();
    mdContainer.addMetadata(customMetadata);

    // Setup deploy callback, MyDeployCallback implements
    // the Metadata.DeployCallback interface (code for
    // this class not shown in this example)
    CustomMetadataCallback callback = new CustomMetadataCallback();

    // Enqueue custom metadata deployment
    // jobId is the deployment ID
    Id jobId = Metadata.Operations.enqueueDeployment(mdContainer, callback);
    //----------------------------------------------------------------------
        Profile p = [SELECT id FROM Profile WHERE Name ='Standard User'];
        
        User usr1 = new User (LastName ='Fatale',
                              FirstName ='Natasha',
                              Email = 'natasha.fatele@bullwinkleshow.com',
                              Username = 'natasha.fatele@bullwinkleshow.com',
                              Alias = 'natas',
                              Profileid = p.Id,
                              TimeZoneSidKey ='GMT' ,
                              LanguageLocaleKey = 'en_US',
                              EmailEncodingKey = 'UTF-8',
                              LocaleSidKey = 'en_US');
        insert usr1;
        Account acct2 = New Account(Name='Snagglepuss', Type='Prospect', SSN__c = '12385678', CreatedById = usr1.id);
        insert acct2;
        Test.startTest();
            Database.DeleteResult result = Database.delete(acct2,false);
            System.assert(!result.isSuccess());
        Test.stopTest();
        
        
    }
}
The following is the callback function that the test code references:
public class CustomMetadataCallback implements Metadata.DeployCallback {
    public void handleResult(Metadata.DeployResult result,
                             Metadata.DeployCallbackContext context) {
        if (result.status == Metadata.DeployStatus.Succeeded) {
            System.debug('success: '+ result);
        } else {
            // Deployment was not successful
            System.debug('fail: '+ result);
        }                       
    }
//https://ashwanisoni.wordpress.com/2017/05/02/create-or-update-custom-metadata-type-via-apex-code-salesforce-summer-17/  
}
I am just missing the boat on how to fix this.

Really would appreciate any help.

 
I have a batch class that I have tested in a Sandbox with 10,000 records and it appears to be functioning as it should. My issue now is I can not seem to figure out the Test Class.

What basically happens is we have Sales Agents that are created as part of a custom Object. I go to the Account that these Sale Agents records are related to and create Accounts for each one and match the original Sales Agent record to the new Account.

I store the id for the Account in a Custom Setting.

The Batch Process:
global class CreateAccountsNewlyCreatedDSS implements 
    Database.Batchable<sObject>, Database.Stateful {
    
    public disc2__c disc2 = disc2__c.getValues('DSS Agent Codes Account ID');
    global ID AcctID = disc2.DSS_AccountID__c;
    
    // instance member to retain state across transactions
    global Integer recordsProcessed = 0;
    global Database.QueryLocator start(Database.BatchableContext bc) 
    {
        return Database.getQueryLocator(
            'SELECT id ,'               +
                    'ssn__c,'           +
                    'agent__c,'         + 
                    'ag_first_name__c,' +
                    'ag_last_name__c,'  +
                    'agent_name__c '    +
            'FROM agent_code__c '       +
            'WHERE agent__c =: AcctID'
        ); 
    }
    global void execute(Database.BatchableContext bc, List<Agent_Code__c> scope)
    {
        // process each batch of records
        map<string, account> ma = new map<string, account>();
        for (agent_code__c ac: scope) 
        {
            
                account a = new account();
                a.AG_First_Name__c = ac.ag_first_name__c;
                a.AG_Last_Name__c  = ac.ag_last_name__c;
                a.Name             = ac.Agent_Name__c;
                a.SSN__c           = ac.ssn__c;
                ma.put(a.SSN__c, a);
                
                
                
                recordsProcessed = recordsProcessed + 1;
        }
        Database.UpsertResult[] upsAgtCode = Database.upsert(ma.values(),account.fields.ssn__c, false);
        for(agent_code__c ac1: scope)
        {
            ac1.agent__c=ma.get(ac1.ssn__c).id;
        }
        database.update(scope, false);
        
        
    }
       
        
    global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + ' records processed. Shazam!');
        List<Agent_Code__c> AgtCde = [SELECT id, Agent__c, Name FROM Agent_Code__c WHERE Agent__c =: AcctID];
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems,
            CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        // call some utility to send email
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for(User usr: [SELECT id, email FROM User WHERE Profile.Name = 'System Administrator'])
        {
            
            
            System.debug('User Array of the System Administrators '+ usr);
            Messaging.SingleEmailMessage mail2 = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            sendTo.add(usr.Email);
            mail2.setToAddresses(sendTo);
            List<String> ccTo = new List<String>();
            ccTo.add('robert.d@XXX.com');
            mail2.setCcAddresses(ccTo);
            mail2.setSubject('Apex Batched Job - Move Contacts from Distribution Supply Source Account');
            string body = 'The Apex Batch Job named \'CreateAccountsNewlyCreatedDSS.apxc\' moves agent codes ';
                   body += 'from the DSS Account and creates them as their own accounts. This process runs daily ';
                   body += 'and was once a manual process. ';
                   body += 'Below are the specifics of this batch job : <br/><br/>';
            body += 'Apex Job '+ job + '<br/><br/>';
            if(AgtCde.size() > 0)
            {
                body += 'List of Agent Codes that were not moved and need to be investigated : <br/><br/> ';
                for(Agent_Code__c ac: AgtCde)
                {
                    body += '    This record id <b>' + ac.Id + '</b> was not moved. <br/>';
                    body += '    This is the Agent Code that did not process <b>'+ ac.Name+'</b>.<br/><br/>';
                }
            } else 
            {
                body += '<b>No Records were left behind</br>. All records matched the requirements to create Accounts. ';    
            }
            
            body += '<br/><br/>For more information on this process and how it should work go to the Admin Routines in ';
            body += 'New Parts Salesforce Org and go to #NewAgentCodes:MovefromTheNewAgentCodeAccountBucket .';
            mail2.setHtmlBody(body);
            mails.add(mail2);
            
        }
        Messaging.sendEmail(mails);
    }    
}

Batch Schedule:
global class MoveAgentCodesBatchScheduler  implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        // Implement any logic to be scheduled
       
        // We now call the batch class to be scheduled
        CreateAccountsNewlyCreatedDSS b = new CreateAccountsNewlyCreatedDSS();
       
        //Parameters of ExecuteBatch(context,BatchSize)
        database.executebatch(b,2000);
    }
   
}
Test Class that not only seems to have to many DML statements but also de-reference a null object.
@isTest
public class CreateAccountsNewlyCreatedDSS_Batch_Test 
{
    
    @testSetup
    
    static void setup()
    {
        Account acct = New Account(Name= 'Test Account'
        );
        insert acct;
        
        List<Agent_Code__c> lstAgtCd = new List<Agent_Code__c>();
        for(Integer i=0; i<20; i++)
        {
            lstAgtCd.add(new Agent_Code__c(Agent__c = acct.id,
                                           Name = 'AgentTestCode'+i,
                                           ag_first_name__c = 'AgentFirstTestName'+i,
                                           ag_last_name__c = 'AgentLastTestName'+i,
                                           ssn__c = i+'2341'
            ));
        }
        
        insert lstAgtCd;      
    }
            static testmethod void test()
        {
            Test.startTest();
            CreateAccountsNewlyCreatedDSS testBatch = new CreateAccountsNewlyCreatedDSS();
            Id batchprocessId = Database.executeBatch(testBatch,10000);
            Test.stopTest();
            
        }
    
}
Your help is appreciated. Thank you in advance for any insight.

Robert

 
I am certain that I am missing something, and am hoping someone can point me to the correct instructions. I did the Trailhead to create a custom homepage, Lightning App Builder, Building a Custom Home Page for Lightning Experience. But ever since then the Home icon on the sidebar is gone and the user goes directly to the Opportunity tab / page.

Can anyone help. I looked and looked but could not find anything that worked for me. Thanks in advance.

Robert
 
I am attempting to add a tab to a custom visual force page someone put together from what appears is this article http://ttps://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_quick_start_tabs.htm

When I go to the classic Salesforce view the object shows in as a related list to Accounts.
When I remove any of the other tabs in the code they disappear, but when I copy a tab's code and copy it into the code with a new id name it does not appear as a new tab.
I have checked object permissions and pagelayout assignment and they seem correct.

Question : Why is my tab (named CS_Division) not showing up? I am not sure how much of the code you need to see so I will put the tab code and then the entire code in hopes it makes it easier to read.
 
<apex:tab label="C S Div" name="CS_Division" id="CSD">
        <apex:relatedList subject="{!account}" list="CS_Rev_Div2s__r"
               rendered="{!$ObjectType.CS_Rev_Div2__c.accessible}"/>
</apex:tab>

The entire page code:
 
<apex:page standardController="Account" action="{!IF(NOT(CONTAINS($Profile.Name,'LEX')),
    null, 
    urlFor($Action.Account.View, account.id,
    null, true))}"
    showHeader="true" tabStyle="account" >
<apex:form >
<apex:inputfield value="{!Account.hidden__c}" style="width:1px; height: 1px" required="false" onfocus="true" />
</apex:form>
<!-- chatter component for follow link only - using the feed component instead
<chatter:follow entityId="{!Account.ID}"/>
-->
<chatter:feedWithFollowers entityId="{!Account.Id}" />
   <style>
      .activeTab {background-color: #236FBD; color:white; 
         background-image:none}
      .inactiveTab { background-color: lightgrey; color:black; 
         background-image:none}
   </style>
   
  
      <apex:sectionheader title="{!account.Name}"/> 

        <apex:outputpanel rendered="{!CASESAFEID(Account.RecordTypeId)='012000000003LLAAQ'}">

      <apex:tabPanel switchType="client" selectedTab="tabdetails" id="AccountTabPanel" tabClass="activeTab" inactiveTabClass="inactiveTab">   
      <apex:tab label="{!$Label.Details}" name="AccDetails" id="tabdetails" >
    
          <apex:detail subject="{!account.Id}" relatedList="false" title="false" inlineEdit="true"/>

       
          <apex:relatedList subject="{!account}" list="Interviews__r" 
                     rendered="{!$ObjectType.Exit_Interview__c.updateable}"/>
                      <apex:outputLink value="/{!Account.PreviousMORID__c}/e?clone=1&retURL=%2F" id="theLink" rendered="{!account.PreviousMORBID__c != ''}" target="_parent" >MOR from Previous</apex:outputLink>

 <apex:outputLink value="/apex/morbnew?CF00N00N3030303000000008stWP={!account.Name}&CF00N3030303009stWP_lkid={!account.Id}&scontrolCaching=1&retURL=%2Fapex%2FtabbedAccount%3Fid%3D{!account.Id}%26sfdc.override%3D1&sfdc.override=1" rendered="{!account.PreviousmorBID__c == ''}" target="_parent" >Monthly Operations Report</apex:outputLink>
&nbsp;
<apex:outputLink value="/apex/EditableContactList?ID={!Account.ID}" id="SurveyPLan" rendered="{!account.Submit_Survey_Plan_October_2015__c != TRUE}" target="_parent" >Survey</apex:outputLink>
      </apex:tab>
      
     
     <apex:tab label="{!$Label.Account_Team}" name="AccountTeamMembers" id="tabAccountTeam">
      <apex:relatedList subject="{!account}" list="accountteammembers" />
      </apex:tab>
      

      <apex:tab label="{!$Label.Contacts}" name="Contacts" id="tabContact">
      <apex:relatedList subject="{!account}" list="contacts" 
       rendered="{!$ObjectType.contact.accessible}"/>
      </apex:tab>
      
      
      
       <apex:tab label="{!$Label.Opportunities}" name="Opportunities" id="tabOpp">
         <apex:relatedList subject="{!account}" list="opportunities" 
         rendered="{!$ObjectType.opportunity.accessible}"/>
      </apex:tab>
      
      <apex:tab label="{!$Label.Notes_and_Attachments}" name="NotesAttachments" id="tabNotesAttachments">
      <apex:relatedList subject="{!account}"  list="CombinedAttachments" />
      </apex:tab>
      
      <apex:tab label="{!$Label.Open_Activities}" name="OpenActivities" id="tabOpenAct">
         <apex:relatedList subject="{!account}" list="OpenActivities" />
      </apex:tab>
      
      <apex:tab label="{!$Label.Activity_History}" name="History" id="tabActivityHistory">
         <apex:relatedList subject="{!account}" list="ActivityHistories" />
            </apex:tab>
            
            <apex:tab label="Account History" name="Field History" id="fieldhistory">
      <apex:outputLink value="/_ui/common/history/ui/EntityHistoryFilterPage?id={!account.id}">Click to view Account History</apex:outputLink>
        </apex:tab>

           

       <apex:tab label="Account Alerts" name="AcctAlerts" id="tabAccountAlerts">
         <apex:relatedList subject="{!account}" list="AcctAlerts__r" 
             rendered="{!$ObjectType.Acct_Alert__c.accessible}"/>
         
      </apex:tab>
      <apex:tab label="Wallet Share" name="WalletShare" id="tabWalletShare">
         <apex:relatedList subject="{!account}" list="Wallet__r" 
         rendered="{!$ObjectType.WalletShare__c.accessible}"/>
      </apex:tab>
      
      
      <apex:tab label="Client Concerns" name="CSurveys" id="CSurveys">
         <apex:relatedList subject="{!account}" list="CSurveys__r" 
            rendered="{!$ObjectType.CSurvey__c.accessible}"/> 
            <apex:relatedList subject="{!account}" list="CPlans__r" 
            rendered="{!$ObjectType.CPlan__c.accessible}"/>
              <apex:relatedList subject="{!account}" list="CForms__r" 
            rendered="{!$ObjectType.CForm__c.accessible}"/>
      </apex:tab>    

    <apex:tab label="Monthly Operations Reporting" name="Weekly_Account_Updates1" id="MOR">
     <center>

<!-- NEW CODE BELOW -->
    <apex:tab label="C S Div" name="CS_Division" id="CSD">
        <apex:relatedList subject="{!account}" list="CS_Rev_Div2s__r"
               rendered="{!$ObjectType.CS_Rev_Div2__c.accessible}"/>
    </apex:tab>
</apex:page>
I appreciate you taking a look at this and would appreciate all feedback.

Thank you.

Robert
 
I am attempting to create a Visualforce page that allows the user to select a contact from a lookup field on a custom object to the contacts object. I am surely missing something silly. Your help would be super.
 
<apex:page standardController="Contact_Plan__c">
    <apex:pageBlock >
        <apex:pageBlockSection>
            <apex:form>
            
                <apex:inputField value="{! Contact_Plan__c.name}"/>     
                <apex:inputField value="{! Contact_Plan__r.Contact.Name}"/>
            </apex:form>
       </apex:pageBlockSection>
</apex:page>

The page would allow for the individual to enter the Contact Plan Name and then Select a Contact from the Contact Object. I have created a custom object called Contact_Plan__c.

Your help is greatly appreciated in advance.

Robert
I am new to the Apex and am see if someone can help me understand how I go about testing a method that gets its data from a List that is an sObject when the parameter that I pass in is the String of the query. I am having trouble figuring out how to get the execute method to test successfully.

The following is my Apex Batchable Class:
 
global class MyBatchJob implements Database.Batchable<sObject>{

    global string query;

       
    global MyBatchJob(){
        String query = 'SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                              
                                   'FROM Opportunity';     
    } 

    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('Started the Batch job to copy key Opportunity Record fields.');
        System.debug('The current Batch unique identifier for this job is : '+ BC.getJobId());
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<Opportunity> scope) {
        System.debug('Executed the Batch job to copy Opportunity Records.');
        System.debug('The current Batch unique identifier for this job is : '+ BC.getJobId());
        List<Opportunity_Snapshot__c> snapList = new List<Opportunity_Snapshot__c>();

                 //Assuming the snapshots you want are of Contact data
		        for(Opportunity opp: scope) {
                 //create a sObject NOT an sObject List to hold the data until I add to the List with snapList.add(snap)
                 //This is a lot like creating a JSON framework in Javascript
                    Opportunity_Snapshot__c snap = new Opportunity_Snapshot__c();
            
                    //start adding to the snap variable from the query results
                    snap.Ss_Account_Id__c                       = opp.AccountId;
                    snap.Ss_Account_Industry__c                 = opp.Account.Industry;
                    snap.Ss_Account_Name__c                     = opp.Account.Name;
                    snap.Ss_Account_Owner_Id__c                 = opp.Account.OwnerId;
                    snap.Ss_Account_Owner_Name__c               = opp.Account.Owner.Firstname + ' ' + opp.Owner.Lastname;
                    snap.Ss_Account_Recordtype_Id__c            = opp.account.recordtypeid;
                    snap.Ss_Account_Recordtype_Name__c          = opp.account.recordtype.name;
                    snap.Ss_Account_Type__c                     = opp.Account.Type;
                    snap.Ss_Opportunity_Amount__c               = opp.Amount;
                    snap.Ss_Opportunity_Annualized_Revenue__c   = opp.Annualized_Revenue__c;
                    snap.Ss_Opportunity_Level_of_Effort__c      = opp.Level_of_Effort__c;
                    snap.Ss_Opportunity_Name__c                 = opp.Name;
                    snap.Ss_Opportunity_Owner_Id__c             = opp.Ownerid;
                    snap.Ss_Opportunity_Owner_Name__c           = opp.Owner.firstname + ' ' + opp.Owner.lastname;
                    snap.Ss_Opportunity_Solution_Complexity__c  = opp.Solution_Complexity__c;
                    snap.Ss_Opportunity_Stage_Name__c           = opp.StageName;
                    snap.Ss_Opportunity_Total_FTE__c            = opp.FTEs__c;
                    snap.Ss_Opportunity_Total_Seats__c          = opp.TotalNumberofSeats__c;

                    //Let's now add these variables to the list to be inserted at the end of the loop.
                    snapList.add(snap); 
  
          
        } 
        insert snapList; 
   }

   global void finish(Database.BatchableContext BC) {
        System.debug(LoggingLevel.WARN,'Batch Job is Complete!!!!!');
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'any@gmail.com', 'any@outlook.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Email Batch Worked');
        mail.setPlainTextBody ('Batch Job worked');
    }
}
So far I have 29% successfully tested.
 
@isTest
public class TestMyBatchJob {
    public static testmethod void TestBatchJob(){
        Test.startTest();
        MyBatchJob bj = new MyBatchJob();
        bj.query=      'SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                                
                                   'FROM Opportunity';        
        ID batchprocessid = Database.executeBatch(bj);

        Test.stopTest();
   
       }


	public static void testBatch() 
	     {
	        List<Opportunity_Snapshot__c> testSnaplist = new List<Opportunity_Snapshot__c>();
        
            Opportunity_Snapshot__c testSnap = new Opportunity_Snapshot__c();
		    for(Integer i = 0 ; i < 200; i++){
		        testSnap.Ss_Account_Id__c                       = 'ID123425'+i;
                testSnap.Ss_Account_Industry__c                 = 'Offshoring and Nearshoring Test';
                testSnap.Ss_Account_Name__c                     = 'Test Account Name'+i;
                testSnap.Ss_Account_Owner_Id__c                 = 'Account Owner Test '+i;
                testSnap.Ss_Account_Owner_Name__c               = 'Test J Tester '+i*157469;
                testSnap.Ss_Account_Recordtype_Id__c            = 'Record Type Id123456789012345678901234567890123456789' +i;
                testSnap.Ss_Account_Recordtype_Name__c          = 'Record Type Name ' +i;
                testSnap.Ss_Account_Type__c                     = 'Account Prospect '+i;
                testSnap.Ss_Opportunity_Amount__c               =  451+i;
                testSnap.Ss_Opportunity_Annualized_Revenue__c   = 12+i;
                testSnap.Ss_Opportunity_Level_of_Effort__c      = 26+i;
                testSnap.Ss_Opportunity_Name__c                 = 'Test Opportunity Name ' +i;
                testSnap.Ss_Opportunity_Owner_Id__c             = 'Opportunity Owner Test ID'+i;
                testSnap.Ss_Opportunity_Owner_Name__c           = 'Sammy the Tester';
                testSnap.Ss_Opportunity_Solution_Complexity__c  = 'High';
                testSnap.Ss_Opportunity_Stage_Name__c           = 'Test Opportunity Stage ' +i;
                testSnap.Ss_Opportunity_Total_FTE__c            = 12;
                testSnap.Ss_Opportunity_Total_Seats__c          = 37;    
            
                testSnaplist.add(testSnap);

		}

		insert testSnaplist;
	   
		Test.StartTest();
               MyBatchJob bj2 = new MyBatchJob();
        
		ID batchprocessid = Database.executeBatch(bj2);
		   
		Test.StopTest();
		
		
	}
}
Your help is greatly appreciated.

Robert

 
Hello,

I am trying to pull data from the Account and Opportunity Objects and insert into a Custom Object named RD_SnapShot_Opportunity. I have the SOQL Query assigned to a list. I think I need to loop through the list and assign the elements in that list to another list and when done insert with a DML statement.

I can not figure out how to take a sObject of Opportuntity that results from the SOQL query and assign to a new List to insert into the table.

Please point me in the right direction. Have I assigned the Opportunity list resulting from the SOQL to the wrong type of sObject?
 
public class RD_SnapshotOpportunityAggregation {
    //To take key information from the Opportunity Object on a schedule to store in the OpportunitySnapshot Object
    
    public static void transferOpportunityData() {
        List<Opportunity> oppList = [ SELECT account.id, 
                                   account.name, 
                                   account.type, 
                                   account.industry, 
                                   account.recordtypeid, 
                                   account.recordtype.name, 
                                   account.ownerId, 
                                   Owner.firstname, 
                                   Owner.lastname, 
                                   Name, 
                                   StageName, 
                                   FTEs__c, 
                                   TotalNumberofSeats__c, 
                                   Amount, 
                                   Annualized_Revenue__c   
                                   FROM Opportunity
                                   ];
        
        // is the RD_Snapshot_Opportunity__c the correct object 
        for(RD_Snapshot_Opportunity__c snap: oppList) {
            //not sure how to assign values to the appropriate field in the snap sObject        
            snap.SsAccountId = oppList[1];
            snap.SsAccountName = oppList[2];
            snap.SsAccountType = oppList[3];
            snap.SsAccountIndustry = oppList[4];
            
            //and each field as we go down the list.
            
        }
        insert opp
    }
}

Any help would be appreciated. Thank you

Thanks in advance,
Robert

Hi All

 

At present when I am exporting or taking a printable view of any report, the downloaded file is named as say for ex: "report1369745790672".

 

I want to give some meaningful name to it while exporting itself. I do not wish to manually rename it post its download.

 

Is it possible through apex?

 

Please help. URGENTLY REQUIRED.

 

Thanks

Shiv

Hello, 

I have a controller which includes serveral UPDATE statements - however I am running into a code coverage error and I think it is because my UPDATE is not covered in my test class.  I tried to add it but I ran into an error.  What is the best way for me to beef up the test class for the controller below?  Thanks in advance!
 
CLASS:

public class R2MPipeLineController{

    public List<Opportunity> listOfLive {get; set;}
    public List<Opportunity> listOfViability {get; set;}
    public List<Opportunity> listOfLaunchPad {get; set;}
    public List<Opportunity> listOfContractSent {get; set;}
    public List<Opportunity> listOfQualified {get; set;}
    public Opportunity Live {get; set;}
    public Opportunity Viability {get; set;}
    public Opportunity LaunchPad {get; set;}
    public Opportunity ContractSent {get; set;}
    public Opportunity Qualified {get; set;}
    
    public PageReference saveCS(){
    UPDATE listOfContractSent;
    return null;
    }
    
    public PageReference saveVI(){
    UPDATE listOfViability;
    return null;
    }
    
    public PageReference saveLP(){
    UPDATE listOfLaunchPad;
    return null;
    }
    
    public PageReference saveQD(){
    UPDATE listOfQualified;
    return null;
    }
    
    public String getName(){
        return 'R2MPipeLineController';
        }
    
public R2MPipeLineController() {
    listofLive = [Select id, name, CreatedDate, Company_Name__c, Next_Step__c, Vertical__c, Weeks_Live__c, Days_Since_Last_Modified__c, Contract_SENT__c, NextStep, LeadSource, Probability, Spend_Last_Week__c, Spend_Last_30_Days__c, Owner_Name__c, Revenue_All_Time__c from Opportunity WHERE StageName = 'Live' ORDER BY Weeks_Live__c DESC];
    listOfViability = [Select id, name, Amount, Projected_Revenue__c, CreatedDate, Company_Name__c, Next_Step__c, Vertical__c, Weeks_Live__c, Days_Since_Last_Modified__c, Contract_SENT__c, NextStep, LeadSource, Probability, Spend_Last_Week__c, Spend_Last_30_Days__c, Owner_Name__c, Revenue_All_Time__c from Opportunity WHERE StageName = 'Viability' ORDER BY Days_Since_Last_Modified__c DESC];
    listOfLaunchPad = [Select id, name, Amount, Projected_Revenue__c, CreatedDate, Company_Name__c, Next_Step__c, Vertical__c, Weeks_Live__c, Days_Since_Last_Modified__c, Contract_SENT__c, NextStep, LeadSource, Probability, Spend_Last_Week__c, Spend_Last_30_Days__c, Owner_Name__c, Revenue_All_Time__c from Opportunity WHERE StageName = 'Launch Pad' ORDER BY Days_Since_Last_Modified__c DESC];
    listOfContractSent = [Select id, name, Amount, Projected_Revenue__c, CreatedDate, Company_Name__c, Next_Step__c, Vertical__c, Weeks_Live__c, Days_Since_Last_Modified__c, Contract_SENT__c, NextStep, LeadSource, Probability, Spend_Last_Week__c, Spend_Last_30_Days__c, Owner_Name__c, Revenue_All_Time__c, Contract_Age__c from Opportunity WHERE StageName = 'Contract Sent' ORDER BY Contract_Age__c ASC];
    listOfQualified = [Select id, name, Amount, Projected_Revenue__c, CreatedDate, Company_Name__c, Next_Step__c, Vertical__c, Weeks_Live__c, Days_Since_Last_Modified__c, Contract_SENT__c, NextStep, LeadSource, Probability, Spend_Last_Week__c, Spend_Last_30_Days__c, Owner_Name__c, Revenue_All_Time__c from Opportunity WHERE StageName = 'Qualified' ORDER BY Probability DESC]; 

}
}

And here is my test class: 
 
@isTest(seeAllData = false)
public class R2MPipeLineControllerTest{
    // Unit test Method
    static testmethod void UnitTest() {
        //Create your buyer record with required field
        //Opportunity o = new Opportunity(StageName = 'Qualified');
        //insert o;
        test.startTest();
           R2MPipeLineController qo = new R2MPipeLineController();
        test.stopTest();
    }   
}

 

Kindly provide a solution to the following : 

 

Details

I as a product manager require a custom search page for my salesforce CRM account. I don’t want to use the standard search functionality for this. Here is what I want to be done:

 

    1. On the VF page, create accustom “search” button and a checkbox with the name “limit to accounts I own”
    2. I should be able to enter and search on the following fields (these are the search criteria fields):
      1. Account name(standard field)
      2. Industry (standard field)
      3. Rating(standard field)
      4. Account  region(custom field)
      5. Account priority(custom filed)
      6. Account summary(text)
    3. The search functionality should be a logical OR of all the above combinations.
    4. The correct search results should be displayed ON THE SAME PAGE only after clicking the “submit” button.Display columns should have these fields: account name, industry, rating, account priority.
    5. If the checkbox “limit to accounts I Own” is checked before clicking on search the display only those accounts where the owner=current logged in user. 

I have developed the following code:

 

<apex:page Controller="AccountSearch">
<apex:form >
 
<apex:outputPanel layout="block">
<label for="checkbox"> Limit to Account I own: </label>
<input id="checkbox" type="checkbox"/>
</apex:outputPanel>
<apex:commandButton action="{!search}" value="Search"/>
 
<apex:pageBlock mode="edit" id="block">
         <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
               <apex:outputLabel for="searchText">Search Text</apex:outputLabel>
               <apex:panelGroup >
                  <apex:inputText id="searchText" value="{!searchText}"/>
                  <apex:commandButton value="Submit" action="{!search}" 
                                      rerender="block"/>
               </apex:panelGroup>
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
 <apex:actionStatus id="status" startText="requesting..."/>
<apex:pageBlockSection title="Results" id="results" columns="1">
           <apex:pageBlockTable value="{!results}" var="a"
                               rendered="{!NOT(ISNULL(results))}">
                               
              <apex:column value="{!a.Name}"/>
              <apex:column value="{!a.Industry}"/>
              <apex:column value="{!a.Rating}"/>
              <apex:column value="{!a.Account_Region__c}"/>
              <apex:column value="{!a.Account_Priority__c}"/>
              <apex:column value="{!a.Account_Summary__c}"/>
   </apex:pageBlockTable>
   </apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
__________________________________________________________________________________________
 
public class AccountSearch {
 
  String searchText;
   List<Account> results;
 
public String getSearchText() {
      return searchText;
   }
 
   public void setSearchText(String s) {
      searchText = s;
   }
 
   public List<Account> getResults() {
      return results;
   }
    public PageReference search() {
    results = (List<Account>)[FIND :searchText RETURNING Account(Name, Industry, Rating, Account_Region__c, Account_Priority__c, Account_Summary__c)][0];  
        return null;
    }
 
}
Please provide the necessary modifications
  • May 27, 2013
  • Like
  • 3