Apex – DML

Apex – DML ”; Previous Next In this chapter, we will discuss how to perform the different Database Modification Functionalities in Salesforce. There are two says with which we can perform the functionalities. DML Statements DML are the actions which are performed in order to perform insert, update, delete, upsert, restoring records, merging records, or converting leads operation. DML is one of the most important part in Apex as almost every business case involves the changes and modifications to database. Database Methods All operations which you can perform using DML statements can be performed using Database methods as well. Database methods are the system methods which you can use to perform DML operations. Database methods provide more flexibility as compared to DML Statements. In this chapter, we will be looking at the first approach using DML Statements. We will look at the Database Methods in a subsequent chapter. DML Statements Let us now consider the instance of the Chemical supplier company again. Our Invoice records have fields as Status, Amount Paid, Amount Remaining, Next Pay Date and Invoice Number. Invoices which have been created today and have their status as ”Pending”, should be updated to ”Paid”. Insert Operation Insert operation is used to create new records in Database. You can create records of any Standard or Custom object using the Insert DML statement. Example We can create new records in APEX_Invoice__c object as new invoices are being generated for new customer orders every day. We will create a Customer record first and then we can create an Invoice record for that new Customer record. // fetch the invoices created today, Note, you must have at least one invoice // created today List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c, createdDate FROM APEX_Invoice__c WHERE createdDate = today]; // create List to hold the updated invoice records List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>(); APEX_Customer__c objCust = new APEX_Customer__C(); objCust.Name = ”Test ABC”; //DML for Inserting the new Customer Records insert objCust; for (APEX_Invoice__c objInvoice: invoiceList) { if (objInvoice.APEX_Status__c == ”Pending”) { objInvoice.APEX_Status__c = ”Paid”; updatedInvoiceList.add(objInvoice); } } // DML Statement to update the invoice status update updatedInvoiceList; // Prints the value of updated invoices System.debug(”List has been updated and updated values are” + updatedInvoiceList); // Inserting the New Records using insert DML statement APEX_Invoice__c objNewInvoice = new APEX_Invoice__c(); objNewInvoice.APEX_Status__c = ”Pending”; objNewInvoice.APEX_Amount_Paid__c = 1000; objNewInvoice.APEX_Customer__c = objCust.id; // DML which is creating the new Invoice record which will be linked with newly // created Customer record insert objNewInvoice; System.debug(”New Invoice Id is ”+objNewInvoice.id+” and the Invoice Number is” + objNewInvoice.Name); Update Operation Update operation is to perform updates on existing records. In this example, we will be updating the Status field of an existing Invoice record to ”Paid”. Example // Update Statement Example for updating the invoice status. You have to create and Invoice records before executing this code. This program is updating the record which is at index 0th position of the List. // First, fetch the invoice created today List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c, createdDate FROM APEX_Invoice__c]; List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>(); // Update the first record in the List invoiceList[0].APEX_Status__c = ”Pending”; updatedInvoiceList.add(invoiceList[0]); // DML Statement to update the invoice status update updatedInvoiceList; // Prints the value of updated invoices System.debug(”List has been updated and updated values of records are” + updatedInvoiceList[0]); Upsert Operation Upsert Operation is used to perform an update operation and if the records to be updated are not present in database, then create new records as well. Example Suppose, the customer records in Customer object need to be updated. We will update the existing Customer record if it is already present, else create a new one. This will be based on the value of field APEX_External_Id__c. This field will be our field to identify if the records are already present or not. Note − Before executing this code, please create a record in Customer object with the external Id field value as ”12341” and then execute the code given below − // Example for upserting the Customer records List<apex_customer__c> CustomerList = new List<apex_customer__c>(); for (Integer i = 0; i < 10; i++) { apex_customer__c objcust=new apex_customer__c(name = ”Test” +i, apex_external_id__c=”1234” +i); customerlist.add(objcust); } //Upserting the Customer Records upsert CustomerList; System.debug(”Code iterated for 10 times and created 9 records as one record with External Id 12341 is already present”); for (APEX_Customer_c objCustomer: CustomerList) { if (objCustomer.APEX_External_Id_c == ”12341”) { system.debug(”The Record which is already present is ”+objCustomer); } } Delete Operation You can perform the delete operation using the Delete DML. Example In this case, we will delete the invoices which have been created for the testing purpose, that is the ones which contain the name as ”Test”. You can execute this snippet from the Developer console as well without creating the class. // fetch the invoice created today List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c, createdDate FROM APEX_Invoice__c WHERE createdDate = today]; List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>(); APEX_Customer__c objCust = new APEX_Customer__C(); objCust.Name = ”Test”; // Inserting the Customer Records insert objCust; for (APEX_Invoice__c objInvoice: invoiceList) { if (objInvoice.APEX_Status__c == ”Pending”) { objInvoice.APEX_Status__c = ”Paid”; updatedInvoiceList.add(objInvoice); } } // DML Statement to update the invoice status update updatedInvoiceList; // Prints the value of updated invoices System.debug(”List has been updated and updated values are” + updatedInvoiceList); // Inserting the New Records using insert DML statement APEX_Invoice__c objNewInvoice = new APEX_Invoice__c(); objNewInvoice.APEX_Status__c = ”Pending”; objNewInvoice.APEX_Amount_Paid__c = 1000; objNewInvoice.APEX_Customer__c = objCust.id; // DML which is creating the new record insert objNewInvoice; System.debug(”New Invoice Id is” + objNewInvoice.id); // Deleting the Test invoices from Database // fetch the invoices which are created for Testing, Select name which Customer Name // is Test. List<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c WHERE APEX_Customer__r.Name = ”Test”]; // DML Statement to delete the Invoices delete invoiceListToDelete; System.debug(”Success, ”+invoiceListToDelete.size()+” Records has been deleted”); Undelete Operation You can undelete the record which has been deleted and is present in Recycle bin. All the relationships which the deleted record has, will also

