Apex – Discussion

Discuss Apex ”; Previous Next Apex is a proprietary language developed by Salesforce.com. It is a strongly typed, object oriented programming language that allows developers to execute flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. Print Page Previous Next Advertisements ”;

Apex – Triggers

Apex – Triggers ”; Previous Next Apex triggers are like stored procedures which execute when a particular event occurs. A trigger executes before and after an event occurs on record. Syntax trigger triggerName on ObjectName (trigger_events) { Trigger_code_block } Executing the Trigger Following are the events on which we can fir the trigger − insert update delete merge upsert undelete Trigger Example 1 Suppose we received a business requirement that we need to create an Invoice Record when Customer”s ”Customer Status” field changes to Active from Inactive. For this, we will create a trigger on APEX_Customer__c object by following these steps − Step 1 − Go to sObject Step 2 − Click on Customer Step 3 − Click on ”New” button in the Trigger related list and add the trigger code as give below. // Trigger Code trigger Customer_After_Insert on APEX_Customer__c (after update) { List InvoiceList = new List(); for (APEX_Customer__c objCustomer: Trigger.new) { if (objCustomer.APEX_Customer_Status__c == ”Active”) { APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } // DML to insert the Invoice List in SFDC insert InvoiceList; } Explanation Trigger.new − This is the context variable which stores the records currently in the trigger context, either being inserted or updated. In this case, this variable has Customer object”s records which have been updated. There are other context variables which are available in the context – trigger.old, trigger.newMap, trigger.OldMap. Trigger Example 2 The above trigger will execute when there is an update operation on the Customer records. Suppose, the invoice record needs to be inserted only when the Customer Status changes from Inactive to Active and not every time; for this, we can use another context variable trigger.oldMap which will store the key as record id and the value as old record values. // Modified Trigger Code trigger Customer_After_Insert on APEX_Customer__c (after update) { List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); for (APEX_Customer__c objCustomer: Trigger.new) { // condition to check the old value and new value if (objCustomer.APEX_Customer_Status__c == ”Active” && trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == ”Inactive”) { APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = ”Pending”; InvoiceList.add(objInvoice); } } // DML to insert the Invoice List in SFDC insert InvoiceList; } Explanation We have used the Trigger.oldMap variable which as explained earlier, is a context variable which stores the Id and old value of records which are being updated. Print Page Previous Next Advertisements ”;

Apex – Debugging

Apex – Debugging ”; Previous Next Debugging is an important part in any programming development. In Apex, we have certain tools that can be used for debugging. One of them is the system.debug() method which prints the value and output of variable in the debug logs. We can use the following two tools for debugging − Developer Console Debug Logs Debugging via Developer Console You can use the Developer console and execute anonymous functionality for debugging the Apex as below − Example Consider our existing example of fetching the customer records which have been created today. We just want to know if the query is returning the results or not and if yes, then we will check the value of List. Paste the code given below in execute anonymous window and follow the steps which we have done for opening execute anonymous window. Step 1 − Open the Developer console Step 2 − Open the Execute anonymous from ”Debug” as shown below. Step 3 − Open the Execute Anonymous window and paste the following code and click on execute. // Debugging The Apex List<apex_customer__c> customerList = new List<apex_customer__c>(); customerList = [SELECT Id, Name FROM APEX_Customer__c WHERE CreatedDate = today]; // Our Query System.debug(”Records on List are ”+customerList+” And Records are ”+customerList); // Debug statement to check the value of List and Size Step 4 − Open the Logs as shown below. Step 5 − Enter ”USER” in filter condition as shown below. Step 6 − Open the USER DEBUG Statement as shown below. Debugging via Debug Logs You can debug the same class via debug logs as well. Suppose, you have a trigger in Customer object and it needs to be debugged for some variable values, then you can do this via the debug logs as shown below − This is the Trigger Code which updates the Description field if the modified customer is active and you want to check the values of variables and records currently in scope − trigger CustomerTrigger on APEX_Customer__c (before update) { List<apex_customer__c> customerList = new List<apex_customer__c>(); for (APEX_Customer__c objCust: Trigger.new) { System.debug(”objCust current value is”+objCust); if (objCust.APEX_Active__c == true) { objCust.APEX_Customer_Description__c = ”updated”; System.debug(”The record which has satisfied the condition ”+objCust); } } } Follow the steps given below to generate the Debug logs. Step 1 − Set the Debug logs for your user. Go to Setup and type ”Debug Log” in search setup window and then click on Link. Step 2 − Set the debug logs as following. Step 3 − Enter the name of User which requires setup. Enter your name here. Step 4 − Modify the customer records as event should occur to generate the debug log. Step 5 − Now go to the debug logs section again. Open the debug logs and click on Reset. Step 6 − Click on the view link of the first debug log. Step 7 − Search for the string ”USER” by using the browser search as shown below. The debug statement will show the value of the field at which we have set the point. Print Page Previous Next Advertisements ”;

