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 ”;
Category: apex
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 ”;
Apex – Strings
Apex – Strings ”; Previous Next String in Apex, as in any other programming language, is any set of characters with no character limit. Example String companyName = ”Abc International”; System.debug(”Value companyName variable”+companyName); String Methods String class in Salesforce has many methods. We will take a look at some of the most important and frequently used string methods in this chapter. contains This method will return true if the given string contains the substring mentioned. Syntax public Boolean contains(String substring) Example String myProductName1 = ”HCL”; String myProductName2 = ”NAHCL”; Boolean result = myProductName2.contains(myProductName1); System.debug(”O/p will be true as it contains the String and Output is:”+result); equals This method will return true if the given string and the string passed in the method have the same binary sequence of characters and they are not null. You can compare the SFDC record id as well using this method. This method is case-sensitive. Syntax public Boolean equals(Object string) Example String myString1 = ”MyString”; String myString2 = ”MyString”; Boolean result = myString2.equals(myString1); System.debug(”Value of Result will be true as they are same and Result is:”+result); equalsIgnoreCase This method will return true if stringtoCompare has the same sequence of characters as the given string. However, this method is not case-sensitive. Syntax public Boolean equalsIgnoreCase(String stringtoCompare) Example The following code will return true as string characters and sequence are same, ignoring the case sensitivity. String myString1 = ”MySTRING”; String myString2 = ”MyString”; Boolean result = myString2.equalsIgnoreCase(myString1); System.debug(”Value of Result will be true as they are same and Result is:”+result); remove This method removes the string provided in stringToRemove from the given string. This is useful when you want to remove some specific characters from string and are not aware of the exact index of the characters to remove. This method is case sensitive and will not work if the same character sequence occurs but case is different. Syntax public String remove(String stringToRemove) Example String myString1 = ”This Is MyString Example”; String stringToRemove = ”MyString”; String result = myString1.remove(stringToRemove); System.debug(”Value of Result will be ”This Is Example” as we have removed the MyString and Result is :”+result); removeEndIgnoreCase This method removes the string provided in stringToRemove from the given string but only if it occurs at the end. This method is not case-sensitive. Syntax public String removeEndIgnoreCase(String stringToRemove) Example String myString1 = ”This Is MyString EXAMPLE”; String stringToRemove = ”Example”; String result = myString1.removeEndIgnoreCase(stringToRemove); System.debug(”Value of Result will be ”This Is MyString” as we have removed the ”Example” and Result is :”+result); startsWith This method will return true if the given string starts with the prefix provided in the method. Syntax public Boolean startsWith(String prefix) Example String myString1 = ”This Is MyString EXAMPLE”; String prefix = ”This”; Boolean result = myString1.startsWith(prefix); System.debug(” This will return true as our String starts with string ”This” and the Result is :”+result); Print Page Previous Next Advertisements ”;
Apex – Overview
Apex – Overview ”; Previous Next What is Apex? Apex is a proprietary language developed by the Salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.Apex code can be initiated by Web service requests and from triggers on objects. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and Developer Edition. Features of Apex as a Language Let us now discuss the features of Apex as a Language − Integrated Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML Exception handling. It has support for inline SOQL and SOSL query handling which returns the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters. Java like syntax and easy to use Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop syntax and conditional statements. Strongly Integrated With Data Apex is data focused and designed to execute multiple queries and DML statements together. It issues multiple transaction statements on Database. Strongly Typed Apex is a strongly typed language. It uses direct reference to schema objects like sObject and any invalid reference quickly fails if it is deleted or if is of wrong data type. Multitenant Environment Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with easy-to-understand error messages. Upgrades Automatically Apex is upgraded as part of Salesforce releases. We don”t have to upgrade it manually. Easy Testing Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code can be more efficient. When Should Developer Choose Apex? Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration. Apex Applications We can use Apex when we want to − Create Web services with integrating other systems. Create email services for email blast or email setup. Perform complex validation over multiple objects at the same time and also custom validation implementation. Create complex business processes that are not supported by existing workflow functionality or flows. Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records. Perform some logic when a record is modified or modify the related object”s record when there is some event which has caused the trigger to fire. Working Structure of Apex As shown in the diagram below (Reference: Salesforce Developer Documentation), Apex runs entirely on demand Force.com Platform Flow of Actions There are two sequence of actions when the developer saves the code and when an end user performs some action which invokes the Apex code as shown below − Developer Action When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into a set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata. End User Action When an end-user triggers the execution of Apex, by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time as compared to the standard application platform request. Since Apex is the proprietary language of Salesforce.com, it does not support some features which a general programming language does. Following are a few features which Apex does not support − It cannot show the elements in User Interface. You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution. Creating multiple threads is also not possible as we can do it in other languages. Understanding the Apex Syntax Apex code typically contains many things that we might be familiar with from other programming languages. Variable Declaration As strongly typed language, you must declare every variable with data type in Apex. As seen in the code below (screenshot below), lstAcc is declared with data type as List of Accounts. SOQL Query This will be used to fetch the data from Salesforce database. The query shown in screenshot below is fetching data from Account object. Loop Statement This loop statement is used for iterating over a list or iterating over a piece of code for a specified number of times. In the code shown in the screenshot below, iteration will be same as the number of records we have. Flow Control Statement The If statement is used for flow control in this code. Based on certain condition, it is decided whether to go for execution or to stop the execution of the particular piece of code. For example, in the code shown below, it is checking whether the list is empty or it contains records. DML Statement Performs the records insert, update, upsert, delete operation on the records in database. For example, the code given below helps in updating Accounts with new field value. Following is an example of how an Apex code snippet will look like. We are going to study all these Apex programming concepts further in this tutorial. Print Page Previous Next Advertisements ”;
Apex – SOSL
Apex – SOSL ”; Previous Next Every business or application has search functionality as one of the basic requirements. For this, Salesforce.com provides two major approaches using SOSL and SOQL. Let us discuss the SOSL approach in detail in this chapter. SOSL Searching the text string across the object and across the field will be done by using SOSL. This is Salesforce Object Search Language. It has the capability of searching a particular string across multiple objects. SOSL statements evaluate to a list of sObjects, wherein, each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query. SOSL Query Example Consider a business case wherein, we need to develop a program which can search a specified string. Suppose, we need to search for string ”ABC” in the Customer Name field of Invoice object. The code goes as follows − First, you have to create a single record in Invoice object with Customer name as ”ABC” so that we can get valid result when searched. // Program To Search the given string in all Object // List to hold the returned results of sObject generic type List<list<SObject>> invoiceSearchList = new List<List<SObject>>(); // SOSL query which will search for ”ABC” string in Customer Name field of Invoice Object invoiceSearchList = [FIND ”ABC*” IN ALL FIELDS RETURNING APEX_Invoice_c (Id,APEX_Customer_r.Name)]; // Returned result will be printed System.debug(”Search Result ”+invoiceSearchList); // Now suppose, you would like to search string ”ABC” in two objects, // that is Invoice and Account. Then for this query goes like this: // Program To Search the given string in Invoice and Account object, // you could specify more objects if you want, create an Account with Name as ABC. // List to hold the returned results of sObject generic type List<List<SObject>> invoiceAndSearchList = new List<List<SObject>>(); // SOSL query which will search for ”ABC” string in Invoice and in Account object”s fields invoiceAndSearchList = [FIND ”ABC*” IN ALL FIELDS RETURNING APEX_Invoice__c (Id,APEX_Customer__r.Name), Account]; // Returned result will be printed System.debug(”Search Result ”+invoiceAndSearchList); // This list will hold the returned results for Invoice Object APEX_Invoice__c [] searchedInvoice = ((List<APEX_Invoice_c>)invoiceAndSearchList[0]); // This list will hold the returned results for Account Object Account [] searchedAccount = ((List<Account>)invoiceAndSearchList[1]); System.debug(”Value of searchedInvoice”+searchedInvoice+”Value of searchedAccount” + searchedAccount); SOQL This is almost the same as SOQL. You can use this to fetch the object records from one object only at a time. You can write nested queries and also fetch the records from parent or child object on which you are querying now. We will explore SOQL in the next chapter. Print Page Previous Next Advertisements ”;
Apex – Data Types
Apex – Data Types ”; Previous Next Understanding the Data Types The Apex language is strongly typed so every variable in Apex will be declared with the specific data type. All apex variables are initialized to null initially. It is always recommended for a developer to make sure that proper values are assigned to the variables. Otherwise such variables when used, will throw null pointer exceptions or any unhandled exceptions. Apex supports the following data types − Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean) Collections (Lists, Sets and Maps) (To be covered in Chapter 6) sObject Enums Classes, Objects and Interfaces (To be covered in Chapter 11, 12 and 13) In this chapter, we will look at all the Primitive Data Types, sObjects and Enums. We will be looking at Collections, Classes, Objects and Interfaces in upcoming chapters since they are key topics to be learnt individually. Primitive Data Types In this section, we will discuss the Primitive Data Types supported by Apex. Integer A 32-bit number that does not include any decimal point. The value range for this starts from -2,147,483,648 and the maximum value is up to 2,147,483,647. Example We want to declare a variable which will store the quantity of barrels which need to be shipped to the buyer of the chemical processing plant. Integer barrelNumbers = 1000; system.debug(” value of barrelNumbers variable: ”+barrelNumbers); The System.debug() function prints the value of variable so that we can use this to debug or to get to know what value the variable holds currently. Paste the above code to the Developer console and click on Execute. Once the logs are generated, then it will show the value of variable “barrelNumbers” as 1000. Boolean This variable can either be true, false or null. Many times, this type of variable can be used as flag in programming to identify if the particular condition is set or not set. Example If the Boolean shipmentDispatched is to be set as true, then it can be declared as − Boolean shipmentDispatched; shipmentDispatched = true; System.debug(”Value of shipmentDispatched ”+shipmentDispatched); Date This variable type indicates a date. This can only store the date and not the time. For saving the date along with time, we will need to store it in variable of DateTime. Example Consider the following example to understand how the Date variable works. //ShipmentDate can be stored when shipment is dispatched. Date ShipmentDate = date.today(); System.debug(”ShipmentDate ”+ShipmentDate); Long This is a 64-bit number without a decimal point. This is used when we need a range of values wider than those provided by Integer. Example If the company revenue is to be stored, then we will use the data type as Long. Long companyRevenue = 21474838973344648L; system.debug(”companyRevenue”+companyRevenue); Object We can refer this as any data type which is supported in Apex. For example, Class variable can be object of that class, and the sObject generic type is also an object and similarly specific object type like Account is also an Object. Example Consider the following example to understand how the object variable works. Account objAccount = new Account (Name = ”Test Chemical”); system.debug(”Account value”+objAccount); Note − You can create an object of predefined class as well, as given below − //Class Name: MyApexClass MyApexClass classObj = new MyApexClass(); This is the class object which will be used as class variable. String String is any set of characters within single quotes. It does not have any limit for the number of characters. Here, the heap size will be used to determine the number of characters. This puts a curb on the monopoly of resources by the Apex program and also ensures that it does not get too large. Example String companyName = ”Abc International”; System.debug(”Value companyName variable”+companyName); Time This variable is used to store the particular time. This variable should always be declared with the system static method. Blob The Blob is a collection of Binary data which is stored as object. This will be used when we want to store the attachment in salesforce into a variable. This data type converts the attachments into a single object. If the blob is to be converted into a string, then we can make use of the toString and the valueOf methods for the same. sObject This is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL. There are two types of sObjects – Standard and Custom. For example, Account is a standard sObject and any other user-defined object (like Customer object that we created) is a Custom sObject. Example //Declaring an sObject variable of type Account Account objAccount = new Account(); //Assignment of values to fields of sObjects objAccount.Name = ”ABC Customer”; objAccount.Description = ”Test Account”; System.debug(”objAccount variable value”+objAccount); //Declaring an sObject for custom object APEX_Invoice_c APEX_Customer_c objCustomer = new APEX_Customer_c(); //Assigning value to fields objCustomer.APEX_Customer_Decscription_c = ”Test Customer”; System.debug(”value objCustomer”+objCustomer); Enum Enum is an abstract data type that stores one value of a finite set of specified identifiers. You can use the keyword Enum to define an Enum. Enum can be used as any other data type in Salesforce. Example You can declare the possible names of Chemical Compound by executing the following code − //Declaring enum for Chemical Compounds public enum Compounds {HCL, H2SO4, NACL, HG} Compounds objC = Compounds.HCL; System.debug(”objC value: ”+objC); Print Page Previous Next Advertisements ”;
Apex – Variables
Apex – Variables ”; Previous Next Java and Apex are similar in a lot of ways. Variable declaration in Java and Apex is also quite the same. We will discuss a few examples to understand how to declare local variables. String productName = ”HCL”; Integer i = 0; Set<string> setOfProducts = new Set<string>(); Map<id, string> mapOfProductIdToName = new Map<id, string>(); Note that all the variables are assigned with the value null. Declaring Variables You can declare the variables in Apex like String and Integer as follows − String strName = ”My String”; //String variable declaration Integer myInteger = 1; //Integer variable declaration Boolean mtBoolean = true; //Boolean variable declaration Apex variables are Case-Insensitive This means that the code given below will throw an error since the variable ”m” has been declared two times and both will be treated as the same. Integer m = 100; for (Integer i = 0; i<10; i++) { integer m = 1; //This statement will throw an error as m is being declared again System.debug(”This code will throw error”); } Scope of Variables An Apex variable is valid from the point where it is declared in code. So it is not allowed to redefine the same variable again and in code block. Also, if you declare any variable in a method, then that variable scope will be limited to that particular method only. However, class variables can be accessed throughout the class. Example //Declare variable Products List<string> Products = new List<strings>(); Products.add(”HCL”); //You cannot declare this variable in this code clock or sub code block again //If you do so then it will throw the error as the previous variable in scope //Below statement will throw error if declared in same code block List<string> Products = new List<strings>(); Print Page Previous Next Advertisements ”;
Apex – Arrays
Apex – Arrays ”; Previous Next Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java. Below is the representation of an Array of Products − Index 0 − HCL Index 1 − H2SO4 Index 2 − NACL Index 3 − H2O Index 4 − N2 Index 5 − U296 Syntax <String> [] arrayOfProducts = new List<String>(); Example Suppose, we have to store the name of our Products – we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index. //Defining array String [] arrayOfProducts = new List<String>(); //Adding elements in Array arrayOfProducts.add(”HCL”); arrayOfProducts.add(”H2SO4”); arrayOfProducts.add(”NACL”); arrayOfProducts.add(”H2O”); arrayOfProducts.add(”N2”); arrayOfProducts.add(”U296”); for (Integer i = 0; i<arrayOfProducts.size(); i++) { //This loop will print all the elements in array system.debug(”Values In Array: ”+arrayOfProducts[i]); } Accessing array element by using index You can access any element in array by using the index as shown below − //Accessing the element in array //We would access the element at Index 3 System.debug(”Value at Index 3 is :”+arrayOfProducts[3]); Print Page Previous Next Advertisements ”;
Apex – Decision Making
Apex – Decision Making ”; Previous Next Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. In this chapter, we will be studying the basic and advanced structure of decision-making and conditional statements in Apex. Decision-making is necessary to control the flow of execution when certain condition is met or not. Following is the general form of a typical decision-making structure found in most of the programming languages Sr.No. Statement & Description 1 if statement An if statement consists of a Boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 if…elseif…else statement An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement. 4 nested if statement You can use one if or else if statement inside another if or else if statement(s). Print Page Previous Next Advertisements ”;