Apex – Loops

Apex – Loops ”; Previous Next Loops are used when a particular piece of code should be repeated with the desired number of iteration. Apex supports the standard traditional for loop as well as other advanced types of Loops. In this chapter, we will discuss in detail about the Loops in Apex. A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages − The following tables lists down the different Loops that handle looping requirements in Apex Programming language. Click the following links to check their detail. Sr.No. Loop Type & Description 1 for loop This loop performs a set of statements for each item in a set of records. 2 SOQL for loop Execute a sequence of statements directly over the returned set o SOQL query. 3 Java-like for loop Execute a sequence of statements in traditional Java-like syntax. 4 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 5 do…while loop Like a while statement, except that it tests the condition at the end of the loop body. Print Page Previous Next Advertisements ”;

Apex – Interfaces

Apex – Interfaces ”; Previous Next An interface is like an Apex class in which none of the methods have been implemented. It only contains the method signatures, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface. Interfaces are used mainly for providing the abstraction layer for your code. They separate the implementation from declaration of the method. Let”s take an example of our Chemical Company. Suppose that we need to provide the discount to Premium and Ordinary customers and discounts for both will be different. We will create an Interface called the DiscountProcessor. // Interface public interface DiscountProcessor { Double percentageDiscountTobeApplied(); // method signature only } // Premium Customer Class public class PremiumCustomer implements DiscountProcessor { //Method Call public Double percentageDiscountTobeApplied () { // For Premium customer, discount should be 30% return 0.30; } } // Normal Customer Class public class NormalCustomer implements DiscountProcessor { // Method Call public Double percentageDiscountTobeApplied () { // For Premium customer, discount should be 10% return 0.10; } } When you implement the Interface then it is mandatory to implement the method of that Interface. If you do not implement the Interface methods, it will throw an error. You should use Interfaces when you want to make the method implementation mandatory for the developer. Standard Salesforce Interface for Batch Apex SFDC do have standard interfaces like Database.Batchable, Schedulable, etc. For example, if you implement the Database.Batchable Interface, then you must implement the three methods defined in the Interface – Start, Execute and Finish. Below is an example for Standard Salesforce provided Database.Batchable Interface which sends out emails to users with the Batch Status. This interface has 3 methods, Start, Execute and Finish. Using this interface, we can implement the Batchable functionality and it also provides the BatchableContext variable which we can use to get more information about the Batch which is executing and to perform other functionalities. global class CustomerProessingBatch implements Database.Batchable<sobject7>, Schedulable { // Add here your email address global String [] email = new String[] {”[email protected]”}; // Start Method global Database.Querylocator start (Database.BatchableContext BC) { // This is the Query which will determine the scope of Records and fetching the same return Database.getQueryLocator(”Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today && APEX_Active__c = true”); } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>(); for (sObject objScope: scope) { // type casting from generic sOject to APEX_Customer__c APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ; newObjScope.APEX_Customer_Decscription__c = ”Updated Via Batch Job”; newObjScope.APEX_Customer_Status__c = ”Processed”; // Add records to the List updtaedCustomerList.add(newObjScope); } // Check if List is empty or not if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Update the Records Database.update(updtaedCustomerList); System.debug(”List Size ”+updtaedCustomerList.size()); } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // get the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()]; System.debug(”$$$ Jobid is”+BC.getJobId()); // below code will send an email to User about the status mail.setToAddresses(email); // Add here your email address mail.setReplyTo(”[email protected]”); mail.setSenderDisplayName(”Apex Batch Processing Module”); mail.setSubject(”Batch Processing ”+a.Status); mail.setPlainTextBody(”The Batch Apex job processed ”+a.TotalJobItems+”batches with ”+a.NumberOfErrors+”failures”+”Job Item processed are”+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); } // Scheduler Method to scedule the class global void execute(SchedulableContext sc) { CustomerProessingBatch conInstance = new CustomerProessingBatch(); database.executebatch(conInstance,100); } } To execute this class, you have to run the below code in the Developer Console. CustomerProessingBatch objBatch = new CustomerProessingBatch (); Database.executeBatch(objBatch); Print Page Previous Next Advertisements ”;