Apex – Security

Apex – Security ”; Previous Next Apex security refers to the process of applying security settings and enforcing the sharing rules on running code. Apex classes have security setting that can be controlled via two keywords. Data Security and Sharing Rules Apex generally runs in system context, that is, the current user”s permissions. Field-level security, and sharing rules are not taken into account during code execution. Only the anonymous block code executes with the permission of the user who is executing the code. Our Apex code should not expose the sensitive data to User which is hidden via security and sharing settings. Hence, Apex security and enforcing the sharing rule is most important. With Sharing Keyword If you use this keyword, then the Apex code will enforce the Sharing settings of current user to Apex code. This does not enforce the Profile permission, only the data level sharing settings. Let us consider an example wherein, our User has access to 5 records, but the total number of records is 10. So when the Apex class will be declared with the “With Sharing” Keyword, it will return only 5 records on which the user has access to. Example First, make sure that you have created at least 10 records in the Customer object with ”Name” of 5 records as ”ABC Customer” and rest 5 records as ”XYZ Customer”. Then, create a sharing rule which will share the ”ABC Customer” with all Users. We also need to make sure that we have set the OWD of Customer object as Private. Paste the code given below to Anonymous block in the Developer Console. // Class With Sharing public with sharing class MyClassWithSharing { // Query To fetch 10 records List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10]; public Integer executeQuery () { System.debug(”List will have only 5 records and the actual records are” + CustomerList.size()+” as user has access to”+CustomerList); Integer ListSize = CustomerList.size(); return ListSize; } } // Save the above class and then execute as below // Execute class using the object of class MyClassWithSharing obj = new MyClassWithSharing(); Integer ListSize = obj.executeQuery(); Without Sharing Keyword As the name suggests, class declared with this keyword executes in System mode, i.e., irrespective of the User”s access to the record, query will fetch all the records. // Class Without Sharing public without sharing class MyClassWithoutSharing { List<apex_customer__c> CustomerList = [SELECT id, Name FROM APEX_Customer__c LIMIT 10]; // Query To fetch 10 records, this will return all the records public Integer executeQuery () { System.debug(”List will have only 5 records and the actula records are” + CustomerList.size()+” as user has access to”+CustomerList); Integer ListSize = CustomerList.size(); return ListSize; } } // Output will be 10 records. Setting Security for Apex Class You can enable or disable an Apex class for particular profile. The steps for the same are given below. You can determine which profile should have access to which class. Setting Apex class security from the class list page Step 1 − From Setup, click Develop → Apex Classes. Step 2 − Click the name of the class that you want to restrict. We have clicked on CustomerOperationClass. Step 3 − Click on Security. Step 4 − Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click on Remove. Step 5 − Click on Save. Setting Apex Security from Permission Set Step 1 − From Setup, click Manage Users → Permission Sets. Step 2 − Select a permission set. Step 3 − Click on Apex Class Access. Step 4 − Click on Edit. Step 5 − Select the Apex classes that you want to enable from the Available Apex Classes list and click Add, or select the Apex classes that you want to disable from the Enabled Apex Classes list and click remove. Step 6 − Click the Save button. Print Page Previous Next Advertisements ”;

Apex – SOQL

