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 ”;
Category: apex
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 – Classes
Apex – Classes ”; Previous Next What is a Class? A class is a template or blueprint from which objects are created. An object is an instance of a class. This is the standard definition of Class. Apex Classes are similar to Java Classes. For example, InvoiceProcessor class describes the class which has all the methods and actions that can be performed on the Invoice. If you create an instance of this class, then it will represent the single invoice which is currently in context. Creating Classes You can create class in Apex from the Developer Console, Force.com Eclipse IDE and from Apex Class detail page as well. From Developer Console Follow these steps to create an Apex class from the Developer Console − Step 1 − Go to Name and click on the Developer Console. Step 2 − Click on File ⇒ New and then click on the Apex class. From Force.com IDE Follow these steps to create a class from Force.com IDE − Step 1 − Open Force.com Eclipse IDE Step 2 − Create a New Project by clicking on File ⇒ New ⇒ Apex Class. Step 3 − Provide the Name for the Class and click on OK. Once this is done, the new class will be created. From Apex Class Detail Page Follow these steps to create a class from Apex Class Detail Page − Step 1 − Click on Name ⇒ Setup. Step 2 − Search for ”Apex Class” and click on the link. It will open the Apex Class details page. Step 3 − Click on ”New” and then provide the Name for class and then click Save. Apex Class Structure Below is the sample structure for Apex class definition. Syntax private | public | global [virtual | abstract | with sharing | without sharing] class ClassName [implements InterfaceNameList] [extends ClassName] { // Classs Body } This definition uses a combination of access modifiers, sharing modes, class name and class body. We will look at all these options further. Example Following is a sample structure for Apex class definition − public class MySampleApexClass { //Class definition and body public static Integer myValue = 0; //Class Member variable public static String myString = ””; //Class Member variable public static Integer getCalculatedValue () { // Method definition and body // do some calculation myValue = myValue+10; return myValue; } } Access Modifiers Private If you declare the access modifier as ”Private”, then this class will be known only locally and you cannot access this class outside of that particular piece. By default, classes have this modifier. Public If you declare the class as ”Public” then this implies that this class is accessible to your organization and your defined namespace. Normally, most of the Apex classes are defined with this keyword. Global If you declare the class as ”global” then this will be accessible by all apex codes irrespective of your organization. If you have method defined with web service keyword, then you must declare the containing class with global keyword. Sharing Modes Let us now discuss the different modes of sharing. With Sharing This is a special feature of Apex Classes in Salesforce. When a class is specified with ”With Sharing” keyword then it has following implications: When the class will get executed, it will respect the User”s access settings and profile permission. Suppose, User”s action has triggered the record update for 30 records, but user has access to only 20 records and 10 records are not accessible. Then, if the class is performing the action to update the records, only 20 records will be updated to which the user has access and rest of 10 records will not be updated. This is also called as the User mode. Without Sharing Even if the User does not have access to 10 records out of 30, all the 30 records will be updated as the Class is running in the System mode, i.e., it has been defined with Without Sharing keyword. This is called the System Mode. Virtual If you use the ”virtual” keyword, then it indicates that this class can be extended and overrides are allowed. If the methods need to be overridden, then the classes should be declared with the virtual keyword. Abstract If you declare the class as ”abstract”, then it will only contain the signature of method and not the actual implementation. Class Variables Syntax [public | private | protected | global] [final] [static] data_type variable_name [= value] In the above syntax − Variable data type and variable name are mandatory Access modifiers and value are optional. Example public static final Integer myvalue; Print Page Previous Next Advertisements ”;
Apex – Collections
Apex – Collections ”; Previous Next Collections is a type of variable that can store multiple number of records. For example, List can store multiple number of Account object”s records. Let us now have a detailed overview of all collection types. Lists List can contain any number of records of primitive, collections, sObjects, user defined and built in Apex type. This is one of the most important type of collection and also, it has some system methods which have been tailored specifically to use with List. List index always starts with 0. This is synonymous to the array in Java. A list should be declared with the keyword ”List”. Example Below is the list which contains the List of a primitive data type (string), that is the list of cities. List<string> ListOfCities = new List<string>(); System.debug(”Value Of ListOfCities”+ListOfCities); Declaring the initial values of list is optional. However, we will declare the initial values here. Following is an example which shows the same. List<string> ListOfStates = new List<string> {”NY”, ”LA”, ”LV”}; System.debug(”Value ListOfStates”+ListOfStates); List of Accounts (sObject) List<account> AccountToDelete = new List<account> (); //This will be null System.debug(”Value AccountToDelete”+AccountToDelete); We can declare the nested List as well. It can go up to five levels. This is called the Multidimensional list. This is the list of set of integers. List<List<Set<Integer>>> myNestedList = new List<List<Set<Integer>>>(); System.debug(”value myNestedList”+myNestedList); List can contain any number of records, but there is a limitation on heap size to prevent the performance issue and monopolizing the resources. Methods for Lists There are methods available for Lists which we can be utilized while programming to achieve some functionalities like calculating the size of List, adding an element, etc. Following are some most frequently used methods − size() add() get() clear() set() The following example demonstrates the use of all these methods // Initialize the List List<string> ListOfStatesMethod = new List<string>(); // This statement would give null as output in Debug logs System.debug(”Value of List”+ ListOfStatesMethod); // Add element to the list using add method ListOfStatesMethod.add(”New York”); ListOfStatesMethod.add(”Ohio”); // This statement would give New York and Ohio as output in Debug logs System.debug(”Value of List with new States”+ ListOfStatesMethod); // Get the element at the index 0 String StateAtFirstPosition = ListOfStatesMethod.get(0); // This statement would give New York as output in Debug log System.debug(”Value of List at First Position”+ StateAtFirstPosition); // set the element at 1 position ListOfStatesMethod.set(0, ”LA”); // This statement would give output in Debug log System.debug(”Value of List with element set at First Position” + ListOfStatesMethod[0]); // Remove all the elements in List ListOfStatesMethod.clear(); // This statement would give output in Debug log System.debug(”Value of List”+ ListOfStatesMethod); You can use the array notation as well to declare the List, as given below, but this is not general practice in Apex programming − String [] ListOfStates = new List<string>(); Sets A Set is a collection type which contains multiple number of unordered unique records. A Set cannot have duplicate records. Like Lists, Sets can be nested. Example We will be defining the set of products which company is selling. Set<string> ProductSet = new Set<string>{”Phenol”, ”Benzene”, ”H2SO4”}; System.debug(”Value of ProductSet”+ProductSet); Methods for Sets Set does support methods which we can utilize while programming as shown below (we are extending the above example) − // Adds an element to the set // Define set if not defined previously Set<string> ProductSet = new Set<string>{”Phenol”, ”Benzene”, ”H2SO4”}; ProductSet.add(”HCL”); System.debug(”Set with New Value ”+ProductSet); // Removes an element from set ProductSet.remove(”HCL”); System.debug(”Set with removed value ”+ProductSet); // Check whether set contains the particular element or not and returns true or false ProductSet.contains(”HCL”); System.debug(”Value of Set with all values ”+ProductSet); Maps It is a key value pair which contains the unique key for each value. Both key and value can be of any data type. Example The following example represents the map of the Product Name with the Product code. // Initialize the Map Map<string, string> ProductCodeToProductName = new Map<string, string> {”1000”=>”HCL”, ”1001”=>”H2SO4”}; // This statement would give as output as key value pair in Debug log System.debug(”value of ProductCodeToProductName”+ProductCodeToProductName); Methods for Maps Following are a few examples which demonstrate the methods that can be used with Map − // Define a new map Map<string, string> ProductCodeToProductName = new Map<string, string>(); // Insert a new key-value pair in the map where ”1002” is key and ”Acetone” is value ProductCodeToProductName.put(”1002”, ”Acetone”); // Insert a new key-value pair in the map where ”1003” is key and ”Ketone” is value ProductCodeToProductName.put(”1003”, ”Ketone”); // Assert that the map contains a specified key and respective value System.assert(ProductCodeToProductName.containsKey(”1002”)); System.debug(”If output is true then Map contains the key and output is:” + ProductCodeToProductName.containsKey(”1002”)); // Retrieves a value, given a particular key String value = ProductCodeToProductName.get(”1002”); System.debug(”Value at the Specified key using get function: ”+value); // Return a set that contains all of the keys in the map Set SetOfKeys = ProductCodeToProductName.keySet(); System.debug(”Value of Set with Keys ”+SetOfKeys); Map values may be unordered and hence we should not rely on the order in which the values are stored and try to access the map always using keys. Map value can be null. Map keys when declared String are case-sensitive; for example, ABC and abc will be considered as different keys and treated as unique. Print Page Previous Next Advertisements ”;
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 – 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 ”;