Apex – Database Methods

Apex – Database Methods ”; Previous Next Database class methods is another way of working with DML statements which are more flexible than DML Statements like insert, update, etc. Differences between Database Methods and DML Statements DML Statements Database Methods Partial Update is not allowed. For example, if you have 20 records in list, then either all the records will be updated or none. Partial update is allowed. You can specify the Parameter in Database method as true or false, true to allow the partial update and false for not allowing the same. You cannot get the list of success and failed records. You can get the list of success and failed records as we have seen in the example. Example − insert listName Example − Database.insert(listName, False), where false indicate that partial update is not allowed. Insert Operation Inserting new records via database methods is also quite simple and flexible. Let us consider the previous scenario wherein, we have inserted new records using the DML statements. We will be inserting the same using Database methods. Example // Insert Operation Using Database methods // Insert Customer Records First using simple DML Statement. This Customer Record will be // used when we will create Invoice Records APEX_Customer__c objCust = new APEX_Customer__C(); objCust.Name = ”Test”; insert objCust; // Inserting the Customer Records // Insert Operation Using Database methods APEX_Invoice__c objNewInvoice = new APEX_Invoice__c(); List<apex_invoice__c> InvoiceListToInsert = new List<apex_invoice__c>(); objNewInvoice.APEX_Status__c = ”Pending”; objNewInvoice.APEX_Customer__c = objCust.id; objNewInvoice.APEX_Amount_Paid__c = 1000; InvoiceListToInsert.add(objNewInvoice); Database.SaveResult[] srList = Database.insert(InvoiceListToInsert, false); // Database method to insert the records in List // Iterate through each returned result by the method for (Database.SaveResult sr : srList) { if (sr.isSuccess()) { // This condition will be executed for successful records and will fetch the ids // of successful records System.debug(”Successfully inserted Invoice. Invoice ID: ” + sr.getId()); // Get the invoice id of inserted Account } else { // This condition will be executed for failed records for(Database.Error objErr : sr.getErrors()) { System.debug(”The following error has occurred.”); // Printing error message in Debug log System.debug(objErr.getStatusCode() + ”: ” + objErr.getMessage()); System.debug(”Invoice oject field which are affected by the error:” + objErr.getFields()); } } } Update Operation Let us now consider our business case example using the database methods. Suppose we need to update the status field of Invoice object but at the same time, we also require information like status of records, failed record ids, success count, etc. This is not possible by using DML Statements, hence we must use Database methods to get the status of our operation. Example We will be updating the Invoice”s ”Status” field if it is in status ”Pending” and date of creation is today. The code given below will help in updating the Invoice records using the Database.update method. Also, create an Invoice record before executing this code. // Code to update the records using the Database methods List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c, createdDate FROM APEX_Invoice__c WHERE createdDate = today]; // fetch the invoice created today List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>(); for (APEX_Invoice__c objInvoice: invoiceList) { if (objInvoice.APEX_Status__c == ”Pending”) { objInvoice.APEX_Status__c = ”Paid”; updatedInvoiceList.add(objInvoice); //Adding records to the list } } Database.SaveResult[] srList = Database.update(updatedInvoiceList, false); // Database method to update the records in List // Iterate through each returned result by the method for (Database.SaveResult sr : srList) { if (sr.isSuccess()) { // This condition will be executed for successful records and will fetch // the ids of successful records System.debug(”Successfully updated Invoice. Invoice ID is : ” + sr.getId()); } else { // This condition will be executed for failed records for(Database.Error objErr : sr.getErrors()) { System.debug(”The following error has occurred.”); // Printing error message in Debug log System.debug(objErr.getStatusCode() + ”: ” + objErr.getMessage()); System.debug(”Invoice oject field which are affected by the error:” + objErr.getFields()); } } } We will be looking at only the Insert and Update operations in this tutorial. The other operations are quite similar to these operations and what we did in the last chapter. Print Page Previous Next Advertisements ”;

