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

Apex – Methods

Apex – Methods ”; Previous Next Class Methods There are two modifiers for Class Methods in Apex – Public or Protected. Return type is mandatory for method and if method is not returning anything then you must mention void as the return type. Additionally, Body is also required for method. Syntax [public | private | protected | global] [override] [static] return_data_type method_name (input parameters) { // Method body goes here } Explanation of Syntax Those parameters mentioned in the square brackets are optional. However, the following components are essential − return_data_type method_name Access Modifiers for Class Methods Using access modifiers, you can specify access level for the class methods. For Example, Public method will be accessible from anywhere in the class and outside of the Class. Private method will be accessible only within the class. Global will be accessible by all the Apex classes and can be exposed as web service method accessible by other apex classes. Example //Method definition and body public static Integer getCalculatedValue () { //do some calculation myValue = myValue+10; return myValue; } This method has return type as Integer and takes no parameter. A Method can have parameters as shown in the following example − // Method definition and body, this method takes parameter price which will then be used // in method. public static Integer getCalculatedValueViaPrice (Decimal price) { // do some calculation myValue = myValue+price; return myValue; } Class Constructors A constructor is a code that is invoked when an object is created from the class blueprint. It has the same name as the class name. We do not need to define the constructor for every class, as by default a no-argument constructor gets called. Constructors are useful for initialization of variables or when a process is to be done at the time of class initialization. For example, you will like to assign values to certain Integer variables as 0 when the class gets called. Example // Class definition and body public class MySampleApexClass2 { public static Double myValue; // Class Member variable public static String myString; // Class Member variable public MySampleApexClass2 () { myValue = 100; //initialized variable when class is called } public static Double getCalculatedValue () { // Method definition and body // do some calculation myValue = myValue+10; return myValue; } public static Double getCalculatedValueViaPrice (Decimal price) { // Method definition and body // do some calculation myValue = myValue+price; // Final Price would be 100+100=200.00 return myValue; } } You can call the method of class via constructor as well. This may be useful when programming Apex for visual force controller. When class object is created, then constructor is called as shown below − // Class and constructor has been instantiated MySampleApexClass2 objClass = new MySampleApexClass2(); Double FinalPrice = MySampleApexClass2.getCalculatedValueViaPrice(100); System.debug(”FinalPrice: ”+FinalPrice); Overloading Constructors Constructors can be overloaded, i.e., a class can have more than one constructor defined with different parameters. Example public class MySampleApexClass3 { // Class definition and body public static Double myValue; // Class Member variable public static String myString; // Class Member variable public MySampleApexClass3 () { myValue = 100; // initialized variable when class is called System.debug(”myValue variable with no Overaloading”+myValue); } public MySampleApexClass3 (Integer newPrice) { // Overloaded constructor myValue = newPrice; // initialized variable when class is called System.debug(”myValue variable with Overaloading”+myValue); } public static Double getCalculatedValue () { // Method definition and body // do some calculation myValue = myValue+10; return myValue; } public static Double getCalculatedValueViaPrice (Decimal price) { // Method definition and body // do some calculation myValue = myValue+price; return myValue; } } You can execute this class as we have executed it in previous example. // Developer Console Code MySampleApexClass3 objClass = new MySampleApexClass3(); Double FinalPrice = MySampleApexClass3.getCalculatedValueViaPrice(100); System.debug(”FinalPrice: ”+FinalPrice); Print Page Previous Next Advertisements ”;

Apex – Objects

Apex – Objects ”; Previous Next An instance of class is called Object. In terms of Salesforce, object can be of class or you can create an object of sObject as well. Object Creation from Class You can create an object of class as you might have done in Java or other object-oriented programming language. Following is an example Class called MyClass − // Sample Class Example public class MyClass { Integer myInteger = 10; public void myMethod (Integer multiplier) { Integer multiplicationResult; multiplicationResult = multiplier*myInteger; System.debug(”Multiplication is ”+multiplicationResult); } } This is an instance class, i.e., to call or access the variables or methods of this class, you must create an instance of this class and then you can perform all the operations. // Object Creation // Creating an object of class MyClass objClass = new MyClass(); // Calling Class method using Class instance objClass.myMethod(100); sObject creation sObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects. Following is an example of sObject initialization and shows how you can access the field of that particular object using dot notation and assign the values to fields. // Execute the below code in Developer console by simply pasting it // Standard Object Initialization for Account sObject Account objAccount = new Account(); // Object initialization objAccount.Name = ”Testr Account”; // Assigning the value to field Name of Account objAccount.Description = ”Test Account”; insert objAccount; // Creating record using DML System.debug(”Records Has been created ”+objAccount); // Custom sObject initialization and assignment of values to field APEX_Customer_c objCustomer = new APEX_Customer_c (); objCustomer.Name = ”ABC Customer”; objCustomer.APEX_Customer_Decscription_c = ”Test Description”; insert objCustomer; System.debug(”Records Has been created ”+objCustomer); Static Initialization Static methods and variables are initialized only once when a class is loaded. Static variables are not transmitted as part of the view state for a Visualforce page. Following is an example of Static method as well as Static variable. // Sample Class Example with Static Method public class MyStaticClass { Static Integer myInteger = 10; public static void myMethod (Integer multiplier) { Integer multiplicationResult; multiplicationResult = multiplier * myInteger; System.debug(”Multiplication is ”+multiplicationResult); } } // Calling the Class Method using Class Name and not using the instance object MyStaticClass.myMethod(100); Static Variable Use Static variables will be instantiated only once when class is loaded and this phenomenon can be used to avoid the trigger recursion. Static variable value will be same within the same execution context and any class, trigger or code which is executing can refer to it and prevent the recursion. Print Page Previous Next Advertisements ”;

Apex – Constants

Apex – Constants ”; Previous Next As in any other programming language, Constants are the variables which do not change their value once declared or assigned a value. In Apex, Constants are used when we want to define variables which should have constant value throughout the program execution. Apex constants are declared with the keyword ”final”. Example Consider a CustomerOperationClass class and a constant variable regularCustomerDiscount inside it − public class CustomerOperationClass { static final Double regularCustomerDiscount = 0.1; static Double finalPrice = 0; public static Double provideDiscount (Integer price) { //calculate the discount finalPrice = price – price * regularCustomerDiscount; return finalPrice; } } To see the Output of the above class, you have to execute the following code in the Developer Console Anonymous Window − Double finalPrice = CustomerOperationClass.provideDiscount(100); System.debug(”finalPrice ”+finalPrice); Print Page Previous Next Advertisements ”;