Apex – SOQL ”; Previous Next This is Salesforce Object Query Language designed to work with SFDC Database. It can search a record on a given criterion only in single sObject. Like SOSL, it cannot search across multiple objects but it does support nested queries. SOQL Example Consider our ongoing example of Chemical Company. Suppose, we need a list of records which are created today and whose customer name is not ”test”. In this case, we will have to use the SOQL query as given below − // fetching the Records via SOQL List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); InvoiceList = [SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c WHERE createdDate = today AND APEX_Customer__r.Name != ”Test”]; // SOQL query for given criteria // Printing the fetched records System.debug(”We have total ”+InvoiceList.size()+” Records in List”); for (APEX_Invoice__c objInvoice: InvoiceList) { System.debug(”Record Value is ”+objInvoice); // Printing the Record fetched } You can run the SOQL query via the Query Editor in the Developer console as shown below. Run the query given below in the Developer Console. Search for the Invoice records created today. SELECT Id, Name, APEX_Customer__r.Name, APEX_Status__c FROM APEX_Invoice__c WHERE createdDate = today You must select the fields for which you need the values, otherwise, it can throw run time errors. Traversing Relationship Fields This is one of the most important parts in SFDC as many times we need to traverse through the parent child object relationship Also, there may be cases when you need to insert two associated objects records in Database. For example, Invoice object has relationship with the Customer object and hence one Customer can have many invoices. Suppose, you are creating the invoice and then you need to relate this invoice to Customer. You can use the following code for this functionality − // Now create the invoice record and relate it with the Customer object // Before executing this, please create a Customer Records with Name ”Customer // Creation Test” APEX_Invoice__c objInvoice = new APEX_Invoice__c(); // Relating Invoice to customer via id field of Customer object objInvoice.APEX_Customer__c = [SELECT id FROM APEX_Customer__c WHERE Name = ”Customer Creation Test” LIMIT 1].id; objInvoice.APEX_Status__c = ”Pending”; insert objInvoice; //Creating Invoice System.debug(”Newly Created Invoice”+objInvoice); //Newly created invoice Execute this code snippet in the Developer Console. Once executed, copy the Id of invoice from the Developer console and then open the same in SFDC as shown below. You can see that the Parent record has already been assigned to Invoice record as shown below. Fetching Child Records Let us now consider an example wherein, all the invoices related to particular customer record need to be in one place. For this, you must know the child relationship name. To see the child relationship name, go to the field detail page on the child object and check the “Child Relationship” value. In our example, it is invoices appended by __r at the end. Example In this example, we will need to set up data, create a customer with name as ”ABC Customer” record and then add 3 invoices to that customer. Now, we will fetch the invoices the Customer ”ABC Customer” has. Following is the query for the same − // Fetching Child Records using SOQL List<apex_customer__c> ListCustomers = [SELECT Name, Id, (SELECT id, Name FROM Invoices__r) FROM APEX_Customer__c WHERE Name = ”ABC Customer”]; // Query for fetching the Child records along with Parent System.debug(”ListCustomers ”+ListCustomers); // Parent Record List<apex_invoice__c> ListOfInvoices = ListCustomers[0].Invoices__r; // By this notation, you could fetch the child records and save it in List System.debug(”ListOfInvoices values of Child ”+ListOfInvoices); // Child records You can see the Record values in the Debug logs. Fetching Parent Record Suppose, you need to fetch the Customer Name of Invoice the creation date of which is today, then you can use the query given below for the same − Example Fetch the Parent record”s value along with the child object. // Fetching Parent Record Field value using SOQL List<apex_invoice__c> ListOfInvoicesWithCustomerName = new List<apex_invoice__c>(); ListOfInvoicesWithCustomerName = [SELECT Name, id, APEX_Customer__r.Name FROM APEX_Invoice__c LIMIT 10]; // Fetching the Parent record”s values for (APEX_Invoice__c objInv: ListOfInvoicesWithCustomerName) { System.debug(”Invoice Customer Name is ”+objInv.APEX_Customer__r.Name); // Will print the values, all the Customer Records will be printed } Here we have used the notation APEX_Customer__r.Name, where APEX_Customer__r is parent relationship name, here you have to append the __r at the end of the Parent field and then you can fetch the parent field value. Aggregate Functions SOQL does have aggregate function as we have in SQL. Aggregate functions allow us to roll up and summarize the data. Let us now understand the function in detail. Suppose, you wanted to know that what is the average revenue we are getting from Customer ”ABC Customer”, then you can use this function to take up the average. Example // Getting Average of all the invoices for a Perticular Customer AggregateResult[] groupedResults = [SELECT AVG(APEX_Amount_Paid__c)averageAmount FROM APEX_Invoice__c WHERE APEX_Customer__r.Name = ”ABC Customer”]; Object avgPaidAmount = groupedResults[0].get(”averageAmount”); System.debug(”Total Average Amount Received From Customer ABC is ”+avgPaidAmount); Check the output in Debug logs. Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a readonly sObject and is only used for query results. It is useful when we need to generate the Report on Large data. There are other aggregate functions as well which you can be used to perform data summary. MIN() − This can be used to find the minimum value MAX() − This can be used to find the maximum value. Binding Apex Variables You can use the Apex variable in SOQL query to fetch the desired results. Apex variables can be referenced by the Colon (:) notation. Example // Apex Variable Reference String CustomerName = ”ABC Customer”; List<apex_customer__c> ListCustomer = [SELECT Id, Name FROM APEX_Customer__c WHERE Name = :CustomerName]; // Query Using Apex variable System.debug(”ListCustomer Name”+ListCustomer); // Customer Name Print Page Previous Next

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 – 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 ”;