Apex – Example

Apex – Example ”; Previous Next Enterprise Application Development Example For our tutorial, we will be implementing the CRM application for a Chemical Equipment and Processing Company. This company deals with suppliers and provides services. We will work out small code snippets related to this example throughout our tutorial to understand every concept in detail. For executing the code in this tutorial, you will need to have two objects created: Customer and Invoice objects. If you already know how to create these objects in Salesforce, you can skip the steps given below. Else, you can follow the step by step guide below. Creating Customer Object We will be setting up the Customer object first. Step 1 − Go to Setup and then search for ”Object” as shown below. Then click on the Objects link as shown below. Step 2 − Once the object page is opened, then click on the ”Create New Object” button as shown below. Step 3 − After clicking on button, the new object creation page will appear and then enter all the object details as entered below. Object name should be Customer. You just have to enter the information in the field as shown in the screenshot below and keep other default things as it is. Enter the information and then click on the ”Save” button − By following the above steps, we have successfully created the Customer object. Creating the Custom Fields for Customer object Now that we have our Customer object set up, we will create a field ”Active” and then you can create the other fields by following similar steps. The Name and API name of the field will be given in the screenshot. Step 1 − We will be creating a field named as ”Active” of data type as Checkbox. Go to Setup and click on it. Step 2 − Search for ”Object” as shown below and click on it. Step 3 − Click on object ”Customer”. Step 4 − Once you have clicked on the Customer object link and the object detail page appears, click on the New button. Step 5 − Now, select the data type as Checkbox and click Next. Step 6 − Enter the field name and label as shown below. Step 7 − Click on Visible and then click Next. Step 8 − Now click on ”Save”. By following the above steps, our custom field ”Active” is created. You have to follow all the above custom field creation steps for the remaining fields. This is the final view of customer object once all the fields are created − Creating Invoice Object Step 1 − Go to Setup and search for ”Object” and then click on the Objects link as shown below. Step 2 − Once the object page is opened, then click on the ”Create New Object” button as shown below. Step 3 − After clicking on the button, the new object creation page will appear as shown in the screenshot below. You need to enter the details here. The object name should be Invoice. This is similar to how we created the Customer object earlier in this tutorial. Step 4 − Enter the information as shown below and then click on the ”Save” button. By following these steps, your Invoice object will be created. Creating the Custom Fields for Invoice object We will be creating the field Description on Invoice object as shown below − Step 1 − Go to Setup and click on it. Step 2 − Search for ”Object” as shown below and click on it. Step 3 − Click on object ”Invoice”. And then click on ”New”. Step 4 − Select the data type as Text Area and then click on Next button. Step 5 − Enter the information as given below. Step 6 − Click on Visible and then Next. Step 7 − Click on Save. Similarly, you can create the other fields on the Invoice object. By this, we have created the objects that are needed for this tutorial. We will be learning various examples in the subsequent chapters based on these objects. Print Page Previous Next Advertisements ”;

Apex – Invoking

Apex – Invoking ”; Previous Next Apex invoking refers to the process of executing the Apex class. Apex class can only be executed when it is invoked via one of the ways listed below − Triggers and Anonymous block A trigger invoked for specified events Asynchronous Apex Scheduling an Apex class to run at specified intervals, or running a batch job Web Services class Apex Email Service class Apex Web Services, which allow exposing your methods via SOAP and REST Web services Visualforce Controllers Apex Email Service to process inbound email Invoking Apex Using JavaScript The Ajax toolkit to invoke Web service methods implemented in Apex We will now understand a few common ways to invoke Apex. From Execute Anonymous Block You can invoke the Apex class via execute anonymous in the Developer Console as shown below − Step 1 − Open the Developer Console. Step 2 − Click on Debug. Step 3 − Execute anonymous window will open as shown below. Now, click on the Execute button − Step 4 − Open the Debug Log when it will appear in the Logs pane. From Trigger You can call an Apex class from Trigger as well. Triggers are called when a specified event occurs and triggers can call the Apex class when executing. Following is the sample code that shows how a class gets executed when a Trigger is called. Example // Class which will gets called from trigger public without sharing class MyClassWithSharingTrigger { public static Integer executeQuery (List<apex_customer__c> CustomerList) { // perform some logic and operations here Integer ListSize = CustomerList.size(); return ListSize; } } // Trigger Code trigger Customer_After_Insert_Example on APEX_Customer__c (after insert) { System.debug(”Trigger is Called and it will call Apex Class”); MyClassWithSharingTrigger.executeQuery(Trigger.new); // Calling Apex class and // method of an Apex class } // This example is for reference, no need to execute and will have detail look on // triggers later chapters. From Visualforce Page Controller Code Apex class can be called from the Visualforce page as well. We can specify the controller or the controller extension and the specified Apex class gets called. Example VF Page Code Apex Class Code (Controller Extension) Print Page Previous Next Advertisements ”;

Apex – Governer Limits

Apex – Governer Limits ”; Previous Next Governor execution limits ensure the efficient use of resources on the Force.com multitenant platform. It is the limit specified by the Salesforce.com on code execution for efficient processing. What are Governor Limits? As we know, Apex runs in multi-tenant environment, i.e., a single resource is shared by all the customers and organizations. So, it is necessary to make sure that no one monopolizes the resources and hence Salesforce.com has created the set of limits which governs and limits the code execution. Whenever any of the governor limits are crossed, it will throw error and will halt the execution of program. From a Developer”s perspective, it is important to ensure that our code should be scalable and should not hit the limits. All these limits are applied on per transaction basis. A single trigger execution is one transaction. As we have seen, the trigger design pattern helps avoid the limit error. We will now see other important limits. Avoiding SOQL Query Limit You can issue only 100 queries per transaction, that is, when your code will issue more than 100 SOQL queries then it will throw error. Example This example shows how SOQL query limit can be reached − The following trigger iterates over a list of customers and updates the child record”s (Invoice) description with string ”Ok to Pay”. // Helper class:Below code needs o be checked. public class CustomerTriggerHelper { public static void isAfterUpdateCall(Trigger.new) { createInvoiceRecords(trigger.new);//Method call updateCustomerDescription(trigger.new); } // Method To Create Invoice Records public static void createInvoiceRecords (List<apex_customer__c> customerList) { for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } // Method to update the invoice records public static updateCustomerDescription (List<apex_customer__c> customerList) { for (APEX_Customer__c objCust: customerList) { List<apex_customer__c> invList = [SELECT Id, Name, APEX_Description__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id]; // This query will fire for the number of records customer list has and will // hit the governor limit when records are more than 100 for (APEX_Invoice__c objInv: invList) { objInv.APEX_Description__c = ”OK To Pay”; update objInv; // Update invoice, this will also hit the governor limit for DML if large // number(150) of records are there } } } } When the ”updateCustomerDescription” method is called and the number of customer records are more than 100, then it will hit the SOQL limit. To avoid this, never write the SOQL query in the For Loop. In this case, the SOQL query has been written in the For loop. Following is an example which will show how to avoid the DML as well as the SOQL limit. We have used the nested relationship query to fetch the invoice records and used the context variable trigger.newMap to get the map of id and Customer records. // SOQL-Good Way to Write Query and avoid limit exception // Helper Class public class CustomerTriggerHelper { public static void isAfterUpdateCall(Trigger.new) { createInvoiceRecords(trigger.new); //Method call updateCustomerDescription(trigger.new, trigger.newMap); } // Method To Create Invoice Records public static void createInvoiceRecords (List<apex_customer__c> customerList) { for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } // Method to update the invoice records public static updateCustomerDescription (List<apex_customer__c> customerList, Map<id, apex_customer__c> newMapVariable) { List<apex_customer__c> customerListWithInvoice = [SELECT id, Name,(SELECT Id, Name, APEX_Description__c FROM APEX_Invoice__r) FROM APEX_Customer__c WHERE Id IN :newMapVariable.keySet()]; // Query will be for only one time and fetches all the records List<apex_invoice__c> invoiceToUpdate = new List<apex_invoice__c>(); for (APEX_Customer__c objCust: customerList) { for (APEX_Invoice__c objInv: invList) { objInv.APEX_Description__c = ”OK To Pay”; invoiceToUpdate.add(objInv); // Add the modified records to List } } update invoiceToUpdate; } } DML Bulk Calls This example shows the Bulk trigger along with the trigger helper class pattern. You must save the helper class first and then save the trigger. Note − Paste the below code in ”CustomerTriggerHelper” class which we have created earlier. // Helper Class public class CustomerTriggerHelper { public static void isAfterUpdateCall(List<apex_customer__c> customerList, Map<id, apex_customer__c> mapIdToCustomers, Map<id, apex_customer__c> mapOldItToCustomers) { createInvoiceRecords(customerList, mapOldItToCustomers); //Method call updateCustomerDescription(customerList,mapIdToCustomers, mapOldItToCustomers); } // Method To Create Invoice Records public static void createInvoiceRecords (List<apex_customer__c> customerList, Map<id, apex_customer__c> mapOldItToCustomers) { List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); List<apex_customer__c> customerToInvoice = [SELECT id, Name FROM APEX_Customer__c LIMIT 1]; for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == ”Active” && mapOldItToCustomers.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { //condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; objInvoice.APEX_Customer__c = objCustomer.id; InvoiceList.add(objInvoice); } } system.debug(”InvoiceList&&&”+InvoiceList); insert InvoiceList; // DML to insert the Invoice List in SFDC. This also follows the Bulk pattern } // Method to update the invoice records public static void updateCustomerDescription (List<apex_customer__c> customerList, Map<id, apex_customer__c> newMapVariable, Map<id, apex_customer__c> oldCustomerMap) { List<apex_customer__c> customerListWithInvoice = [SELECT id, Name,(SELECT Id, Name, APEX_Description__c FROM Invoices__r) FROM APEX_Customer__c WHERE Id IN :newMapVariable.keySet()]; // Query will be for only one time and fetches all the records List<apex_invoice__c> invoiceToUpdate = new List<apex_invoice__c>(); List<apex_invoice__c> invoiceFetched = new List<apex_invoice__c>(); invoiceFetched = customerListWithInvoice[0].Invoices__r; system.debug(”invoiceFetched”+invoiceFetched); system.debug(”customerListWithInvoice****”+customerListWithInvoice); for (APEX_Customer__c objCust: customerList) { system.debug(”objCust.Invoices__r”+objCust.Invoices__r); if (objCust.APEX_Active__c == true && oldCustomerMap.get(objCust.id).APEX_Active__c == false) { for (APEX_Invoice__c objInv: invoiceFetched) { system.debug(”I am in For Loop”+objInv); objInv.APEX_Description__c = ”OK To Pay”; invoiceToUpdate.add(objInv); // Add the modified records to List } } } system.debug(”Value of List ***”+invoiceToUpdate); update invoiceToUpdate; // This statement is Bulk DML which performs the DML on List and avoids // the DML Governor limit } } // Trigger Code for this class: Paste this code in ”Customer_After_Insert” // trigger on Customer Object trigger Customer_After_Insert on APEX_Customer__c (after update) { CustomerTriggerHelper.isAfterUpdateCall(Trigger.new, trigger.newMap, trigger.oldMap); // Trigger calls the helper class and does not have any code in Trigger } Other Salesforce Governor Limits Following table

Apex – Deployment

Apex – Deployment ”; Previous Next What is Deployment in SFDC? Till now we have developed code in Developer Edition, but in real life scenario, you have to do this development in Sandbox and then you might need to deploy this to another sandbox or production environment and this is called the deployment. In short, this is the movement of metadata from one organization to another. The reason behind this is that you cannot develop Apex in your Salesforce production organization. Live users accessing the system while you are developing can destabilize your data or corrupt your application. Tools available for deployment − Force.com IDE Change Sets SOAP API Force.com Migration Tool As we are using the Developer Edition for our development and learning purpose, we cannot use the Change Set or other tools which need the SFDC enterprise or other paid edition. Hence, we will be elaborating the Force.com IDE deployment method in this tutorial. Force.com Eclipse IDE Step 1 − Open Eclipse and open the class trigger that needs to be deployed. Step 2 − Once you click on ”Deploy to server”, then enter the username and password of the organization wherein, the Component needs to be deployed. By performing the above mentioned steps, your Apex components will be deployed to the target organization. Deployment using Change Set You can deploy Validation rules, workflow rules, Apex classes and Trigger from one organization to other by connecting them via the deployment settings. In this case, organizations must be connected. To open the deployment setup, follow the steps given below. Remember that this feature is not available in the Developer Edition − Step 1 − Go to Setup and search for ”Deploy”. Step 2 − Click on ”Outbound Change Set” in order to create change set to deploy. Step 3 − Add components to change set using the ”Add” button and then Save and click on Upload. Step 4 − Go to the Target organization and click on the inbound change set and finally click on deploy. SOAP API Calls to Deploy We will just have a small overview of this method as this is not a commonly-used method. You can use the method calls given below to deploy your metadata. compileAndTest() compileClasses() compileTriggers() Force.com Migration Tool This tool is used for the scripted deployment. You have to download the Force.com Migration tool and then you can perform the file based deployment. You can download the Force.com migration tool and then do the scripted deployment. Print Page Previous Next Advertisements ”;

Apex – Resources

Apex – Useful Resources ”; Previous Next The following resources contain additional information on Apex. Please use them to get more in-depth knowledge on this topic. Useful Video Courses A Practical Guide To SFDX and Salesforce CLI 38 Lectures 3 hours Manish Choudhari More Detail Oracle Apex – Web App Development 15 Lectures 2 hours Vijay Thapa More Detail Oracle Application Express APEX 20.1 Administration Training 7 Lectures 2 hours Uplatz More Detail Learn Salesforce Apex Programming (Along with Practice Exams) Best Seller 29 Lectures 6 hours Ramnarayan Ramakrishnan More Detail Oracle APEX Advanced Ideas 49 Lectures 3 hours Ali Saleh Ali More Detail Salesforce Development – Customization with Apex for Beginners 10 Lectures 4 hours Soham Ghosh More Detail Print Page Previous Next Advertisements ”;

Apex – Testing

Apex – Testing ”; Previous Next Testing is the integrated part of Apex or any other application development. In Apex, we have separate test classes to develop for all the unit testing. Test Classes In SFDC, the code must have 75% code coverage in order to be deployed to Production. This code coverage is performed by the test classes. Test classes are the code snippets which test the functionality of other Apex class. Let us write a test class for one of our codes which we have written previously. We will write test class to cover our Trigger and Helper class code. Below is the trigger and helper class which needs to be covered. // Trigger with Helper Class trigger Customer_After_Insert on APEX_Customer__c (after update) { CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap); //Trigger calls the helper class and does not have any code in Trigger } // Helper Class: public class CustomerTriggerHelper { public static void createInvoiceRecords (List<apex_customer__c> customerList, Map<id, apex_customer__c> oldMapCustomer) { List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == ”Active” && oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; objInvoice.APEX_Customer__c = objCustomer.id; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } } Creating Test Class In this section, we will understand how to create a Test Class. Data Creation We need to create data for test class in our test class itself. Test class by default does not have access to organization data but if you set @isTest(seeAllData = true), then it will have the access to organization”s data as well. @isTest annotation By using this annotation, you declared that this is a test class and it will not be counted against the organization”s total code limit. testMethod keyword Unit test methods are the methods which do not take arguments, commit no data to the database, send no emails, and are declared with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest. We have used the ”myUnitTest” test method in our examples. Test.startTest() and Test.stopTest() These are the standard test methods which are available for test classes. These methods contain the event or action for which we will be simulating our test. Like in this example, we will test our trigger and helper class to simulate the fire trigger by updating the records as we have done to start and stop block. This also provides separate governor limit to the code which is in start and stop block. System.assert() This method checks the desired output with the actual. In this case, we are expecting an Invoice record to be inserted so we added assert to check the same. Example /** * This class contains unit tests for validating the behavior of Apex classes * and triggers. * * Unit tests are class methods that verify whether a particular piece * of code is working properly. Unit test methods take no arguments, * commit no data to the database, and are flagged with the testMethod * keyword in the method definition. * * All test methods in an organization are executed whenever Apex code is deployed * to a production organization to confirm correctness, ensure code * coverage, and prevent regressions. All Apex classes are * required to have at least 75% code coverage in order to be deployed * to a production organization. In addition, all triggers must have some code coverage. * * The @isTest class annotation indicates this class only contains test * methods. Classes defined with the @isTest annotation do not count against * the organization size limit for all Apex scripts. * * See the Apex Language Reference for more information about Testing and Code Coverage. */ @isTest private class CustomerTriggerTestClass { static testMethod void myUnitTest() { //Create Data for Customer Objet APEX_Customer__c objCust = new APEX_Customer__c(); objCust.Name = ”Test Customer”; objCust.APEX_Customer_Status__c = ”Inactive”; insert objCust; // Now, our trigger will fire on After update event so update the Records Test.startTest(); // Starts the scope of test objCust.APEX_Customer_Status__c = ”Active”; update objCust; Test.stopTest(); // Ends the scope of test // Now check if it is giving desired results using system.assert // Statement.New invoice should be created List<apex_invoice__c> invList = [SELECT Id, APEX_Customer__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id]; system.assertEquals(1,invList.size()); // Check if one record is created in Invoivce sObject } } Running the Test Class Follow the steps given below to run the test class − Step 1 − Go to Apex classes ⇒ click on the class name ”CustomerTriggerTestClass”. Step 2 − Click on Run Test button as shown. Step 3 − Check status Step 4 − Now check the class and trigger for which we have written the test Class Trigger Our testing is successful and completed. Print Page Previous Next Advertisements ”;