text
stringlengths
73
5.28k
apex developer guide version 58.0, summer ’23 @salesforcedocs last updated: june 15, 2023© copyright 2000–2023 salesforce, inc. all rights reserved. salesforce is a registered trademark of salesforce, inc., as are other names and marks. other marks appearing herein may be trademarks of their respective owners.contents apex developer guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 release notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 getting started with apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 introducing apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 apex development process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 apex quick start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 writing apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 data types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 control flow statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 classes, objects, and interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 working with data in apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 running apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 invoking apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 apex transactions and governor limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 using salesforce features with apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 integration and apex utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 debugging, testing, and deploying apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 debugging apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595 testing apex . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634 deploying apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 distributing apex using managed packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675 apex reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 shipping invoice example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 reserved keywords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 documentation typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694apex developer guide apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the salesforce platform server, in conjunction with calls to the api. this guide introduces you to the apex development process and provides valuable information on learning, writing, deploying and testing apex. for reference information on apex classes, interfaces, exceptions and so on, see apex reference guide. in this section: apex release notes use the salesforce release notes to learn about the most recent updates and changes to apex. getting started with apex learn about the apex development lifecycle. follow a step-by-step tutorial to create an apex class and trigger, and deploy them to a production organisation. writing apex apex is like java for salesforce. it enables you to add and interact with data in the lightning platform persistence layer. it uses classes, data types, variables, and if-else statements. you can make it execute based on a condition, or have a block of code execute repeatedly. running apex you can access many features of the salesforce user interface programmatically in apex, and you can integrate with external soap and rest web services. you can run apex code using a variety of mechanisms. apex code runs in atomic transactions. debugging, testing, and deploying apex develop your apex code in a sandbox and debug it with the developer console and debug logs. unit-test your code, then distribute it to customers using packages. apex reference in summer ’21 and later versions, apex reference content is moved to a separate guide called the apex reference guide. appendices glossary apex release notes use the salesforce release notes to learn about the most recent updates and changes to apex. for apex updates and changes that impact the salesforce platform, see the apex release notes. for new and changed apex classes, methods, exceptions and interfaces, see apex: new and changed items in the salesforce release notes. getting started with apex learn about the apex development lifecycle. follow a step-by-step tutorial to create an apex class and trigger, and deploy them to a production organisation. 1apex developer guide introducing apex in this section: introducing apex apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of business applications. apex revolutionizes the way developers create on-demand applications. apex development process in this chapter, you’ll learn about the apex development lifecycle, and which organization and tools to use to develop apex
. you’ll also learn about testing and deploying apex code. apex quick start this step-by-step tutorial shows how to create a simple apex class and trigger, and how to deploy these components to a production organization. introducing apex apex code is the first multitenant, on-demand programming language for developers interested in building the next generation of business applications. apex revolutionizes the way developers create on-demand applications. while many customization options are available through the salesforce user interface, such as the ability to define new fields, objects, workflow, and approval processes, developers can also use the soap api to issue data manipulation commands such as delete(), update() or upsert(), from client-side programs. these client-side programs, typically written in java, javascript, .net, or other programming languages, grant organizations more flexibility in their customizations. however, because the controlling logic for these client-side programs is not located on salesforce servers, they are restricted by the performance costs of making multiple round-trips to the salesforce site to accomplish common business transactions, and by the cost and complexity of hosting server code, such as java or .net, in a secure and robust environment. in this section: 1. what is apex? apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on salesforce servers in conjunction with calls to the api. using syntax that looks like java and acts like database stored procedures, apex enables 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. 2. understanding apex core concepts apex code typically contains many things that you might be familiar with from other programming languages. 3. when should i use apex? the salesforce prebuilt applications provide powerful crm functionality. in addition, salesforce provides the ability to customize the prebuilt applications to fit your organization. however, your organization may have complex business processes that are unsupported by the existing functionality. in this case, lightning platform provides various ways for advanced administrators and developers to build custom functionality. 4. how does apex work? all apex runs entirely on-demand on the lightning platform. developers write and save apex code to the platform, and end users trigger the execution of the apex code via the user interface. 5. developing code in the cloud the apex programming language is saved and runs in the cloud—the multitenant platform. apex is tailored for data access and data manipulation on the platform, and it enables you to add custom business logic to system events. while it provides many benefits for automating business processes on the platform, it is not a general purpose programming language. 2apex developer guide introducing apex what is apex? apex is a strongly typed, object-oriented programming language that allows developers to execute editions flow and transaction control statements on salesforce servers in conjunction with calls to the api. using syntax that looks like java and acts like database stored procedures, apex enables developers available in: salesforce to add business logic to most system events, including button clicks, related record updates, and classic (not available in all visualforce pages. apex code can be initiated by web service requests and from triggers on objects. orgs) and lightning experience available in: enterprise, performance, unlimited, developer, and database.com editions you can add apex to most system events. as a language, apex is: integrated apex provides built-in support for common lightning platform idioms, including: • data manipulation language (dml) calls, such as insert, update, and delete, that include built-in dmlexception handling 3apex developer guide introducing apex • inline salesforce object query language (soql) and salesforce object search language (sosl) queries that return lists of sobject records • looping that allows for bulk processing of multiple records at a time • locking syntax that prevents record update conflicts • custom public api calls that can be built from stored apex methods • warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by apex easy to use apex is based on familiar java idioms, such as variable and expression syntax, block and conditional statement syntax, loop syntax, object and array notation. where apex introduces new elements, it uses syntax and semantics that are easy to understand and encourage efficient use of the lightning platform. therefore, apex produces code that is both succinct and easy to write. data focused apex is designed to thread together multiple query and
dml statements into a single unit of work on the salesforce server. developers use database stored procedures to thread together multiple transaction statements on a database server in a similar way. like other database stored procedures, apex does not attempt to provide general support for rendering elements in the user interface. rigorous apex is a strongly typed language that uses direct references to schema objects such as object and field names. it fails quickly at compile time if any references are invalid. it stores all custom field, object, and class dependencies in metadata to ensure that they are not deleted while required by active apex code. hosted apex is interpreted, executed, and controlled entirely by the lightning platform. multitenant aware like the rest of the lightning platform, apex runs in a multitenant environment. so, 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. easy to test apex provides built-in support for unit test creation and execution. it includes test results that indicate how much code is covered, and which parts of your code could be more efficient. salesforce ensures that all custom apex code works as expected by executing all unit tests prior to any platform upgrades. versioned you can save your apex code against different versions of the api. this enables you to maintain behavior. apex is included in performance edition, unlimited edition, developer edition, enterprise edition, and database.com. understanding apex core concepts apex code typically contains many things that you might be familiar with from other programming languages. 4apex developer guide introducing apex programming elements in apex the section describes the basic functionality of apex, as well as some of the core concepts. using version settings in the salesforce user interface you can specify a version of the salesforce api against which to save your apex class or trigger. this setting indicates not only the version of soap api to use, but which version of apex as well. you can change the version after saving. every class or trigger name must be unique. you cannot save the same class or trigger against different versions. you can also use version settings to associate a class or trigger with a particular version of a managed package that is installed in your organization from appexchange. this version of the managed package will continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update the version setting. to add an installed managed package to the settings list, select a package from the list of available packages. the list is only displayed if you have an installed managed package that is not already associated with the class or trigger. for more information about using version settings with managed packages, see about package versions in the salesforce online help. 5apex developer guide introducing apex naming variables, methods and classes you cannot use any of the apex reserved keywords when naming variables, methods or classes. these include words that are part of apex and the lightning platform, such as list, test, or account, as well as reserved keywords. using variables and expressions apex is a strongly-typed language, that is, you must declare the data type of a variable when you first refer to it. apex data types include basic types such as integer, date, and boolean, as well as more advanced types such as lists, maps, objects and sobjects. variables are declared with a name and a data type. you can assign a value to a variable when you declare it. you can also assign values later. use the following syntax when declaring variables: datatype variable_name [ = value]; tip: note that the semi-colon at the end of the above is not optional. you must end all statements with a semi-colon. the following are examples of variable declarations: // the following variable has the data type of integer with the name count, // and has the value of 0. integer count = 0; // the following variable has the data type of decimal with the name total. note // that no value has been assigned to it. decimal total; // the following variable is an account, which is also referred to as an sobject. account myacct = new account(); in apex, all primitive data type arguments, such as integer or string, are passed into methods by value. this fact means that any changes to the arguments exist only within the scope of the method. when the method returns, the changes to the arguments are lost. non-primitive data type arguments, such as sobjects, are passed into methods by reference. therefore, when the method returns, the passed-in argument still
references the same object as before the method call. within the method, the reference can't be changed to point to another object, but the values of the object's fields can be changed. using statements a statement is any coded instruction that performs an action. in apex, statements must end with a semicolon and can be one of the following types: • assignment, such as assigning a value to a variable • conditional (if-else) • loops: – do-while – while – for • locking • data manipulation language (dml) • transaction control • method invoking • exception handling 6apex developer guide introducing apex a block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement would be allowed. for example: if (true) { system.debug(1); system.debug(2); } else { system.debug(3); system.debug(4); } in cases where a block consists of only one statement, the curly braces can be left off. for example: if (true) system.debug(1); else system.debug(2); using collections apex has the following types of collections: • lists (arrays) • maps • sets a list is a collection of elements, such as integers, strings, objects, or other collections. use a list when the sequence of elements is important. you can have duplicate elements in a list. the first index position in a list is always 0. to create a list: • use the new keyword • use the list keyword followed by the element type contained within <> characters. use the following syntax for creating a list: list <datatype> list_name [= new list<datatype>();] | [=new list<datatype>{value [, value2. . .]};] | ; the following example creates a list of integer, and assigns it to the variable my_list. remember, because apex is strongly typed, you must declare the data type of my_list as a list of integer. list<integer> my_list = new list<integer>(); for more information, see lists on page 28. a set is a collection of unique, unordered elements. it can contain primitive data types, such as string, integer, date, and so on. it can also contain more complex data types, such as sobjects. to create a set: • use the new keyword • use the set keyword followed by the primitive data type contained within <> characters 7apex developer guide introducing apex use the following syntax for creating a set: set<datatype> set_name [= new set<datatype>();] | [= new set<datatype>{value [, value2. . .] };] | ; the following example creates a set of string. the values for the set are passed in using the curly braces {}. set<string> my_string = new set<string>{'a', 'b', 'c'}; for more information, see sets on page 31. a map is a collection of key-value pairs. keys can be any primitive data type. values can include primitive data types, as well as objects and other collections. use a map when finding something by key matters. you can have duplicate values in a map, but each key must be unique. to create a map: • use the new keyword • use the map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters. use the following syntax for creating a map: map<key_datatype, value_datatype> map_name [=new map<key_datatype, value_datatype>();] | [=new map<key_datatype, value_datatype> {key1_value => value1_value [, key2_value => value2_value. . .]};] | ; the following example creates a map that has a data type of integer for the key and string for the value. in this example, the values for the map are being passed in between the curly braces {} as the map is being created. map<integer, string> my_map = new map<integer, string>{1 => 'a', 2 => 'b', 3 => 'c'}; for more information, see maps on page 32. using branching an if statement is a true-false test that enables your application to
do different things based on a condition. the basic syntax is as follows: if (condition){ // do this if the condition is true } else { // do this if the condition is not true } for more information, see conditional (if-else) statements on page 51. using loops while the if statement enables your application to do things based on a condition, loops tell your application to do the same thing again and again based on a condition. apex supports the following types of loops: • do-while 8apex developer guide introducing apex • while • for a do-while loop checks the condition after the code has executed. a while loop checks the condition at the start, before the code executes. a for loop enables you to more finely control the condition used with the loop. in addition, apex supports traditional for loops where you set the conditions, as well as for loops that use lists and soql queries as part of the condition. for more information, see loops on page 55. when should i use apex? the salesforce prebuilt applications provide powerful crm functionality. in addition, salesforce provides the ability to customize the prebuilt applications to fit your organization. however, your organization may have complex business processes that are unsupported by the existing functionality. in this case, lightning platform provides various ways for advanced administrators and developers to build custom functionality. apex use apex if you want to: • create web services. • create email services. • perform complex validation over multiple objects. • create complex business processes that are not supported by workflow. • create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object). • attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless of whether it originates in the user interface, a visualforce page, or from soap api. lightning components develop lightning components to customize lightning experience, the salesforce mobile app, or to build your own standalone apps. you can also use out-of-the-box components to speed up development. as of spring ’19 (api version 45.0), you can build lightning components using two programming models: the lightning web components model, and the original aura components model. lightning web components are custom html elements built using html and modern javascript. lightning web components and aura components can coexist and interoperate on a page.configure lightning web components and aura components to work in lightning app builder and experience builder. admins and end users don’t know which programming model was used to develop the components. to them, they’re simply lightning components. for more information, see the component library. visualforce visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing the salesforce user interface. with visualforce you can: • build wizards and other multistep processes. • create your own custom flow control through an application. • define navigation patterns and data-specific rules for optimal, efficient application interaction. 9apex developer guide introducing apex for more information, see the visualforce developer's guide. soap api use standard soap api calls if you want to add functionality to a composite application that processes only one type of record at a time and does not require any transactional control (such as setting a savepoint or rolling back changes). for more information, see the soap api developer guide. how does apex work? all apex runs entirely on-demand on the lightning platform. developers write and save apex code to the platform, and end users trigger the execution of the apex code via the user interface. apex is compiled, stored, and run entirely on the lightning platform when a developer writes and saves apex code to the platform, the platform application server first compiles the code into an abstract set of instructions that can be understood by the apex runtime interpreter, and then saves those instructions as metadata. when an end user triggers the execution of apex, perhaps 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 from standard platform requests. developing code in the cloud the apex programming language is saved and runs in the cloud—the multitenant platform. apex is tailored for data access and data manipulation on the platform, and it enables you to add custom business logic to system events. while it provides many benefits for automating business processes on the platform, it is not a general purpose programming language. apex cannot be used
to: • render elements in the user interface other than error messages • change standard functionality—apex can only prevent the functionality from happening, or add additional functionality • create temporary files • spawn threads tip: all apex code runs on the lightning platform, which is a shared resource used by all other organizations. to guarantee consistent performance and scalability, the execution of apex is bound by governor limits that ensure no single apex execution impacts the overall service of salesforce. this means all apex code is limited by the number of operations (such as dml or soql) that it can perform within one process. 10apex developer guide apex development process all apex requests return a collection that contains from 1 to 50,000 records. you cannot assume that your code only works on a single record at a time. therefore, you must implement programming patterns that take bulk processing into account. if you don’t, you may run into the governor limits. see also: trigger and bulk request best practices apex development process in this chapter, you’ll learn about the apex development lifecycle, and which organization and tools to use to develop apex. you’ll also learn about testing and deploying apex code. in this section: what is the apex development process? to develop apex, get a developer edition account, write and test your code, then deploy your code. create a developer or sandbox org you can run apex in a production org, a developer org, or a sandbox org. you can develop apex in a developer org or a sandbox org, but not in a production org. learning apex after you have your developer account, there are many resources available to you for learning about apex writing apex using development environments there are several development environments for developing apex code. the developer console and the salesforce extensions for visual studio code allow you to write, test, and debug your apex code. the code editor in the user interface enables only writing code and doesn’t support debugging. writing tests testing is the key to successful long-term development and is a critical component of the development process. we strongly recommend that you use a test-driven development process, that is, test development that occurs at the same time as code development. deploying apex to a sandbox organization sandboxes create copies of your salesforce org in separate environments. use them for development, testing, and training without compromising the data and applications in your production org. sandboxes are isolated from your production org, so operations that you perform in your sandboxes don’t affect your production org. deploying apex to a salesforce production organization after you have finished all of your unit tests and verified that your apex code is executing properly, the final step is deploying apex to your salesforce production organization. adding apex code to a appexchange app you can include an apex class or trigger in an app that you are creating for appexchange. what is the apex development process? to develop apex, get a developer edition account, write and test your code, then deploy your code. we recommend the following process for developing apex: 1. obtain a developer edition account. 11apex developer guide apex development process 2. learn more about apex. 3. write your apex. 4. while writing apex, you should also be writing tests. 5. optionally deploy your apex to a sandbox organization and do final unit tests. 6. deploy your apex to your salesforce production organization. in addition to deploying your apex, once it is written and tested, you can also add your classes and triggers to a appexchange app package. create a developer or sandbox org you can run apex in a production org, a developer org, or a sandbox org. you can develop apex in a developer org or a sandbox org, but not in a production org. • production org—an org that has live users accessing your data • developer org—an org created with a developer edition account • sandbox org—an org created on your production org that is a copy of your production org note: apex triggers are available in the trial edition of salesforce. however, they are disabled when you convert to any other edition. if your newly signed-up org includes apex, deploy your code to your org using one of the deployment methods. you can't develop apex in your salesforce production org. live users accessing the system while you're developing can destabilize your data or corrupt your application. instead, do all your development work in either a sandbox or a developer edition org. if you aren't already a member of the developer community, go to https://developer.salesforce.com/signup and follow the instructions to sign up for a
developer edition account. a developer edition account gives you access to a free developer edition org. even if you already have a professional, enterprise, unlimited, or performance edition org and a sandbox for creating apex, we strongly recommend that you take advantage of the resources available in the developer community. note: you can’t modify apex using the salesforce user interface in a salesforce production org. to create a sandbox org: 1. from setup, enter sandboxes in the quick find box, then select sandboxes. 2. click new sandbox. 3. enter a name (10 characters or fewer) and description for the sandbox. we recommend that you choose a name that: • reflects the purpose of this sandbox, such as qa. • has only a few characters, because salesforce appends the sandbox name to usernames on user records in the sandbox environment. names with fewer characters make sandbox logins easier to type. 4. select the type of sandbox you want. if your production org is hosted on an eligible hyperforce instance, our quick create technology enhances the speed at which a full sandbox is created. if you don’t see a sandbox option or need licenses for more, contact salesforce to order sandboxes for your org. if you reduce the number of sandboxes you purchase, you’re required to match the number of your sandboxes to the number you purchased. for example, if you have two full sandboxes but purchased only one, you can’t create a full sandbox. instead, convert a full sandbox to a smaller one, such as a developer pro or developer sandbox, depending on which types you have available. 5. select the data to include in your partial copy or full sandbox. 12apex developer guide apex development process • for a partial copy sandbox, click next, and then select the template you created to specify the data for your sandbox. if you haven’t created a template for this partial copy sandbox, see create or edit sandbox templates. • for a full sandbox click next, and then decide how much data to include. – to include template-based data for a full sandbox, select an existing sandbox template. for more information, see create or edit sandbox templates – to include all data in a full sandbox, choose whether and how much field tracking history data to include, and whether to copy chatter data. chatter data includes feeds, messages, and topics and is used in many components that affect your sandbox copy. decreasing the amount of data you copy can significantly speed sandbox copy time. 6. to run scripts after each create and refresh for this sandbox, specify the apex class you previously created from the sandboxpostcopy interface. 7. click create. tip: try to limit changes in your production org while the sandbox copy proceeds. learning apex after you have your developer account, there are many resources available to you for learning about apex apex trailhead content beginning and intermediate programmers several trailhead modules provide tutorials on learning apex. use these modules to learn the fundamentals of apex and how you can use it on the lightning platform. use apex to add custom business logic through triggers, unit tests, asynchronous apex, rest web services, and visualforce controllers. quick start: apex apex basics & database apex triggers apex integration services apex testing asynchronous apex salesforce developers apex page beginning and advanced programmers the apex page on salesforce developers has links to several resources including articles about the apex programming language. these resources provide a quick introduction to apex and include best practices for apex development. lightning platform code samples and sdks beginning and advanced programmers open-source code samples and sdks, reference code, and best practices can be found at code samples and sdks. a library of concise, meaningful examples of apex code for common use cases, following best practices, can be found at apex-recipes. development life cycle: enterprise development on the lightning platform architects and advanced programmers the application lifecycle and development models module on trailhead helps you learn how to use the application lifecycle and development models on the lightning platform. training courses training classes are also available from salesforce trailhead academy. grow and validate your skills with salesforce credentials. 13apex developer guide apex development process in this book (apex developer's guide) beginning programmers can look at the following: • introducing apex, and in particular: – documentation conventions – core concepts – quick start tutorial • classes, objects, and interfaces • testing apex • execution governors and limits in addition, advanced programmers can look at: • trigger and bulk request best practices •
advanced apex programming example • understanding apex describe information • asynchronous execution (@future annotation) • batch apex and apex scheduler writing apex using development environments there are several development environments for developing apex code. the developer console and the salesforce extensions for visual studio code allow you to write, test, and debug your apex code. the code editor in the user interface enables only writing code and doesn’t support debugging. developer console the developer console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your salesforce organization. the developer console supports these tasks: • writing code—you can add code using the source code editor. also, you can browse packages in your organization. • compiling code—when you save a trigger or class, the code is automatically compiled. any compilation errors will be reported. • debugging—you can view debug logs and set checkpoints that aid in debugging. • testing—you can execute tests of specific test classes or all tests in your organization, and you can view test results. also, you can inspect code coverage. • checking performance—you can inspect debug logs to locate performance bottlenecks. • soql queries—you can query data in your organization and view the results using the query editor. • color coding and autocomplete—the source code editor uses a color scheme for easier readability of code elements and provides autocompletion for class and method names. salesforce extensions for visual studio code the salesforce extension pack for visual studio code includes tools for developing on the salesforce platform in the lightweight, extensible vs code editor. these tools provide features for working with development orgs (scratch orgs, sandboxes, and de orgs), apex, aura components, and visualforce. see the website for information about installation and usage. 14apex developer guide apex development process tip: if you want to develop an apex ide of your own, the soap api includes methods for compiling triggers and classes, and executing test methods, while the metadata api includes methods for deploying code to production environments. for more information, see deploying apex on page 668 and using soap api to deploy apex on page 674. code editor in the salesforce user interface the salesforce user interface. all classes and triggers are compiled when they are saved, and any syntax errors are flagged. you cannot save your code until it compiles without errors. the salesforce user interface also numbers the lines in the code, and uses color coding to distinguish different elements, such as comments, keywords, literal strings, and so on. • for a trigger on an object, from the object’s management settings, go to triggers, click new, and then enter your code in the body text box. • for a class, from setup, enter apex classes in the quick find box, then select apex classes. click new, and then enter your code in the body text box. note: you can’t modify apex using the salesforce user interface in a salesforce production org. alternatively, you can use any text editor, such as notepad, to write apex code. then either copy and paste the code into your application, or use one of the api calls to deploy it. see also: salesforce help: find object management settings writing tests testing is the key to successful long-term development and is a critical component of the development process. we strongly recommend that you use a test-driven development process, that is, test development that occurs at the same time as code development. to facilitate the development of robust, error-free code, apex supports the creation and execution of unit tests. 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 send no emails. such methods are flagged with the @istest annotation in the method definition. unit test methods must be defined in test classes, that is, classes annotated with @istest. note: the @istest annotation on methods is equivalent to the testmethod keyword. as best practice, salesforce recommends that you use @istest rather than testmethod. the testmethod keyword may be versioned out in a future release. in addition, before you deploy apex or package it for the appexchange, the following must be true. • unit tests must cover at least 75% of your apex code, and all of those tests must complete successfully. note the following. – when deploying apex to a production organization, each unit test in your organization namespace is executed by default. – calls to system.debug aren’t counted as part of
apex code coverage. – test methods and test classes aren’t counted as part of apex code coverage. – while only 75% of your apex code must be covered by tests, don’t focus on the percentage of code that is covered. instead, make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. this approach ensures that 75% or more of your code is covered by unit tests. • every trigger must have some test coverage. • all classes and triggers must compile successfully. 15apex developer guide apex quick start for more information on writing tests, see testing apex on page 634. deploying apex to a sandbox organization sandboxes create copies of your salesforce org in separate environments. use them for development, testing, and training without compromising the data and applications in your production org. sandboxes are isolated from your production org, so operations that you perform in your sandboxes don’t affect your production org. to deploy apex from a local project in the salesforce extension for visual studio code to a salesforce organization, see salesforce extensions for visual studio code. you can also use the deploy() metadata api call to deploy your apex from a developer organization to a sandbox organization. a useful api call is runtests(). in a development or sandbox organization, you can run the unit tests for a specific class, a list of classes, or a namespace. you can also use salesforce cli. see develop against any org for details. for more information, see deploying apex. deploying apex to a salesforce production organization after you have finished all of your unit tests and verified that your apex code is executing properly, the final step is deploying apex to your salesforce production organization. to deploy apex from a local project in visual studio code editor to a salesforce organization, see salesforce extensions for visual studio code. also, you can deploy apex through change sets in the salesforce user interface. for more information and for additional deployment options, see deploying apex on page 668, and build and release your app. adding apex code to a appexchange app you can include an apex class or trigger in an app that you are creating for appexchange. any apex that is included as part of a package must have at least 75% cumulative test coverage. each trigger must also have some test coverage. when you upload your package to appexchange, all tests are run to ensure that they run without errors. in addition, tests with the@istest(oninstall=true) annotation run when the package is installed in the installer's organization. you can specify which tests should run during package install by annotating them with @istest(oninstall=true). this subset of tests must pass for the package install to succeed. in addition, salesforce recommends that any appexchange package that contains apex be a managed package. for more information, see the quick reference for developing packages. for more information about apex in managed packages, see “what is a package” in the salesforce online help. note: packaging apex classes that contain references to custom labels which have translations: to include the translations in the package, enable the translation workbench and explicitly package the individual languages used in the translated custom labels. see “custom labels” in the salesforce online help. apex quick start this step-by-step tutorial shows how to create a simple apex class and trigger, and how to deploy these components to a production organization. 16apex developer guide apex quick start once you have a developer edition or sandbox organization, you may want to learn some of the core concepts of apex. after reviewing the basics, you are ready to write your first apex program—a very simple class, trigger, and unit test. because apex is very similar to java, you may recognize much of the functionality. this tutorial is based on a custom object called book that is created in the first step. this custom object is updated through a trigger. this hello world sample requires custom objects. you can either create these on your own, or download the objects and apex code as an unmanaged package from the salesforce appexchange. to obtain the sample assets in your org, install the apex tutorials package. this package also contains sample code and objects for the shipping invoice example. note: there is a more complex shipping invoice example that you can also walk through. that example illustrates many more features of the language. in this section: 1. create a custom object in this step, you create a custom object called book with one custom field called price. 2. adding an apex class in this step, you
add an apex class that contains a method for updating the book price. this method is called by the trigger that you will be adding in the next step. 3. add an apex trigger in this step, you create a trigger for the book__c custom object that calls the applydiscount method of the myhelloworld class that you created in the previous step. 4. add a test class in this step, you add a test class with one test method. you also run the test and verify code coverage. the test method exercises and validates the code in the trigger and class. also, it enables you to reach 100% code coverage for the trigger and class. 5. deploying components to production in this step, you deploy the apex code and the custom object you created previously to your production organization using change sets. create a custom object in this step, you create a custom object called book with one custom field called price. prerequisites: a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. for more information about creating a sandbox org, see “sandbox types and templates” in the salesforce help. to sign up for a free developer org, see the developer edition environment sign up page. 1. log in to your sandbox or developer org. 2. from your management settings for custom objects, if you’re using salesforce classic, click new custom object, or if you’re using lightning experience, select create > custom object. 3. enter book for the label. 4. enter books for the plural label. 5. click save. ta dah! you’ve now created your first custom object. now let’s create a custom field. 6. in the custom fields & relationships section of the book detail page, click new. 17apex developer guide apex quick start 7. select number for the data type and click next. 8. enter price for the field label. 9. enter 16 in the length text box. 10.enter 2 in the decimal places text box, and click next. 11.click next to accept the default values for field-level security. 12.click save. you’ve just created a custom object called book, and added a custom field to that custom object. custom objects already have some standard fields, like name and createdby, and allow you to add other fields that are more specific to your implementation. for this tutorial, the price field is part of our book object and it is accessed by the apex class you will write in the next step. see also: salesforce help: find object management settings adding an apex class in this step, you add an apex class that contains a method for updating the book price. this method is called by the trigger that you will be adding in the next step. prerequisites: • a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. • the book custom object. 1. from setup, enter “apex classes” in the quick find box, then select apex classes and click new. 2. in the class editor, enter this class definition: public class myhelloworld { } the previous code is the class definition to which you will be adding one method in the next step. apex code is generally contained in classes. this class is defined as public, which means the class is available to other apex classes and triggers. for more information, see classes, objects, and interfaces on page 58. 3. add this method definition between the class opening and closing brackets. public static void applydiscount(book__c[] books) { for (book__c b :books){ b.price__c *= 0.9; } } this method is called applydiscount, and it is both public and static. because it is a static method, you don't need to create an instance of the class to access the method—you can just use the name of the class followed by a dot (.) and the name of the method. for more information, see static and instance methods, variables, and initialization code on page 67. this method takes one parameter, a list of book records, which is assigned to the variable books. notice the __c in the object name book__c. this indicates that it is a custom object that you created. standard objects that are provided in the salesforce application, such as account, don't end with this postfix. 18apex developer guide apex quick start the next section of code contains the rest of the method definition: for (book__c b :
books){ b.price__c *= 0.9; } notice the __c after the field name price__c. this indicates it is a custom field that you created. standard fields that are provided by default in salesforce are accessed using the same type of dot notation but without the __c, for example, name doesn't end with __c in book__c.name. the statement b.price__c *= 0.9; takes the old value of b.price__c, multiplies it by 0.9, which means its value will be discounted by 10%, and then stores the new value into the b.price__c field. the *= operator is a shortcut. another way to write this statement is b.price__c = b.price__c * 0.9;. see expression operators on page 38. 4. click save to save the new class. you should now have this full class definition. public class myhelloworld { public static void applydiscount(book__c[] books) { for (book__c b :books){ b.price__c *= 0.9; } } } you now have a class that contains some code that iterates over a list of books and updates the price field for each book. this code is part of the applydiscount static method called by the trigger that you will create in the next step. add an apex trigger in this step, you create a trigger for the book__c custom object that calls the applydiscount method of the myhelloworld class that you created in the previous step. prerequisites: • a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. • the myhelloworld apex class. a trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the lightning platform database. every trigger runs with a set of context variables that provide access to the records that caused the trigger to fire. all triggers run in bulk; that is, they process several records at once. 1. from the object management settings for books, go to triggers, and then click new. 2. in the trigger editor, delete the default template code and enter this trigger definition: trigger helloworldtrigger on book__c (before insert) { book__c[] books = trigger.new; myhelloworld.applydiscount(books); } the first line of code defines the trigger: trigger helloworldtrigger on book__c (before insert) { it gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. for example, this trigger is called helloworldtrigger, it operates on the book__c object, and runs before new books are inserted into the database. 19apex developer guide apex quick start the next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context variable called trigger.new. trigger context variables such as trigger.new are implicitly defined in all triggers and provide access to the records that caused the trigger to fire. in this case, trigger.new contains all the new books that are about to be inserted. book__c[] books = trigger.new; the next line in the code calls the method applydiscount in the myhelloworld class. it passes in the array of new books. myhelloworld.applydiscount(books); you now have all the code that is needed to update the price of all books that get inserted. however, there is still one piece of the puzzle missing. unit tests are an important part of writing code and are required. in the next step, you will see why this is so and you will be able to add a test class. see also: salesforce help: find object management settings add a test class in this step, you add a test class with one test method. you also run the test and verify code coverage. the test method exercises and validates the code in the trigger and class. also, it enables you to reach 100% code coverage for the trigger and class. prerequisites: • a salesforce account in a sandbox professional, enterprise, performance, or unlimited edition org, or an account in a developer org. • the helloworldtrigger apex trigger. note: testing is an important part of the development process. before you can deploy apex or package it for appexchange, the following must be true. • unit tests must cover at least 75% of your apex code, and all of those tests must complete successfully. note the following. – when deploying apex to a production organization,
each unit test in your organization namespace is executed by default. – calls to system.debug aren’t counted as part of apex code coverage. – test methods and test classes aren’t counted as part of apex code coverage. – while only 75% of your apex code must be covered by tests, don’t focus on the percentage of code that is covered. instead, make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. this approach ensures that 75% or more of your code is covered by unit tests. • every trigger must have some test coverage. • all classes and triggers must compile successfully. 1. from setup, enter apex classes in the quick find box, then select apex classes and click new. 2. in the class editor, add this test class definition, and then click save. @istest private class helloworldtestclass { @istest static void validatehelloworld() { book__c b = new book__c(name='behind the cloud', price__c=100); system.debug('price before inserting new book: ' + b.price__c); 20apex developer guide apex quick start // insert book insert b; // retrieve the new book b = [select price__c from book__c where id =:b.id]; system.debug('price after trigger fired: ' + b.price__c); // test that the trigger correctly updated the price system.assertequals(90, b.price__c); } } this class is defined using the @istest annotation. classes defined this way should only contain test methods and any methods required to support those test methods. one advantage to creating a separate class for testing is that classes defined with @istest don’t count against your org’s limit of 6 mb of apex code. you can also add the @istest annotation to individual methods. for more information, see @istest annotation on page 98 and execution governors and limits. the method validatehelloworld is defined using the @istest annotation. this annotation means that if changes are made to the database, they’re rolled back when execution completes. you don’t have to delete any test data created in the test method. note: the @istest annotation on methods is equivalent to the testmethod keyword. as best practice, salesforce recommends that you use @istest rather than testmethod. the testmethod keyword may be versioned out in a future release. first, the test method creates a book and inserts it into the database temporarily. the system.debug statement writes the value of the price in the debug log. book__c b = new book__c(name='behind the cloud', price__c=100); system.debug('price before inserting new book: ' + b.price__c); // insert book insert b; after the book is inserted, the code retrieves the newly inserted book, using the id that was initially assigned to the book when it was inserted. the system.debug statement then logs the new price that the trigger modified. // retrieve the new book b = [select price__c from book__c where id =:b.id]; system.debug('price after trigger fired: ' + b.price__c); when the myhelloworld class runs, it updates the price__c field and reduces its value by 10%. the following test verifies that the method applydiscount ran and produced the expected result. // test that the trigger correctly updated the price system.assertequals(90, b.price__c); 3. to run this test and view code coverage information, switch to the developer console. 4. in the developer console, click test > new run. 5. to select your test class, click helloworldtestclass. 6. to add all methods in the helloworldtestclass class to the test run, click add selected. 7. click run. the test result displays in the tests tab. optionally, you can expand the test class in the tests tab to view which methods were run. in this case, the class contains only one test method. 21apex developer guide apex quick start 8. the overall code coverage pane shows the code coverage of this test class. to view the percentage of lines of code in the trigger covered by this test, which is 100%, double-click the code coverage line for helloworldtrigger. because the trigger calls a method from the myhelloworld class, this class also has coverage (100%). to view the class coverage, double-click myhelloworld. 9. to open the log file,
in the logs tab, double-click the most recent log line in the list of logs. the execution log displays, including logging information about the trigger event, the call to the applydiscount method, and the price before and after the trigger. by now, you’ve completed all the steps necessary for writing some apex code with a test that runs in your development environment. in the real world, after you’ve tested your code and are satisfied with it, you want to deploy the code and any prerequisite components to a production org. the next step shows you how to do this deployment for the code and custom object you’ve created. see also: salesforce help: open the developer console deploying components to production in this step, you deploy the apex code and the custom object you created previously to your production organization using change sets. prerequisites: • a salesforce account in a sandbox performance, unlimited, or enterprise edition organization. • the helloworldtestclass apex test class. • a deployment connection between the sandbox and production organizations that allows inbound change sets to be received by the production organization. see “change sets” in the salesforce online help. • “create and upload change sets” user permission to create, edit, or upload outbound change sets. this procedure doesn't apply to developer organizations since change sets are available only in performance, unlimited, enterprise, or database.com edition organizations. if you have a developer edition account, you can use other deployment methods. for more information, see deploying apex. 1. from setup, enter outbound changesets in the quick find box, then select outbound changesets. 2. if a splash page appears, click continue. 3. in the change sets list, click new. 4. enter a name for your change set, for example, helloworldchangeset, and optionally a description. click save. 5. in the change set components section, click add. 6. select apex class from the component type drop-down list, then select the myhelloworld and the helloworldtestclass classes from the list and click add to change set. 7. click view/add dependencies to add the dependent components. 8. select the top checkbox to select all components. click add to change set. 9. in the change set detail section of the change set page, click upload. 10.select the target organization, in this case production, and click upload. 11.after the change set upload completes, deploy it in your production organization. a. log into your production organization. b. from setup, enter inbound change sets in the quick find box, then select inbound change sets. c. if a splash page appears, click continue. d. in the change sets awaiting deployment list, click your change set's name. 22apex developer guide writing apex e. click deploy. in this tutorial, you learned how to create a custom object, how to add an apex trigger, class, and test class. finally, you also learned how to test your code, and how to upload the code and the custom object using change sets. writing apex apex is like java for salesforce. it enables you to add and interact with data in the lightning platform persistence layer. it uses classes, data types, variables, and if-else statements. you can make it execute based on a condition, or have a block of code execute repeatedly. in this section: data types and variables apex uses data types, variables, and related language constructs such as enums, constants, expressions, operators, and assignment statements. control flow statements apex provides if-else statements, switch statements, and loops to control the flow of code execution. statements are generally executed line by line, in the order they appear. with control flow statements, you can make apex code execute based on a certain condition, or have a block of code execute repeatedly. working with data in apex you can add and interact with data in the lightning platform persistence layer. the sobject data type is the main data type that holds data objects. you’ll use data manipulation language (dml) to work with data, and use query languages to retrieve data, such as the (), among other things. data types and variables apex uses data types, variables, and related language constructs such as enums, constants, expressions, operators, and assignment statements. in this section: 1. data types in apex, all variables and expressions have a data type, such as sobject, primitive, or enum. 2. primitive data types apex uses the same primitive data types as soap api, except for higher-precision dec
imal type in certain cases. all primitive data types are passed by value. 3. collections collections in apex can be lists, sets, or maps. 4. enums an enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. enums are typically used to define a set of possible values that don’t otherwise have a numerical order. typical examples include the suit of a card, or a particular season of the year. 5. variables local variables are declared with java-style syntax. as with java, multiple variables can be declared and initialized in a single statement. 23apex developer guide data types and variables 6. constants apex constants are variables whose values don’t change after being initialized once. constants can be defined using the final keyword. 7. expressions and operators an expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. 8. assignment statements an assignment statement is any statement that places a value into a variable. 9. rules of conversion in general, apex requires you to explicitly convert one data type to another. for example, a variable of the integer data type cannot be implicitly converted to a string. you must use the string.format method. however, a few data types can be implicitly converted, without using a method. data types in apex, all variables and expressions have a data type, such as sobject, primitive, or enum. • a primitive, such as an integer, double, long, date, datetime, string, id, or boolean (see primitive data types on page 24) • an sobject, either as a generic sobject or as a specific sobject, such as an account, contact, or mycustomobject__c (see working with sobjects on page 122 in chapter 4.) • a collection, including: – a list (or array) of primitives, sobjects, user defined objects, objects created from apex classes, or collections (see lists on page 28) – a set of primitives (see sets on page 31) – a map from a primitive to a primitive, sobject, or collection (see maps on page 32) • a typed list of values, also known as an enum (see enums on page 33) • objects created from user-defined apex classes (see classes, objects, and interfaces on page 58) • objects created from system supplied apex classes • null (for the null constant, which can be assigned to any variable) methods can return values of any of the listed types, or return no value and be of type void. type checking is strictly enforced at compile time. for example, the parser generates an error if an object field of type integer is assigned a value of type string. however, all compile-time exceptions are returned as specific fault codes, with the line number and column of the error. for more information, see debugging apex on page 595. primitive data types apex uses the same primitive data types as soap api, except for higher-precision decimal type in certain cases. all primitive data types are passed by value. all apex variables, whether they’re class member variables or method variables, are initialized to null. make sure that you initialize your variables to appropriate values before using them. for example, initialize a boolean variable to false. apex primitive data types include: 24apex developer guide data types and variables data type description blob a collection of binary data stored as a single object. you can convert this data type to string or from string using the tostring and valueof methods, respectively. blobs can be accepted as web service arguments, stored in a document (the body of a document is a blob), or sent as attachments. for more information, see crypto class. boolean a value that can only be assigned true, false, or null. for example: boolean iswinner = true; date a value that indicates a particular day. unlike datetime values, date values contain no information about time. always create date values with a system static method. you can add or subtract an integer value from a date value, returning a date value. addition and subtraction of integer values are the only arithmetic functions that work with date values. you can’t perform arithmetic functions that include two or more date values. instead, use the date methods. use the string.valueof() method to obtain the date without an appended timestamp. using an implicit string conversion with a date value results in the date with the timestamp appended. datetime a value that indicates a particular day and time
, such as a timestamp. always create datetime values with a system static method. you can add or subtract an integer or double value from a datetime value, returning a date value. addition and subtraction of integer and double values are the only arithmetic functions that work with datetime values. you can’t perform arithmetic functions that include two or more datetime values. instead, use the datetime methods. decimal a number that includes a decimal point. decimal is an arbitrary precision number. currency fields are automatically assigned the type decimal. if you don’t explicitly set the number of decimal places for a decimal, the item from which the decimal is created determines the decimal’s scale. scale is a count of decimal places. use the setscale method to set a decimal’s scale. • if the decimal is created as part of a query, the scale is based on the scale of the field returned from the query. • if the decimal is created from a string, the scale is the number of characters after the decimal point of the string. • if the decimal is created from a non-decimal number, the number is first converted to a string. scale is then set using the number of characters after the decimal point. note: two decimal objects that are numerically equivalent but differ in scale (such as 1.1 and 1.10) generally do not have the same hashcode. use caution when such decimal objects are used in sets or as map keys. double a 64-bit number that includes a decimal point. doubles have a minimum value of -263 and a maximum value of 263-1. for example: double pi = 3.14159; double e = 2.7182818284d; scientific notation (e) for doubles isn’t supported. 25apex developer guide data types and variables data type description id any valid 18-character lightning platform record identifier. for example: id id='00300000003t2pgaa0'; if you set id to a 15-character value, apex converts the value to its 18-character representation. all invalid id values are rejected with a runtime exception. integer a 32-bit number that doesn’t include a decimal point. integers have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647. for example: integer i = 1; long a 64-bit number that doesn’t include a decimal point. longs have a minimum value of -263 and a maximum value of 263-1. use this data type when you need a range of values wider than the range provided by integer. for example: long l = 2147483648l; object any data type that is supported in apex. apex supports primitive data types (such as integer), user-defined custom classes, the sobject generic type, or an sobject specific type (such as account). all apex data types inherit from object. you can cast an object that represents a more specific data type to its underlying data type. for example: object obj = 10; // cast the object to an integer. integer i = (integer)obj; system.assertequals(10, i); the next example shows how to cast an object to a user-defined type—a custom apex class named myapexclass that is predefined in your organization. object obj = new myapexclass(); // cast the object to the myapexclass custom type. myapexclass mc = (myapexclass)obj; // access a method on the user-defined class. mc.someclassmethod(); string any set of characters surrounded by single quotes. for example, string s = 'the quick brown fox jumped over the lazy dog.'; string size: strings have no limit on the number of characters they can include. instead, the heap size limit is used to ensure that your apex programs don't grow too large. empty strings and trailing whitespace: sobject string field values follow the same rules as in soap api: they can never be empty (only null), and they can never include leading and trailing whitespace. these conventions are necessary for database storage. conversely, strings in apex can be null or empty and can include leading and trailing whitespace, which can be used to construct a message. 26apex developer guide data types and variables data type description the solution sobject field solutionnote operates as a special type of string. if you have html solutions enabled, any html tags used in this field are verified before the
object is created or updated. if invalid html is entered, an error is thrown. any javascript used in this field is removed before the object is created or updated. in the following example, when the solution displays on a detail page, the solutionnote field has h1 html formatting applied to it: trigger t on solution (before insert) { trigger.new[0].solutionnote ='<h1>hello</h1>'; } in the following example, when the solution displays on a detail page, the solutionnote field only contains hellogoodbye: trigger t2 on solution (before insert) { trigger.new[0].solutionnote = '<javascript>hello</javascript>goodbye'; } for more information, see “html solutions overview” in salesforce help. escapesequences: all strings in apex use the same escape sequences as soql strings: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash). comparison operators: unlike java, apex strings support using the comparison operators ==, !=, <, <=, >, and >=. because apex uses soql comparison semantics, results for strings are collated according to the context user’s locale and aren’t case-sensitive. for more information, see expression operators. string methods: as in java, strings can be manipulated with several standard methods. for more information, see string class. apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. time a value that indicates a particular time. always create time values with a system static method. see time class. in addition, two non-standard primitive data types can’t be used as variable or method types, but do appear in system static methods: • anytype. the valueof static method converts an sobject field of type anytype to a standard primitive. anytype is used within the lightning platform database exclusively for sobject fields in field history tracking tables. • currency. the currency.newinstance static method creates a literal of type currency. this method is for use solely within soql and sosl where clauses to filter against sobject currency fields. you can’t instantiate currency in any other type of apex. for more information on the anytype data type, see field types in the object reference for salesforce. 27apex developer guide data types and variables versioned behavior changes in api version 16 (summer ’09) and later, apex uses the higher-precision decimal data type in certain types such as currency. see also: expression operators collections collections in apex can be lists, sets, or maps. note: there is no limit on the number of items a collection can hold. however, there is a general limit on heap size. in this section: lists a list is an ordered collection of elements that are distinguished by their indices. list elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. sets a set is an unordered collection of elements that do not contain any duplicates. set elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. maps a map is a collection of key-value pairs where each unique key maps to a single value. keys and values can be any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. parameterized typing apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before that variable can be used. see also: execution governors and limits lists a list is an ordered collection of elements that are distinguished by their indices. list elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. this table is a visual representation of a list of strings: index 0 index 1 index 2 index 3 index 4 index 5 'red' 'orange' 'yellow' 'green' 'blue' 'purple' the index position of the first element in a list is always 0. lists can contain any collection and can be nested within one another and become multidimensional. for example, you can have a list
of lists of sets of integers. a list can contain up to seven levels of nested collections inside it, that is, up to eight levels overall. 28apex developer guide data types and variables to declare a list, use the list keyword followed by the primitive data, sobject, nested list, map, or set type within <> characters. for example: // create an empty list of string list<string> my_list = new list<string>(); // create a nested list list<list<set<integer>>> my_list_2 = new list<list<set<integer>>>(); to access elements in a list, use the list methods provided by apex. for example: list<integer> mylist = new list<integer>(); // define a new list mylist.add(47); // adds a second element of value 47 to the end // of the list integer i = mylist.get(0); // retrieves the element at index 0 mylist.set(0, 1); // adds the integer 1 to the list at index 0 mylist.clear(); // removes all elements from the list for more information, including a complete list of all supported methods, see list class. using array notation for one-dimensional lists when using one-dimensional lists of primitives or objects, you can also use more traditional array notation to declare and reference list elements. for example, you can declare a one-dimensional list of primitives or objects by following the data type name with the [] characters: string[] colors = new list<string>(); these two statements are equivalent to the previous: list<string> colors = new string[1]; string[] colors = new string[1]; to reference an element of a one-dimensional list, you can also follow the name of the list with the element's index position in square brackets. for example: colors[0] = 'green'; even though the size of the previous string array is defined as one element (the number between the brackets in new string[1]), lists are elastic and can grow as needed provided that you use the list add method to add new elements. for example, you can add two or more elements to the colors list. but if you’re using square brackets to add an element to a list, the list behaves like an array and isn’t elastic, that is, you won’t be allowed to add more elements than the declared array size. all lists are initialized to null. lists can be assigned values and allocated memory using literal notation. for example: example description defines an integer list of size zero with no elements list<integer> ints = new integer[0]; defines an integer list with memory allocated for six integers list<integer> ints = new integer[6]; 29apex developer guide data types and variables in this section: list sorting you can sort list elements and the sort order depends on the data type of the elements. list sorting you can sort list elements and the sort order depends on the data type of the elements. using the list.sort method, you can sort elements in a list. sorting is in ascending order for elements of primitive data types, such as strings. the sort order of other more complex data types is described in the chapters covering those data types. this example shows how to sort a list of strings and verifies that the colors are in ascending order in the list. list<string> colors = new list<string>{ 'yellow', 'red', 'green'}; colors.sort(); system.assertequals('green', colors.get(0)); system.assertequals('red', colors.get(1)); system.assertequals('yellow', colors.get(2)); for the visualforce selectoption control, sorting is in ascending order based on the value and label fields. see this next section for the sequence of comparison steps used for selectoption. default sort order for selectoption the list.sort method sorts selectoption elements in ascending order using the value and label fields, and is based on this comparison sequence. 1. the value field is used for sorting first. 2. if two value fields have the same value or are both empty, the label field is used. note that the disabled field is not used for sorting. for text fields, the sort algorithm uses the unicode sort order. also, empty fields precede non-empty fields in the sort order. in this example, a list contains three selectoption elements. two elements, united states and mexico, have the same value field (‘a’). the
list.sort method sorts these two elements based on the label field, and places mexico before united states, as shown in the output. the last element in the sorted list is canada and is sorted on its value field ‘c’, which comes after ‘a’. list<selectoption> options = new list<selectoption>(); options.add(new selectoption('a','united states')); options.add(new selectoption('c','canada')); options.add(new selectoption('a','mexico')); system.debug('before sorting: ' + options); options.sort(); system.debug('after sorting: ' + options); this is the output of the debug statements. it shows the list contents before and after the sort. debug|before sorting: (system.selectoption[value="a", label="united states", disabled="false"], system.selectoption[value="c", label="canada", disabled="false"], system.selectoption[value="a", label="mexico", disabled="false"]) debug|after sorting: (system.selectoption[value="a", label="mexico", disabled="false"], 30apex developer guide data types and variables system.selectoption[value="a", label="united states", disabled="false"], system.selectoption[value="c", label="canada", disabled="false"]) sets a set is an unordered collection of elements that do not contain any duplicates. set elements can be of any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. this table represents a set of strings that uses city names: 'san francisco' 'new york' 'paris' 'tokyo' sets can contain collections that can be nested within one another. for example, you can have a set of lists of sets of integers. a set can contain up to seven levels of nested collections inside it, that is, up to eight levels overall. to declare a set, use the set keyword followed by the primitive data type name within <> characters. for example: set<string> mystringset = new set<string>(); the following example shows how to create a set with two hardcoded string values. // defines a new set with two elements set<string> set1 = new set<string>{'new york', 'paris'}; to access elements in a set, use the system methods provided by apex. for example: // define a new set set<integer> myset = new set<integer>(); // add two elements to the set myset.add(1); myset.add(3); // assert that the set contains the integer value we added system.assert(myset.contains(1)); // remove the integer value from the set myset.remove(1); the following example shows how to create a set from elements of another set. // define a new set that contains the // elements of the set created in the previous example set<integer> myset2 = new set<integer>(myset); // assert that the set size equals 1 // note: the set from the previous example contains only one value system.assert(myset2.size() == 1); for more information, including a complete list of all supported set system methods, see set class. note the following limitations on sets: • unlike java, apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, hashset or treeset). apex uses a hash structure for all sets. • a set is an unordered collection—you can’t access a set element at a specific index. you can only iterate over set elements. • the iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of the same code. 31apex developer guide data types and variables maps a map is a collection of key-value pairs where each unique key maps to a single value. keys and values can be any data type—primitive types, collections, sobjects, user-defined types, and built-in apex types. this table represents a map of countries and currencies: country (key) 'united states' 'japan' 'france' 'england' 'india' currency (value) 'dollar' 'yen' 'euro' 'pound' 'rupee' map keys and values can contain any collection, and can contain nested collections. for example, you can have a map of integers to maps, which, in turn
, map strings to lists. map keys can contain up to seven levels of nested collections, that is, up to eight levels overall. to declare a map, use the map keyword followed by the data types of the key and the value within <> characters. for example: map<string, string> country_currencies = new map<string, string>(); map<id, set<string>> m = new map<id, set<string>>(); you can use the generic or specific sobject data types with maps. you can also create a generic instance of a map. as with lists, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. within the curly braces, specify the key first, then specify the value for that key using =>. for example: map<string, string> mystrings = new map<string, string>{'a' => 'b', 'c' => 'd'.touppercase()}; in the first example, the value for the key a is b, and the value for the key c is d. to access elements in a map, use the map methods provided by apex. this example creates a map of integer keys and string values. it adds two entries, checks for the existence of the first key, retrieves the value for the second entry, and finally gets the set of all keys. map<integer, string> m = new map<integer, string>(); // define a new map m.put(1, 'first entry'); // insert a new key-value pair in the map m.put(2, 'second entry'); // insert a new key-value pair in the map system.assert(m.containskey(1)); // assert that the map contains a key string value = m.get(2); // retrieve a value, given a particular key system.assertequals('second entry', value); set<integer> s = m.keyset(); // return a set that contains all of the keys in the map for more information, including a complete list of all supported map methods, see map class. map considerations • unlike java, apex developers do not need to reference the algorithm that is used to implement a map in their declarations (for example, hashmap or treemap). apex uses a hash structure for all maps. • the iteration order of map elements is deterministic. you can rely on the order being the same in each subsequent execution of the same code. however, we recommend to always access map elements by key. • a map key can hold the null value. • adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with the new entry. 32apex developer guide data types and variables • map keys of type string are case-sensitive. two keys that differ only by the case are considered unique and have corresponding distinct map entries. subsequently, the map methods, including put, get, containskey, and remove treat these keys as distinct. • uniqueness of map keys of user-defined types is determined by the equals and hashcode methods, which you provide in your classes. uniqueness of keys of all other non-primitive types, such as sobject keys, is determined by comparing the objects’ field values. • a map object is serializable into json only if it uses one of the following data types as a key. – boolean – date – datetime – decimal – double – enum – id – integer – long – string – time parameterized typing apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before that variable can be used. this is legal in apex: integer x = 1; this is not legal, if x has not been defined earlier: x = 1; lists, maps and sets are parameterized in apex: they take any data type apex supports for them as an argument. that data type must be replaced with an actual data type upon construction of the list, map or set. for example: list<string> mylist = new list<string>(); subtyping with parameterized lists in apex, if type t is a subtype of u, then list<t> would be a subtype of list<u>. for example, the following is legal: list<string> slst = new list<string> {'alpha', 'beta'}; list<object> olst = slst; enums an enum is an abstract data type with values that each take on exactly one
of a finite set of identifiers that you specify. enums are typically used to define a set of possible values that don’t otherwise have a numerical order. typical examples include the suit of a card, or a particular season of the year. 33apex developer guide data types and variables although each value corresponds to a distinct integer value, the enum hides this implementation. hiding the implementation prevents any possible misuse of the values to perform arithmetic and so on. after you create an enum, variables, method arguments, and return types can be declared of that type. note: unlike java, the enum type itself has no constructor syntax. to define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values. for example, the following code creates an enum called season: public enum season {winter, spring, summer, fall} by creating the enum season, you have also created a new data type called season. you can use this new data type as you would any other data type. for example: season southernhemisphereseason = season.winter; public season getsouthernhemisphereseason(season northernhemisphereseason) { if (northernhemisphereseason == season.summer) return southernhemisphereseason; //... } you can also define a class as an enum. when you create an enum class, do not use the class keyword in the definition. public enum myenumclass { x, y } you can use an enum in any place you can use another data type name. if you define a variable whose type is an enum, any object you assign to it must be an instance of that enum class. any webservice method can use enum types as part of their signature. in this case, the associated wsdl file includes definitions for the enum and its values, which the api client can use. apex provides the following system-defined enums: • system.statuscode this enum corresponds to the api error code that is exposed in the wsdl document for all api operations. for example: statuscode.cannot_insert_update_activate_entity statuscode.insufficient_access_on_cross_reference_entity the full list of status codes is available in the wsdl file for your organization. for more information about accessing the wsdl file for your organization, see downloading salesforce wsdls and client authentication certificates in salesforce help. • system.xmltag: this enum returns a list of xml tags used for parsing the result xml from a webservice method. for more information, see xmlstreamreader class. • system.applicationreadwritemode: this enum indicates if an organization is in 5 minute upgrade read-only mode during salesforce upgrades and downtimes. for more information, see system.getapplicationreadwritemode(). • system.logginglevel: this enum is used with the system.debug method, to specify the log level for all debug calls. for more information, see system class. • system.roundingmode: this enum is used by methods that perform mathematical operations to specify the rounding behavior for the operation. typical examples are the decimal divide method and the double round method. for more information, see rounding mode. 34apex developer guide data types and variables • system.soaptype: this enum is returned by the field describe result getsoaptype method. for more information, see soaptype enum. • system.displaytype: this enum is returned by the field describe result gettype method. for more information, see displaytype enum. • system.jsontoken: this enum is used for parsing json content. for more information, see jsontoken enum. • apexpages.severity: this enum specifies the severity of a visualforce message. for more information, see apexpages.severity enum. • dom.xmlnodetype: this enum specifies the node type in a dom document. note: system-defined enums cannot be used in web service methods. all enum values, including system enums, have common methods associated with them. for more information, see enum methods. you cannot add user-defined methods to enum values. variables local variables are declared with java-style syntax. as with java, multiple variables can be declared and initialized in a single statement. local variables are declared with java-style syntax. for example: integer i = 0; string str; list<string> strlist; set<string> s;
map<id, string> m; as with java, multiple variables can be declared and initialized in a single statement, using comma separation. for example: integer i, j, k; null variables and initial values if you declare a variable and don't initialize it with a value, it will be null. in essence, null means the absence of a value. you can also assign null to any variable declared with a primitive type. for example, both of these statements result in a variable set to null: boolean x = null; decimal d; many instance methods on the data type will fail if the variable is null. in this example, the second statement generates an exception (nullpointerexception) date d; d.adddays(2); 35apex developer guide data types and variables all variables are initialized to null if they aren’t assigned a value. for instance, in the following example, i, and k are assigned values, while the integer variable j and the boolean variable b are set to null because they aren’t explicitly initialized. integer i = 0, j, k = 1; boolean b; note: a common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system. this isn’t the case. like all other variables, boolean variables are null if not assigned a value explicitly. variable scope variables can be defined at any point in a block, and take on scope from that point forward. sub-blocks can’t redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. for example: integer i; { // integer i; this declaration is not allowed } for (integer j = 0; j < 10; j++); for (integer j = 0; j < 10; j++); case sensitivity to avoid confusion with case-insensitive soql and sosl queries, apex is also case-insensitive. this means: • variable and method names are case-insensitive. for example: integer i; //integer i; this would be an error. • references to object and field names are case-insensitive. for example: account a1; account a2; • soql and sosl statements are case- insensitive. for example: account[] accts = [select id from account where name = 'fred']; note: you’ll learn more about sobjects, soql and sosl later in this guide. also note that apex uses the same filtering semantics as soql, which is the basis for comparisons in the soap api and the salesforce user interface. the use of these semantics can lead to some interesting behavior. for example, if an end-user generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned in the result. the rationale for this behavior is that users typically think of a field without a value as just a space character, rather than its actual null value. consequently, in apex, the following expressions all evaluate to true: string s; system.assert('a' == 'a'); system.assert(s < 'b'); system.assert(!(s > 'b')); note: although s < 'b' evaluates to true in the example above, 'b.'compareto(s) generates an error because you’re trying to compare a letter to a null value. 36apex developer guide data types and variables constants apex constants are variables whose values don’t change after being initialized once. constants can be defined using the final keyword. the final keyword means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer method if the constant is defined in a class. this example declares two constants. the first is initialized in the declaration statement. the second is assigned a value in a static block by calling a static method. public class mycls { static final integer private_int_const = 200; static final integer private_int_const2; public static integer calculate() { return 2 + 7; } static { private_int_const2 = calculate(); } } for more information, see using the final keyword on page 82. expressions and operators an expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. in this section: expressions an expression is a construct made up
of variables, operators, and method invocations that evaluates to a single value. expression operators expressions can be joined to one another with operators to create compound expressions. safe navigation operator use the safe navigation operator (?.) to replace explicit, sequential checks for null references. this operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a nullpointerexception. operator precedence operators are interpreted in order, according to rules. comments both single and multiline comments are supported in apex code. see also: expanding sobject and list expressions expressions an expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. in apex, an expression is always one of the following types: 37apex developer guide data types and variables • a literal expression. for example: 1 + 1 • a new sobject, apex object, list, set, or map. for example: new account(<field_initializers>) new integer[<n>] new account[]{<elements>} new list<account>() new set<string>{} new map<string, integer>() new myrenamingclass(string oldname, string newname) • any value that can act as the left-hand of an assignment operator (l-values), including variables, one-dimensional list positions, and most sobject or apex object field references. for example: integer i mylist[3] mycontact.name myrenamingclass.oldname • any sobject field reference that is not an l-value, including: – the id of an sobject in a list (see lists) – a set of child records associated with an sobject (for example, the set of contacts associated with a particular account). this type of expression yields a query result, much like soql and sosl queries. • a soql or sosl query surrounded by square brackets, allowing for on-the-fly evaluation in apex. for example: account[] aa = [select id, name from account where name ='acme']; integer i = [select count() from contact where lastname ='weissman']; list<list<sobject>> searchlist = [find 'map*' in all fields returning account (id, name), contact, opportunity, lead]; for information, see soql and sosl queries on page 157. • a static or instance method invocation. for example: system.assert(true) myrenamingclass.replacenames() changepoint(new point(x, y)); expression operators expressions can be joined to one another with operators to create compound expressions. apex supports the following operators: operator syntax description = x = y assignment operator (right associative). assigns the value of y to the l-value x. the data type of x must match the data type of y and can’t be null. 38apex developer guide data types and variables operator syntax description += x += y addition assignment operator (right associative). adds the value of y to the original value of x and then reassigns the new value to x. see + for additional information. x and y can’t be null. *= x *= y multiplication assignment operator (right associative). multiplies the value of y with the original value of x and then reassigns the new value to x. note: x and y must be integers or doubles or a combination. x and y can’t be null. -= x -= y subtraction assignment operator (right associative). subtracts the value of y from the original value of x and then reassigns the new value to x. note: x and y must be integers or doubles or a combination. x and y can’t be null. /= x /= y division assignment operator (right associative). divides the original value of x with the value of y and then reassigns the new value to x. note: x and y must be integers or doubles or a combination. x and y can’t be null. |= x |= y or assignment operator (right associative). if x, a boolean, and y, a boolean, are both false, then x remains false. otherwise x is assigned the value of true. x and y can’t be null. &= x &= y and assignment operator (right associative).
if x, a boolean, and y, a boolean, are both true, then x remains true. otherwise x is assigned the value of false. x and y can’t be null. <<= x <<= y bitwise shift left assignment operator. shifts each bit in x to the left by y bits so that the high-order bits are lost and the new right bits are set to 0. this value is then reassigned to x. >>= x >>= y bitwise shift right signed assignment operator. shifts each bit in x to the right by y bits so that the low-order bits are lost and the new left bits are set to 0 for positive values of y and 1 for negative values of y. this value is then reassigned to x. >>>= x >>>= y bitwise shift right unsigned assignment operator. shifts each bit in x to the right by y bits so that the low-order bits are lost and the new left bits are set to 0 for all values of y. this value is then reassigned to x. ? : x ? y : z ternary operator (right associative). this operator acts as a short-hand for if-then-else statements. if x, a boolean, is true, y is the result. otherwise z is the result. note: x can’t be null. 39apex developer guide data types and variables operator syntax description && x && y and logical operator (left associative). if x, a boolean, and y, a boolean, are both true, then the expression evaluates to true. otherwise the expression evaluates to false. note: • && has precedence over || • this operator exhibits short-circuiting behavior, which means y is evaluated only if x is true. • x and y can’t be null. || x || y or logical operator (left associative). if x, a boolean, and y, a boolean, are both false, then the expression evaluates to false. otherwise the expression evaluates to true. note: • && has precedence over || • this operator exhibits short-circuiting behavior, which means y is evaluated only if x is false. • x and y can’t be null. == x == y equality operator. if the value of x equals the value of y, the expression evaluates to true. otherwise the expression evaluates to false. note: • unlike java, == in apex compares object value equality not reference equality, except for user-defined types. therefore: – string comparison using == is case-insensitive and is performed according to the locale of the context user – id comparison using == is case-sensitive and doesn’t distinguish between 15-character and 18-character formats – user-defined types are compared by reference, which means that two objects are equal only if they reference the same location in memory. you can override this default comparison behavior by providing equals and hashcode methods in your class to compare object values instead. • for sobjects and sobject arrays, == performs a deep check of all sobject field values before returning its result. likewise for collections and built-in apex objects. • for records, every field must have the same value for == to evaluate to true. • x or y can be the literal null. • the comparison of any two values can never result in null. • soql and sosl use = for their equality operator and not ==. although apex and soql and sosl are strongly linked, this unfortunate syntax discrepancy exists because most modern languages use = for assignment 40apex developer guide data types and variables operator syntax description and == for equality. the designers of apex deemed it more valuable to maintain this paradigm than to force developers to learn a new assignment operator. as a result, apex developers must use == for equality tests in the main body of the apex code, and = for equality in soql and sosl queries. === x === y exact equality operator. if x and y reference the exact same location in memory the expression evaluates to true. otherwise the expression evaluates to false. < x < y less than operator. if x is less than y, the expression evaluates to true. otherwise the expression evaluates to false. note: • unlike other database stored procedures, apex doesn’t support tri-state boolean logic and the comparison of any two values can never result in null. • if x or y equal null and are integers, doubles, dates, or datetimes, the expression is false. • a non-null string or id value is always greater
than a null value. • if x and y are ids, they must reference the same type of object. otherwise a runtime error results. • if x or y is an id and the other value is a string, the string value is validated and treated as an id. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. > x > y greater than operator. if x is greater than y, the expression evaluates to true. otherwise the expression evaluates to false. note: • the comparison of any two values can never result in null. • if x or y equal null and are integers, doubles, dates, or datetimes, the expression is false. • a non-null string or id value is always greater than a null value. • if x and y are ids, they must reference the same type of object. otherwise a runtime error results. • if x or y is an id and the other value is a string, the string value is validated and treated as an id. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. 41apex developer guide data types and variables operator syntax description <= x <= y less than or equal to operator. if x is less than or equal to y, the expression evaluates to true. otherwise the expression evaluates to false. note: • the comparison of any two values can never result in null. • if x or y equal null and are integers, doubles, dates, or datetimes, the expression is false. • a non-null string or id value is always greater than a null value. • if x and y are ids, they must reference the same type of object. otherwise a runtime error results. • if x or y is an id and the other value is a string, the string value is validated and treated as an id. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. >= x >= y greater than or equal to operator. if x is greater than or equal to y, the expression evaluates to true. otherwise the expression evaluates to false. note: • the comparison of any two values can never result in null. • if x or y equal null and are integers, doubles, dates, or datetimes, the expression is false. • a non-null string or id value is always greater than a null value. • if x and y are ids, they must reference the same type of object. otherwise a runtime error results. • if x or y is an id and the other value is a string, the string value is validated and treated as an id. • x and y can’t be booleans. • the comparison of two strings is performed according to the locale of the context user and is case-insensitive. != x != y inequality operator. if the value of x doesn’t equal the value of y, the expression evaluates to true. otherwise the expression evaluates to false. note: • string comparison using != is case-insensitive • unlike java, != in apex compares object value equality not reference equality, except for user-defined types. • for sobjects and sobject arrays, != performs a deep check of all sobject field values before returning its result. • for records, != evaluates to true if the records have different values for any field. 42apex developer guide data types and variables operator syntax description • user-defined types are compared by reference, which means that two objects are different only if they reference different locations in memory. you can override this default comparison behavior by providing equals and hashcode methods in your class to compare object values instead. • x or ycan be the literal null. • the comparison of any two values can never result in null. !== x !== y exact inequality operator. if x and y don’t reference the exact same location in memory, the expression evaluates to true. otherwise the expression evaluates to false. + x + y addition operator. adds the value of x to the value of y according to the following rules: • if x and y are integers or doubles, the operator adds the value of x to the value of y. if a double is used, the result is a double. • if x is a
date and y is an integer, returns a new date that is incremented by the specified number of days. • if x is a datetime and y is an integer or double, returns a new date that is incremented by the specified number of days, with the fractional portion corresponding to a portion of a day. • if x is a string and y is a string or any other type of non-null argument, concatenates y to the end of x. - x - y subtraction operator. subtracts the value of y from the value of x according to the following rules: • if x and y are integers or doubles, the operator subtracts the value of y from the value of x. if a double is used, the result is a double. • if x is a date and y is an integer, returns a new date that is decremented by the specified number of days. • if x is a datetime and y is an integer or double, returns a new date that is decremented by the specified number of days, with the fractional portion corresponding to a portion of a day. * x * y multiplication operator. multiplies x, an integer or double, with y, another integer or double. if a double is used, the result is a double. / x / y division operator. divides x, an integer or double, by y, another integer or double. if a double is used, the result is a double. ! !x logical complement operator. inverts the value of a boolean so that true becomes false and false becomes true. - -x unary negation operator. multiplies the value of x, an integer or double, by -1. the positive equivalent + is also syntactically valid but doesn’t have a mathematical effect. 43apex developer guide data types and variables operator syntax description ++ x++ increment operator. adds 1 to the value of x, a variable of a numeric type. if prefixed (++x), the expression evaluates to the value of x after the increment. if ++x postfixed (x++), the expression evaluates to the value of x before the increment. -- x-- decrement operator. subtracts 1 from the value of x, a variable of a numeric type. if prefixed (--x), the expression evaluates to the value of x after the decrement. if --x postfixed (x--), the expression evaluates to the value of x before the decrement. & x & y bitwise and operator. ands each bit in x with the corresponding bit in y so that the result bit is set to 1 if both of the bits are set to 1. | x | y bitwise or operator. ors each bit in x with the corresponding bit in y so that the result bit is set to 1 if at least one of the bits is set to 1. ^ x ^ y bitwise exclusive or operator. exclusive ors each bit in x with the corresponding bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the other bit is set to 0. ^= x ^= y bitwise exclusive or operator. exclusive ors each bit in x with the corresponding bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the other bit is set to 0. assigns the result of the exclusive or operation to x. << x << y bitwise shift left operator. shifts each bit in x to the left by y bits so that the high-order bits are lost and the new right bits are set to 0. >> x >> y bitwise shift right signed operator. shifts each bit in x to the right by y bits so that the low-order bits are lost and the new left bits are set to 0 for positive values of y and 1 for negative values of y. >>> x >>> y bitwise shift right unsigned operator. shifts each bit in x to the right by y bits so that the low-order bits are lost and the new left bits are set to 0 for all values of y. ~ ~x bitwise not or complement operator. toggles each binary digit of x, converting 0 to 1 and 1 to 0. boolean values are converted from true to false and vice versa. () (x) parentheses. elevates the precedence of an expression x so that it’s evaluated first in a compound expression. ?. x?.y safe navigation operator. short-circuits expressions that attempt to operate on a null value, and returns null
instead of throwing a nullpointerexception. if the left-hand side of the chain expression evaluates to null, the right-hand side of the chain expression isn’t evaluated. safe navigation operator use the safe navigation operator (?.) to replace explicit, sequential checks for null references. this operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a nullpointerexception. important: where possible, we changed noninclusive terms to align with our company value of equality. we maintained certain terms to avoid any effect on customer implementations. 44apex developer guide data types and variables if the left-hand-side of the chain expression evaluates to null, the right-hand-side isn’t evaluated. use the safe navigation operator (?.) in method, variable, and property chaining. the part of the expression that isn’t evaluated can include variable references, method references, or array expressions. note: all apex types are implicitly nullable and can hold a null value returned from the operator. examples • this example first evaluates a, and returns null if a is null. otherwise the return value is a.b. a?.b // evaluates to: a == null ? null : a.b • this example returns null if a[x] evaluates to null. if a[x] doesn’t evaluate to null and amethod() returns null, then this expression throws a nullpointerexception. a[x]?.amethod().afield // evaluates to null if a[x] == null • this example returns null if a[x].amethod() evaluates to null. a[x].amethod()?.afield • this example indicates that the type of the expression is the same whether the safe navigation operator is used in the expression or not. integer x = anobject?.anintegerfield; // the expression is of type integer because the field is of type integer • this example shows a single statement replacing a block of code that checks for nulls. // previous code checking for nulls string profileurl = null; if (user.getprofileurl() != null) { profileurl = user.getprofileurl().toexternalform(); } // new code using the safe navigation operator string profileurl = user.getprofileurl()?.toexternalform(); • this example shows a single-row soql query using the safe navigation operator. // previous code checking for nulls results = [select name from account where id = :accid]; if (results.size() == 0) { // account was deleted return null; } return results[0].name; // new code using the safe navigation operator return [select name from account where id = :accid]?.name; table 1: safe navigation operator use-cases allowed use-case example more information method or variable or parameter chains aobject?.amethod(); can be used as a top-level statement. 45apex developer guide data types and variables allowed use-case example more information using parentheses, for example in a cast. ((t)a1?.b1)?.c1() the operator skips the method chain up to the first closing parenthesis. by adding the operator after the parenthesis, the code safeguards the whole expression. if the operator is used elsewhere, and not after the parenthesis, the whole cast expression isn’t be safeguarded. for example, the behavior of //incorrect use of safe navigation operator ((t)a1?.b1).c1() is equivalent to: t ref = null; if (a1 != null) { ref = (t)a1.b1; } result = ref.c1(); sobject chaining string s = an sobject expression evaluates to null contact.account?.billingcity; when the relationship is null. the behavior is equivalent to string s = contact.account.billingcity. soql queries string s = [select lastname if the soql query returns no objects, then from contact]?.lastname; the expression evaluates to null. the behavior is equivalent to: list<contact> contacts = [select lastname from contact]; string s; if (contacts.size() == 0) { s = null; // new behavior when using safe navigation. earlier, this would throw an exception. } else if (contacts.size() == 1) { s = contacts.get(0).last
name; } else { // contacts.size() > 1 throw new queryexception(...); } 46
apex developer guide data types and variables you can’t use the safe navigation operator in certain cases. attempting to use the operator in these ways causes an error during compilation: • types and static expressions with dots. for example: – namespaces – {namespace}.{class} – trigger.new – flow.interview.{flowname} – {type}.class • static variable access, method calls, and expressions. for example: – aclass.astaticmethodcall() – aclass.astaticvariable – string.format('{0}', 'hello world') – page.{pagename} • assignable expressions. for example: – foo?.bar = 42; – ++foo?.bar; • soql bind expressions. for example: class x { public string query = 'xyz';} x x = new x(); list<account> accounts = [select name from account where name = :x?.query] list<list<sobject>> moreaccounts = [find :x?.query in all fields returning account(name)]; • with adderror() on sobject scalar fields. for example: contact c; c.lastname?.adderror('the field must have a value'); note: you can use the operator with adderror() on sobjects, including lookup and master-detail fields. operator precedence operators are interpreted in order, according to rules. apex uses the following operator precedence rules: precedence operators description 1 {} () ++ -- grouping and prefix increments and decrements 2 ~ ! -x +x (type) new unary operators, additive operators, type cast and object creation 3 * / multiplication and division 4 + - addition and subtraction 47apex developer guide data types and variables precedence operators description 5 << >> >>> shift operators 6 < <= > >= instanceof greater-than and less-than comparisons, reference tests 7 == != comparisons: equal and not-equal 8 & bitwise and 9 ^ bitwise xor 10 | bitwise or 11 && logical and 12 || logical or 13 = += -= *= /= &= <<= >>= >>>= assignment operators comments both single and multiline comments are supported in apex code. • to create a single line comment, use //. all characters on the same line to the right of the // are ignored by the parser. for example: integer i = 1; // this comment is ignored by the parser • to create a multiline comment, use /* and */ to demarcate the beginning and end of the comment block. for example: integer i = 1; /* this comment can wrap over multiple lines without getting interpreted by the parser. */ assignment statements an assignment statement is any statement that places a value into a variable. an assignment statement generally takes one of two forms: [lvalue] = [new_value_expression]; [lvalue] = [[inline_soql_query]]; in the forms above, [lvalue] stands for any expression that can be placed on the left side of an assignment operator. these include: • a simple variable. for example: integer i = 1; account a = new account(); account[] accts = [select id from account]; • a de-referenced list element. for example: ints[0] = 1; accts[0].name = 'acme'; 48apex developer guide data types and variables • an sobject field reference that the context user has permission to edit. for example: account a = new account(name = 'acme', billingcity = 'san francisco'); // ids cannot be set prior to an insert call // a.id = '00300000003t2pgaa0'; // instead, insert the record. the system automatically assigns it an id. insert a; // fields also must be writable for the context user // a.createddate = system.today(); this code is invalid because // createddate is read-only! // since the account a has been inserted, it is now possible to // create a new contact that is related to it contact c = new contact(lastname = 'roth', account = a); // notice that you can write to the account name directly through the contact c.account.name = 'salesforce.com'; assignment is always done by reference. for example: account a = new account(); account b;
account[] c = new account[]{}; a.name = 'acme'; b = a; c.add(a); // these asserts should now be true. you can reference the data // originally allocated to account a through account b and account list c. system.assertequals(b.name, 'acme'); system.assertequals(c[0].name, 'acme'); similarly, two lists can point at the same value in memory. for example: account[] a = new account[]{new account()}; account[] b = a; a[0].name = 'acme'; system.assert(b[0].name == 'acme'); in addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. see expression operators on page 38. rules of conversion in general, apex requires you to explicitly convert one data type to another. for example, a variable of the integer data type cannot be implicitly converted to a string. you must use the string.format method. however, a few data types can be implicitly converted, without using a method. numbers form a hierarchy of types. variables of lower numeric types can always be assigned to higher types without explicit conversion. the following is the hierarchy for numbers, from lowest to highest: 1. integer 2. long 49apex developer guide data types and variables 3. double 4. decimal note: once a value has been passed from a number of a lower type to a number of a higher type, the value is converted to the higher type of number. note that the hierarchy and implicit conversion is unlike the java hierarchy of numbers, where the base interface number is used and implicit object conversion is never allowed. in addition to numbers, other data types can be implicitly converted. the following rules apply: • ids can always be assigned to strings. • strings can be assigned to ids. however, at runtime, the value is checked to ensure that it is a legitimate id. if it is not, a runtime exception is thrown. • the instanceof keyword can always be used to test whether a string is an id. additional considerations for data types data types of numeric values numeric values represent integer values unless they are appended with l for a long or with .0 for a double or decimal. for example, the expression long d = 123; declares a long variable named d and assigns it to an integer numeric value (123), which is implicitly converted to a long. the integer value on the right hand side is within the range for integers and the assignment succeeds. however, if the numeric value on the right hand side exceeds the maximum value for an integer, you get a compilation error. in this case, the solution is to append l to the numeric value so that it represents a long value which has a wider range, as shown in this example: long d = 2147483648l;. overflow of data type values arithmetic computations that produce values larger than the maximum value of the current type are said to overflow. for example, integer i = 2147483647 + 1; yields a value of –2147483648 because 2147483647 is the maximum value for an integer, so adding one to it wraps the value around to the minimum negative value for integers, –2147483648. if arithmetic computations generate results larger than the maximum value for the current type, the end result will be incorrect because the computed values that are larger than the maximum will overflow. for example, the expression long millsperyear = 365 * 24 * 60 * 60 * 1000; results in an incorrect result because the products of integers on the right hand side are larger than the maximum integer value and they overflow. as a result, the final product isn't the expected one. you can avoid this by ensuring that the type of numeric values or variables you are using in arithmetic operations are large enough to hold the results. in this example, append l to numeric values to make them long so the intermediate products will be long as well and no overflow occurs. the following example shows how to correctly compute the amount of milliseconds in a year by multiplying long numeric values. long millsperyear = 365l * 24l * 60l * 60l * 1000l; long expectedvalue = 31536000000l; system.assertequals(millsperyear, expectedvalue); loss of fractions in divisions when dividing numeric integer or long values, the fractional portion of the result, if any, is removed before performing any implicit conversions to a double or
decimal. for example, double d = 5/3; returns 1.0 because the actual result (1.666...) is an integer and is rounded to 1 before being implicitly converted to a double. to preserve the fractional value, ensure that you are using double or decimal numeric values in the division. for example, double d = 5.0/3.0; returns 1.6666666666666667 because 5.0 and 3.0 represent double values, which results in the quotient being a double as well and no fractional value is lost. 50apex developer guide control flow statements control flow statements apex provides if-else statements, switch statements, and loops to control the flow of code execution. statements are generally executed line by line, in the order they appear. with control flow statements, you can make apex code execute based on a certain condition, or have a block of code execute repeatedly. in this section: conditional (if-else) statements the conditional statement in apex works similarly to java. switch statements apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly. loops apex supports five types of procedural loops. conditional (if-else) statements the conditional statement in apex works similarly to java. if ([boolean_condition]) // statement 1 else // statement 2 the else portion is always optional, and always groups with the closest if. for example: integer x, sign; // your code if (x <= 0) if (x == 0) sign = 0; else sign = -1; is equivalent to: integer x, sign; // your code if (x <= 0) { if (x == 0) { sign = 0; } else { sign = -1; } } repeated else if statements are also allowed. for example: if (place == 1) { medal_color = 'gold'; } else if (place == 2) { medal_color = 'silver'; } else if (place == 3) { medal_color = 'bronze'; } else { medal_color = null; } 51apex developer guide control flow statements switch statements apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly. the syntax is: switch on expression { when value1 { // when block 1 // code block 1 } when value2 { // when block 2 // code block 2 } when value3 { // when block 3 // code block 3 } when else { // default block, optional // code block 4 } } the when value can be a single value, multiple values, or sobject types. for example: when value1 { } when value2, value3 { } when typename variablename { } the switch statement evaluates the expression and executes the code block for the matching when value. if no value matches, the when else code block is executed. if there isn’t a when else block, no action is taken. note: there is no fall-through. after the code block is executed, the switch statement exits. apex switch statement expressions can be one of the following types. • integer • long • sobject • string • enum when blocks each when block has a value that the expression is matched against. these values can take one of the following forms. • when literal {} (a when block can have multiple, comma-separated literal clauses) • when sobjecttype identifier {} • when enum_value {} the value null is a legal value for all types. 52apex developer guide control flow statements each when value must be unique. for example, you can use the literal x only in one when block clause. a when block is matched one time at most. when else block if no when values match the expression, the when else block is executed. note: salesforce recommends including a when else block, especially with enum types, although it isn’t required. when you build a switch statement using enum values provided by a managed package, your code might not behave as expected if a new version of the package contains additional enum values. you can prevent this problem by including a when else block to handle unanticipated values. if you include a when else block, it must be the last block in the switch statement. examples with literals you can use literal when values for switching on integer, long, and string types. string clauses are case-sensitive. for example, “orange” is a different value than “or
ange.” single value example the following example uses integer literals for when values. switch on i { when 2 { system.debug('when block 2'); } when -3 { system.debug('when block -3'); } when else { system.debug('default'); } } null value example because all types in apex are nullable, a when value can be null. switch on i { when 2 { system.debug('when block 2'); } when null { system.debug('bad integer'); } when else { system.debug('default ' + i); } } multiple values examples 53apex developer guide control flow statements the apex switch statement doesn’t fall-through, but a when clause can include multiple literal values to match against. you can also nest apex switch statements to provide multiple execution paths within a when clause. switch on i { when 2, 3, 4 { system.debug('when block 2 and 3 and 4'); } when 5, 6 { system.debug('when block 5 and 6'); } when 7 { system.debug('when block 7'); } when else { system.debug('default'); } } method example instead of switching on a variable expression, the following example switches on the result of a method call. switch on someinteger(i) { when 2 { system.debug('when block 2'); } when 3 { system.debug('when block 3'); } when else { system.debug('default'); } } example with sobjects switching on an sobject value allows you to implicitly perform instanceof checks and casting. for example, consider the following code that uses if-else statements. if (sobject instanceof account) { account a = (account) sobject; system.debug('account ' + a); } else if (sobject instanceof contact) { contact c = (contact) sobject; system.debug('contact ' + c); } else { system.debug('default'); } you can replace and simplify this code with the following switch statement. switch on sobject { when account a { system.debug('account ' + a); } when contact c { 54apex developer guide control flow statements system.debug('contact ' + c); } when null { system.debug('null'); } when else { system.debug('default'); } } note: you can use only one sobject type per when block. example with enums a switch statement that uses enum when values doesn’t require a when else block, but it is recommended. you can use multiple enum values per when block clause. switch on season { when winter { system.debug('boots'); } when spring, summer { system.debug('sandals'); } when else { system.debug('none of the above'); } } loops apex supports five types of procedural loops. these types of procedural loops are supported: • do {statement} while (boolean_condition); • while (boolean_condition) statement; • for (initialization; boolean_exit_condition; increment) statement; • for (variable : array_or_set) statement; • for (variable : [inline_soql_query]) statement; all loops allow for loop control structures: • break; exits the entire loop • continue; skips to the next iteration of the loop in this section: 1. do-while loops 2. while loops 3. for loops 55apex developer guide control flow statements do-while loops the apex do-while loop repeatedly executes a block of code as long as a particular boolean condition remains true. its syntax is: do { code_block } while (condition); note: curly braces ({}) are always required around a code_block. as in java, the apex do-while loop does not check the boolean condition statement until after the first loop is executed. consequently, the code block always runs at least once. as an example, the following code outputs the numbers 1 - 10 into the debug log: integer count = 1; do { system.debug(count); count++; } while (count < 11); while loops the apex while loop repeatedly executes a block of code as long as a particular boolean condition remains true. its syntax is: while (condition) { code_block
} note: curly braces ({}) are required around a code_block only if the block contains more than one statement. unlike do-while, the while loop checks the boolean condition statement before the first loop is executed. consequently, it is possible for the code block to never execute. as an example, the following code outputs the numbers 1 - 10 into the debug log: integer count = 1; while (count < 11) { system.debug(count); count++; } for loops apex supports three variations of the for loop: • the traditional for loop: for (init_stmt; exit_condition; increment_stmt) { code_block } 56apex developer guide control flow statements • the list or set iteration for loop: for (variable : list_or_set) { code_block } where variable must be of the same primitive or sobject type as list_or_set. • the soql for loop: for (variable : [soql_query]) { code_block } or for (variable_list : [soql_query]) { code_block } both variable and variable_list must be of the same sobject type as is returned by the soql_query. note: curly braces ({}) are required around a code_block only if the block contains more than one statement. each is discussed further in the sections that follow. in this section: traditional for loops list or set iteration for loops iterating collections traditional for loops the traditional for loop in apex corresponds to the traditional syntax used in java and other languages. its syntax is: for (init_stmt; exit_condition; increment_stmt) { code_block } when executing this type of for loop, the apex runtime engine performs the following steps, in order: 1. execute the init_stmt component of the loop. note that multiple variables can be declared and/or initialized in this statement. 2. perform the exit_condition check. if true, the loop continues. if false, the loop exits. 3. execute the code_block. 4. execute the increment_stmt statement. 5. return to step 2. as an example, the following code outputs the numbers 1 - 10 into the debug log. note that an additional initialization variable, j, is included to demonstrate the syntax: for (integer i = 0, j = 0; i < 10; i++) { system.debug(i+1); } 57apex developer guide classes, objects, and interfaces list or set iteration for loops the list or set iteration for loop iterates over all the elements in a list or set. its syntax is: for (variable : list_or_set) { code_block } where variable must be of the same primitive or sobject type as list_or_set. when executing this type of for loop, the apex runtime engine assigns variable to each element in list_or_set, and runs the code_block for each value. for example, the following code outputs the numbers 1 - 10 to the debug log: integer[] myints = new integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (integer i : myints) { system.debug(i); } iterating collections collections can consist of lists, sets, or maps. modifying a collection's elements while iterating through that collection is not supported and causes an error. do not directly add or remove elements while iterating through the collection that includes them. adding elements during iteration to add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the original after you finish iterating the collection. removing elements during iteration to remove elements while iterating a list, create a new list, then copy the elements you wish to keep. alternatively, add the elements you wish to remove to a temporary list and remove them after you finish iterating the collection. note: the list.remove method performs linearly. using it to remove elements has time and resource implications. to remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them after you finish iterating the collection. classes, objects, and interfaces apex classes are modeled on their counterparts in java. you’ll define, instantiate, and extend
classes, and you’ll work with interfaces, apex class versions, properties, and other related class concepts. in this section: 1. classes as in java, you can create classes in apex. a class is a template or blueprint from which objects are created. an object is an instance of a class. 58apex developer guide classes, objects, and interfaces 2. interfaces an interface is like a class in which none of the methods have been implemented—the method signatures are there, 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. 3. keywords apex provides the keywords final, instanceof, super, this, transient, with sharing and without sharing. 4. annotations an apex annotation modifies the way that a method or class is used, similar to annotations in java. annotations are defined with an initial @ symbol, followed by the appropriate keyword. 5. classes and casting in general, all type information is available at run time. this means that apex enables casting, that is, a data type of one class can be assigned to a data type of another class, but only if one class is a subclass of the other class. use casting when you want to convert an object from one data type to another. 6. differences between apex classes and java classes apex classes and java classes work in similar ways, but there are some significant differences. 7. class definition creation use the class editor to create a class in salesforce. 8. namespace prefix the salesforce application supports the use of namespace prefixes. namespace prefixes are used in managed appexchange packages to differentiate custom object and field names from names used by other organizations. 9. apex code versions to aid backwards-compatibility, classes and triggers are stored with the version settings for a specific salesforce api version. 10. lists of custom types and sorting lists can hold objects of your user-defined types (your apex classes). lists of user-defined types can be sorted. 11. using custom types in map keys and sets you can add instances of your own apex classes to maps and sets. classes as in java, you can create classes in apex. a class is a template or blueprint from which objects are created. an object is an instance of a class. for example, the purchaseorder class describes an entire purchase order, and everything that you can do with a purchase order. an instance of the purchaseorder class is a specific purchase order that you send or receive. all objects have state and behavior, that is, things that an object knows about itself, and things that an object can do. the state of a purchaseorder object—what it knows—includes the user who sent it, the date and time it was created, and whether it was flagged as important. the behavior of a purchaseorder object—what it can do—includes checking inventory, shipping a product, or notifying a customer. a class can contain variables and methods. variables are used to specify the state of an object, such as the object's name or type. since these variables are associated with a class and are members of it, they are commonly referred to as member variables. methods are used to control behavior, such as getotherquotes or copylineitems. a class can contain other classes, exception types, and initialization code. 59apex developer guide classes, objects, and interfaces an interface is like a class in which none of the methods have been implemented—the method signatures are there, 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. for more general information on classes, objects, and interfaces, see http://java.sun.com/docs/books/tutorial/java/concepts/index.html in addition to classes, apex provides triggers, similar to database triggers. a trigger is apex code that executes before or after database operations. see triggers. in this section: 1. apex class definition 2. class variables 3. class methods 4. using constructors 5. access modifiers 6. static and instance methods, variables, and initialization code in apex, you can have static methods, variables, and initialization code. however, apex classes can't be static. you can also have instance methods, member variables, and initialization code, which have no modifier, and local variables. 7. apex properties 8. extending a class you can extend a class to provide more specialized behavior. 9. extended class example apex class definition
in apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another class. you can only have inner classes one level deep. for example: public class myouterclass { // additional myouterclass code here class myinnerclass { // myinnerclass code here } } to define a class, specify the following: 1. access modifiers: • you must use one of the access modifiers (such as public or global) in the declaration of a top-level class. • you don’t have to use an access modifier in the declaration of an inner class. 2. optional definition modifiers (such as virtual, abstract, and so on) 3. required: the keyword class followed by the name of the class 4. optional extensions or implementations or both note: avoid using standard object names for class names. doing so causes unexpected results. for a list of standard objects, see object reference for salesforce. 60apex developer guide classes, objects, and interfaces use the following syntax for defining classes: private | public | global [virtual | abstract | with sharing | without sharing] class classname [implements interfacenamelist] [extends classname] { // the body of the class } • the private access modifier declares that this class is only known locally, that is, only by this section of code. this is the default access for inner classes—that is, if you don't specify an access modifier for an inner class, it’s considered private. this keyword can only be used with inner classes (or with top-level test classes marked with the @istest annotation). • the public access modifier declares that this class is visible in your application or namespace. • the global access modifier declares that this class is known by all apex code everywhere. all classes containing methods defined with the webservice keyword must be declared as global. if a method or inner class is declared as global, the outer, top-level class must also be defined as global. • the with sharing and without sharing keywords specify the sharing mode for this class. for more information, see using the with sharing, without sharing, and inherited sharing keywords on page 86. • the virtual definition modifier declares that this class allows extension and overrides. you can’t override a method with the override keyword unless the class has been defined as virtual. • the abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined. note: • you can’t add an abstract method to a global class after the class has been uploaded in a managed - released package version. • if the class in the managed - released package is virtual, the method that you can add to it must also be virtual and must have an implementation. • you can’t override a public or protected virtual method of a global class of an installed managed package. for more information about managed packages, see what is a package? on page 675. a class can implement multiple interfaces, but only extend one existing class. this restriction means that apex doesn’t support multiple inheritance. the interface names in the list are separated by commas. for more information about interfaces, see interfaces on page 78. for more information about method and variable access modifiers, see access modifiers on page 66. see also: documentation typographical conventions salesforce help: manage apex classes salesforce help: developer console functionality class variables to declare a variable, specify the following: • optional: modifiers, such as public or final, as well as static. • required: the data type of the variable, such as string or boolean. • required: the name of the variable. • optional: the value of the variable. 61apex developer guide classes, objects, and interfaces use the following syntax when defining a variable: [public | private | protected | global] [final] [static] data_type variable_name [= value] for example: private static final integer my_int; private final integer i = 1; versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. class methods to define a method, specify the following: • optional: modifiers, such as
public or protected. • required: the data type of the value returned by the method, such as string or integer. use void if the method doesn’t return a value. • required: a list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses (). if there are no parameters, use a set of empty parentheses. a method can only have 32 input parameters. • required: the body of the method, enclosed in braces {}. all the code for the method, including any local variable declarations, is contained here. use the following syntax when defining a method: [public | private | protected | global] [override] [static] data_type method_name (input parameters) { // the body of the method } note: you can use override to override methods only in classes that have been defined as virtual or abstract. for example: public static integer getint() { return my_int; } as in java, methods that return values can also be run as a statement if their results aren’t assigned to another variable. user-defined methods: • can be used anywhere that system methods are used. • can be recursive. • can have side effects, such as dml insert statements that initialize sobject record ids. see apex dml statements. • can refer to themselves or to methods defined later in the same class or anonymous block. apex parses methods in two phases, so forward declarations aren’t needed. 62apex developer guide classes, objects, and interfaces • can be polymorphic. for example, a method named example can be implemented in two ways, one with a single integer parameter and one with two integer parameters. depending on whether the method is called with one or two integers, the apex parser selects the appropriate implementation to execute. if the parser can’t find an exact match, it then seeks an approximate match using type coercion rules. for more information on data conversion, see rules of conversion on page 49. note: if the parser finds multiple approximate matches, a parse-time exception is generated. • methods with a void return type are typically invoked as a standalone statement in apex code. for example: system.debug('here is a note for the log.'); • can have statements where the return values are run as a statement if their results aren’t assigned to another variable. this rule is the same in java. passing method arguments by value in apex, all primitive data type arguments, such as integer or string, are passed into methods by value. this fact means that any changes to the arguments exist only within the scope of the method. when the method returns, the changes to the arguments are lost. non-primitive data type arguments, such as sobjects, are passed into methods by reference. therefore, when the method returns, the passed-in argument still references the same object as before the method call. within the method, the reference can't be changed to point to another object but the values of the object's fields can be changed. the following are examples of passing primitive and non-primitive data type arguments into methods. example: passing primitive data type arguments this example shows how a primitive argument of type string is passed by value into another method. the debugstatusmessage method in this example creates a string variable, msg, and assigns it a value. it then passes this variable as an argument to another method, which modifies the value of this string. however, since string is a primitive type, it’s passed by value, and when the method returns, the value of the original variable, msg, is unchanged. an assert statement verifies that the value of msg is still the old value. public class passprimitivetypeexample { public static void debugstatusmessage() { string msg = 'original value'; processstring(msg); // the value of the msg variable didn't // change; it is still the old value. system.assertequals(msg, 'original value'); } public static void processstring(string s) { s = 'modified value'; } } example: passing non-primitive data type arguments this example shows how a list argument is passed by reference into the reference() method and is modified. it then shows, in the referencenew() method, that the list argument can't be changed to point to another list object. first, the createtemperaturehistory method creates a variable, fillme, that is a list of integers and passes it to a method. the called method fills this list with integer values representing rounded temperature values. when the method returns, an assert statement ver
ifies that the contents of the original list variable has changed and now contains five values. next, the example creates a second list variable, createme, and passes it to another method. the called method assigns the passed-in argument to a newly 63apex developer guide classes, objects, and interfaces created list that contains new integer values. when the method returns, the original createme variable doesn't point to the new list but still points to the original list, which is empty. an assert statement verifies that createme contains no values. public class passnonprimitivetypeexample { public static void createtemperaturehistory() { list<integer> fillme = new list<integer>(); reference(fillme); // the list is modified and contains five items // as expected. system.assertequals(fillme.size(),5); list<integer> createme = new list<integer>(); referencenew(createme); // the list is not modified because it still points // to the original list, not the new list // that the method created. system.assertequals(createme.size(),0); } public static void reference(list<integer> m) { // add rounded temperatures for the last five days. m.add(70); m.add(68); m.add(75); m.add(80); m.add(82); } public static void referencenew(list<integer> m) { // assign argument to a new list of // five temperature values. m = new list<integer>{55, 59, 62, 60, 63}; } } versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. using constructors a constructor is code that is invoked when an object is created from the class blueprint. you do not need to write a constructor for every class. if a class does not have a user-defined constructor, a default, no-argument, public constructor is used. the syntax for a constructor is similar to a method, but it differs from a method definition in that it never has an explicit return type and it is not inherited by the object created from it. 64apex developer guide classes, objects, and interfaces after you write the constructor for a class, you must use the new keyword in order to instantiate an object from that class, using that constructor. for example, using the following class: public class testobject { // the no argument constructor public testobject() { // more code here } } a new object of this type can be instantiated with the following code: testobject mytest = new testobject(); if you write a constructor that takes arguments, you can then use that constructor to create an object using those arguments. if you create a constructor that takes arguments, and you still want to use a no-argument constructor, you must create your own no-argument constructor in your code. once you create a constructor for a class, you no longer have access to the default, no-argument public constructor. in apex, a constructor can be overloaded, that is, there can be more than one constructor for a class, each having different parameters. the following example illustrates a class with two constructors: one with no arguments and one that takes a simple integer argument. it also illustrates how one constructor calls another constructor using the this(...) syntax, also know as constructor chaining. public class testobject2 { private static final integer default_size = 10; integer size; //constructor with no arguments public testobject2() { this(default_size); // using this(...) calls the one argument constructor } // constructor with one argument public testobject2(integer objectsize) { size = objectsize; } } new objects of this type can be instantiated with the following code: testobject2 myobject1 = new testobject2(42); testobject2 myobject2 = new testobject2(); every constructor that you create for a class must have a different argument list. in the following example, all of the constructors are possible: public class leads { // first a no-argument constructor public leads () {} // a constructor with one argument public leads (boolean call) {} 65apex developer guide classes, objects, and inter
faces // a constructor with two arguments public leads (string email, boolean call) {} // though this constructor has the same arguments as the // one above, they are in a different order, so this is legal public leads (boolean call, string email) {} } when you define a new class, you are defining a new data type. you can use class name in any place you can use other data type names, such as string, boolean, or account. if you define a variable whose type is a class, any object you assign to it must be an instance of that class or subclass. access modifiers apex allows you to use the private, protected, public, and global access modifiers when defining methods and variables. while triggers and anonymous blocks can also use these access modifiers, they aren’t as useful in smaller portions of apex. for example, declaring a method as global in an anonymous block doesn’t enable you to call it from outside of that code. for more information on class access modifiers, see apex class definition on page 60. note: interface methods have no access modifiers. they’re always global. for more information, see interfaces on page 78. by default, a method or variable is visible only to the apex code within the defining class. explicitly specify a method or variable as public in order for it to be available to other classes in the same application namespace (see namespace prefix). you can change the level of visibility by using the following access modifiers: private this access modifier is the default, and means that the method or variable is accessible only within the apex class in which it’s defined. if you don’t specify an access modifier, the method or variable is private. protected this means that the method or variable is visible to any inner classes in the defining apex class, and to the classes that extend the defining apex class. you can only use this access modifier for instance methods and member variables. this setting is strictly more permissive than the default (private) setting, just like java. public this means that the method or variable is accessible by all apex within a specific package. for accessibility by all second-generation (2gp) managed packages that share a namespace, use public with the @namespaceaccessible annotation. using the public access modifier in no-namespace packages implicitly renders the apex code as @namespaceaccessible. note: in apex, the public access modifier isn’t the same as it is in java. this was done to discourage joining applications, to keep the code for each application separate. in apex, if you want to make something public like it is in java, you must use the global access modifier. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. global this means the method or variable can be used by any apex code that has access to the class, not just the apex code in the same application. this access modifier must be used for any method that must be referenced outside of the application, either in soap api or by other apex code. if you declare a method or variable as global, you must also declare the class that contains it as global. note: we recommend using the global access modifier rarely, if at all. cross-application dependencies are difficult to maintain. 66apex developer guide classes, objects, and interfaces to use the private, protected, public, or global access modifiers, use the following syntax: [(none)|private|protected|public|global] declaration for example: // private variable s1 private string s1 = '1'; // public method getsz() public string getsz() { ... } static and instance methods, variables, and initialization code in apex, you can have static methods, variables, and initialization code. however, apex classes can't be static. you can also have instance methods, member variables, and initialization code, which have no modifier, and local variables. characteristics static methods, variables, and initialization code have these characteristics. • they’re associated with a class. • they’re allowed only in outer classes. • they’re initialized only when a class is loaded. • they aren’t transmitted as part of the view state for a visualforce page. instance methods, member variables, and initialization code have these characteristics. • they’re associated with a particular object. • they have no definition modifier. • they’re created with every object instantiated from the class in which they’re declared. local variables have these characteristics. • they’re associated
with the block of code in which they’re declared. • they must be initialized before they’re used. the following example shows a local variable whose scope is the duration of the if code block. boolean mycondition = true; if (mycondition) { integer localvariable = 10; } using static methods and variables you can use static methods and variables only with outer classes. inner classes have no static methods or variables. a static method or variable doesn’t require an instance of the class in order to run. before an object of a class is created, all static member variables in a class are initialized, and all static initialization code blocks are executed. these items are handled in the order in which they appear in the class. a static method is used as a utility method, and it never depends on the value of an instance member variable. because a static method is only associated with a class, it can’t access the instance member variable values of its class. 67apex developer guide classes, objects, and interfaces a static variable is static only within the scope of the apex transaction. it’s not static across the server or the entire organization. the value of a static variable persists within the context of a single transaction and is reset across transaction boundaries. for example, if an apex dml request causes a trigger to fire multiple times, the static variables persist across these trigger invocations. to store information that is shared across instances of a class, use a static variable. all instances of the same class share a single copy of the static variable. for example, all triggers that a single transaction spawns can communicate with each other by viewing and updating static variables in a related class. a recursive trigger can use the value of a class variable to determine when to exit the recursion. suppose that you had the following class. public class p { public static boolean firstrun = true; } a trigger that uses this class could then selectively fail the first run of the trigger. trigger t1 on account (before delete, after delete, after undelete) { if(trigger.isbefore){ if(trigger.isdelete){ if(p.firstrun){ trigger.old[0].adderror('before account delete error'); p.firstrun=false; } } } } a static variable defined in a trigger doesn't retain its value between different trigger contexts within the same transaction, such as between before insert and after insert invocations. instead, define the static variables in a class so that the trigger can access these class member variables and check their static values. a class static variable can’t be accessed through an instance of that class. if class myclass has a static variable mystaticvariable, and myclassinstance is an instance of myclass, myclassinstance.mystaticvariable isn’t a legal expression. the same is true for instance methods. if mystaticmethod() is a static method, myclassinstance.mystaticmethod() isn’t legal. instead, refer to those static identifiers using the class: myclass.mystaticvariable and myclass.mystaticmethod(). local variable names are evaluated before class names. if a local variable has the same name as a class, the local variable hides methods and variables on the class of the same name. for example, this method works if you comment out the string line. but if the string line is included the method doesn’t compile, because salesforce reports that the method doesn’t exist or has an incorrect signature. public static void method() { string database = ''; database.insert(new account()); } an inner class behaves like a static java inner class, but doesn’t require the static keyword. an inner class can have instance member variables like an outer class, but there’s no implicit pointer to an instance of the outer class (using the this keyword). note: in api version 20.0 and earlier, if a bulk api request causes a trigger to fire, each chunk of 200 records for the trigger to process is split into chunks of 100 records. in salesforce api version 21.0 and later, no further splits of api chunks occur. if a bulk api request causes a trigger to fire multiple times for chunks of 200 records, governor limits are reset between these trigger invocations for the same http request. 68apex developer guide classes, objects, and interfaces using instance methods and variables instance methods and member variables are used by an instance of a class, that is, by an object. an instance member variable is declared inside a class, but not within a method. instance methods usually use instance member variables to affect the behavior of the method
. suppose that you want to have a class that collects two-dimensional points and plots them on a graph. the following skeleton class uses member variables to hold the list of points and an inner class to manage the two-dimensional list of points. public class plotter { // this inner class manages the points class point { double x; double y; point(double x, double y) { this.x = x; this.y = y; } double getxcoordinate() { return x; } double getycoordinate() { return y; } } list<point> points = new list<point>(); public void plot(double x, double y) { points.add(new point(x, y)); } // the following method takes the list of points and does something with them public void render() { } } using initialization code instance initialization code is a block of code in the following form that is defined in a class. { //code body } the instance initialization code in a class is executed each time an object is instantiated from that class. these code blocks run before the constructor. if you don’t want to write your own constructor for a class, you can use an instance initialization code block to initialize instance variables. in simple situations, use an ordinary initializer. reserve initialization code for complex situations, such as initializing a static map. a static initialization block runs only one time, regardless of how many times you access the class that contains it. 69apex developer guide classes, objects, and interfaces static initialization code is a block of code preceded with the keyword static. static { //code body } similar to other static code, a static initialization code block is only initialized one time on the first use of the class. a class can have any number of either static or instance initialization code blocks. they can appear anywhere in the code body. the code blocks are executed in the order in which they appear in the file, just as they are in java. you can use static initialization code to initialize static final variables and to declare information that is static, such as a map of values. for example: public class myclass { class rgb { integer red; integer green; integer blue; rgb(integer red, integer green, integer blue) { this.red = red; this.green = green; this.blue = blue; } } static map<string, rgb> colormap = new map<string, rgb>(); static { colormap.put('red', new rgb(255, 0, 0)); colormap.put('cyan', new rgb(0, 255, 255)); colormap.put('magenta', new rgb(255, 0, 255)); } } versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. apex properties an apex property is similar to a variable; however, you can do additional things in your code to a property value before it’s accessed or returned. properties can be used to validate data before a change is made, to prompt an action when data is changed (such as altering the value of other member variables), or to expose data that is retrieved from some other source (such as another class). property definitions include one or two code blocks, representing a get accessor and a set accessor: • the code in a get accessor executes when the property is read. • the code in a set accessor executes when the property is assigned a new value. 70apex developer guide classes, objects, and interfaces if a property has only a get accessor, it’s considered read-only. if a property has only a set accessor, it’s considered write-only. a property with both accessors is considered read-write. to declare a property, use the following syntax in the body of a class: public class basicclass { // property declaration access_modifier return_type property_name { get { //get accessor code block } set { //set accessor code block } } } where: • access_modifier is the access modifier for the property. the access modifiers that can be applied to properties include: public, private, global, and protected. in addition,
these definition modifiers can be applied: static and transient. for more information on access modifiers, see access modifiers on page 66. • return_type is the type of the property, such as integer, double, sobject, and so on. for more information, see data types on page 24. • property_name is the name of the property for example, the following class defines a property named prop. the property is public. the property returns an integer data type. public class basicproperty { public integer prop { get { return prop; } set { prop = value; } } } the following code segment calls the basicproperty class, exercising the get and set accessors: basicproperty bp = new basicproperty(); bp.prop = 5; // calls set accessor system.assertequals(5, bp.prop); // calls get accessor note the following: • the body of the get accessor is similar to that of a method. it must return a value of the property type. executing the get accessor is the same as reading the value of the variable. • the get accessor must end in a return statement. • we recommend that your get accessor not change the state of the object that it’s defined on. • the set accessor is similar to a method whose return type is void. • when you assign a value to the property, the set accessor is invoked with an argument that provides the new value. • in api version 42.0 and later, unless a variable value is set in a set accessor, you can’t update its value in a get accessor. • when the set accessor is invoked, the system passes an implicit argument to the setter called value of the same data type as the property. • properties can’t be defined on interface. 71apex developer guide classes, objects, and interfaces • apex properties are based on their counterparts in c#, with the following differences: – properties provide storage for values directly. you don’t need to create supporting members for storing values. – it’s possible to create automatic properties in apex. for more information, see using automatic properties on page 72. using automatic properties properties don’t require additional code in their get or set accessor code blocks. instead, you can leave get and set accessor code blocks empty to define an automatic property. automatic properties allow you to write more compact code that is easier to debug and maintain. they can be declared as read-only, read-write, or write-only. the following example creates three automatic properties: public class automaticproperty { public integer myreadonlyprop { get; } public double myreadwriteprop { get; set; } public string mywriteonlyprop { set; } } the following code segment exercises these properties: automaticproperty ap = new automaticproperty(); ap.myreadonlyprop = 5; // this produces a compile error: not writable ap.myreadwriteprop = 5; // no error system.assertequals(5, ap.mywriteonlyprop); // this produces a compile error: not readable using static properties when a property is declared as static, the property's accessor methods execute in a static context. therefore, accessors don’t have access to non-static member variables defined in the class. the following example creates a class with both static and instance properties: public class staticproperty { private static integer staticmember; private integer nonstaticmember; // the following produces a system error // public static integer mybadstaticprop { return nonstaticmember; } public static integer mygoodstaticprop { get {return staticmember;} set { staticmember = value; } } public integer mygoodnonstaticprop { get {return nonstaticmember;} set { nonstaticmember = value; } } } the following code segment calls the static and instance properties: staticproperty sp = new staticproperty(); // the following produces a system error: a static variable cannot be // accessed through an object instance // sp.mygoodstaticprop = 5; 72apex developer guide classes, objects, and interfaces // the following does not produce an error staticproperty.mygoodstaticprop = 5; using access modifiers on property accessors property accessors can be defined with their own access modifiers. if an accessor includes its own access modifier, this modifier overrides the access modifier of the property. the access modifier of an individual accessor must be more restrictive than the access modifier on the property itself. for example, if the property has been defined as public, the individual accessor can’
t be defined as global. the following class definition shows additional examples: global virtual class propertyvisibility { // x is private for read and public for write public integer x { private get; set; } // y can be globally read but only written within a class global integer y { get; public set; } // z can be read within the class but only subclasses can set it public integer z { get; protected set; } } extending a class you can extend a class to provide more specialized behavior. a class that extends another class inherits all the methods and properties of the extended class. in addition, the extending class can override the existing virtual methods by using the override keyword in the method definition. overriding a virtual method allows you to provide a different implementation for an existing method. this means that the behavior of a particular method is different based on the object you’re calling it on. this is referred to as polymorphism. a class extends another class using the extends keyword in the class definition. a class can only extend one other class, but it can implement more than one interface. this example shows how the yellowmarker class extends the marker class. to run the inheritance examples in this section, first create the marker class. public virtual class marker { public virtual void write() { system.debug('writing some text.'); } public virtual double discount() { return .05; } } then create the yellowmarker class, which extends the marker class. // extension for the marker class public class yellowmarker extends marker { public override void write() { system.debug('writing some text using the yellow marker.'); } } this code segment shows polymorphism. the example declares two objects of the same type (marker). even though both objects are markers, the second object is assigned to an instance of the yellowmarker class. hence, calling the write method on it yields 73apex developer guide classes, objects, and interfaces a different result than calling this method on the first object, because this method has been overridden. however, you can call the discount method on the second object even though this method isn't part of the yellowmarker class definition. but it’s part of the extended class, and hence, is available to the extending class, yellowmarker. run this snippet in the execute anonymous window of the developer console. marker obj1, obj2; obj1 = new marker(); // this outputs 'writing some text.' obj1.write(); obj2 = new yellowmarker(); // this outputs 'writing some text using the yellow marker.' obj2.write(); // we get the discount method for free // and can call it from the yellowmarker instance. double d = obj2.discount(); the extending class can have more method definitions that aren't common with the original extended class. in this example, the redmarker class extends the marker class and has one extra method, computeprice, that isn't available for the marker class. to call the extra methods, the object type must be the extending class. before running the next snippet, create the redmarker class, which requires the marker class in your org. // extension for the marker class public class redmarker extends marker { public override void write() { system.debug('writing some text in red.'); } // method only in this class public double computeprice() { return 1.5; } } this snippet shows how to call the additional method on the redmarker class. run this snippet in the execute anonymous window of the developer console. redmarker obj = new redmarker(); // call method specific to redmarker only double price = obj.computeprice(); extensions also apply to interfaces—an interface can extend another interface. as with classes, when an interface extends another interface, all the methods and properties of the extended interface are available to the extending interface. versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. 74apex developer guide classes, objects, and interfaces extended class example the following is an extended example of a class, showing all the features of apex classes. the keywords and concepts introduced in the example are explained in more
detail throughout this chapter. // top-level (outer) class must be public or global (usually public unless they contain // a web service, then they must be global) public class outerclass { // static final variable (constant) – outer class level only private static final integer my_int; // non-final static variable - use this to communicate state across triggers // within a single request) public static string sharedstate; // static method - outer class level only public static integer getint() { return my_int; } // static initialization (can be included where the variable is defined) static { my_int = 2; } // member variable for outer class private final string m; // instance initialization block - can be done where the variable is declared, // or in a constructor { m = 'a'; } // because no constructor is explicitly defined in this outer class, an implicit, // no-argument, public constructor exists // inner interface public virtual interface myinterface { // no access modifier is necessary for interface methods - these are always // public or global depending on the interface visibility void mymethod(); } // interface extension interface mysecondinterface extends myinterface { integer method2(integer i); } // inner class - because it is virtual it can be extended. // this class implements an interface that, in turn, extends another interface. // consequently the class must implement all methods. public virtual class innerclass implements mysecondinterface { // inner member variables 75apex developer guide classes, objects, and interfaces private final string s; private final string s2; // inner instance initialization block (this code could be located above) { this.s = 'x'; } // inline initialization (happens after the block above executes) private final integer i = s.length(); // explicit no argument constructor innerclass() { // this invokes another constructor that is defined later this('none'); } // constructor that assigns a final variable value public innerclass(string s2) { this.s2 = s2; } // instance method that implements a method from myinterface. // because it is declared virtual it can be overridden by a subclass. public virtual void mymethod() { /* does nothing */ } // implementation of the second interface method above. // this method references member variables (with and without the "this" prefix) public integer method2(integer i) { return this.i + s.length(); } } // abstract class (that subclasses the class above). no constructor is needed since // parent class has a no-argument constructor public abstract class abstractchildclass extends innerclass { // override the parent class method with this signature. // must use the override keyword public override void mymethod() { /* do something else */ } // same name as parent class method, but different signature. // this is a different method (displaying polymorphism) so it does not need // to use the override keyword protected void method2() {} // abstract method - subclasses of this class must implement this method abstract integer abstractmethod(); } // complete the abstract class by implementing its abstract method public class concretechildclass extends abstractchildclass { // here we expand the visibility of the parent method - note that visibility // cannot be restricted by a sub-class public override integer abstractmethod() { return 5; } } 76apex developer guide classes, objects, and interfaces // a second sub-class of the original innerclass public class anotherchildclass extends innerclass { anotherchildclass(string s) { // explicitly invoke a different super constructor than one with no arguments super(s); } } // exception inner class public virtual class myexception extends exception { // exception class member variable public double d; // exception class constructor myexception(double d) { this.d = d; } // exception class method, marked as protected protected void doit() {} } // exception classes can be abstract and implement interfaces public abstract class mysecondexception extends exception implements myinterface { } } this code example illustrates: • a top-level class definition (also called an outer class) • static variables and static methods in the top-level class, as well as static initialization code blocks • member variables and methods for the top-level class • classes with no user-defined constructor — these have an implicit, no-argument constructor • an interface definition in the top-level class • an interface that extends another interface • inner class definitions (one level
deep) within a top-level class • a class that implements an interface (and, therefore, its associated sub-interface) by implementing public versions of the method signatures • an inner class constructor definition and invocation • an inner class member variable and a reference to it using the this keyword (with no arguments) • an inner class constructor that uses the this keyword (with arguments) to invoke a different constructor • initialization code outside of constructors — both where variables are defined, as well as with anonymous blocks in curly braces ({}). note that these execute with every construction in the order they appear in the file, as with java. • class extension and an abstract class • methods that override base class methods (which must be declared virtual) • the override keyword for methods that override subclass methods • abstract methods and their implementation by concrete sub-classes 77apex developer guide classes, objects, and interfaces • the protected access modifier • exceptions as first class objects with members, methods, and constructors this example shows how the class above can be called by other apex code: // construct an instance of an inner concrete class, with a user-defined constructor outerclass.innerclass ic = new outerclass.innerclass('x'); // call user-defined methods in the class system.assertequals(2, ic.method2(1)); // define a variable with an interface data type, and assign it a value that is of // a type that implements that interface outerclass.myinterface mi = ic; // use instanceof and casting as usual outerclass.innerclass ic2 = mi instanceof outerclass.innerclass ? (outerclass.innerclass)mi : null; system.assert(ic2 != null); // construct the outer type outerclass o = new outerclass(); system.assertequals(2, outerclass.getint()); // construct instances of abstract class children system.assertequals(5, new outerclass.concretechildclass().abstractmethod()); // illegal - cannot construct an abstract class // new outerclass.abstractchildclass(); // illegal – cannot access a static method through an instance // o.getint(); // illegal - cannot call protected method externally // new outerclass.concretechildclass().method2(); this code example illustrates: • construction of the outer class • construction of an inner class and the declaration of an inner interface type • a variable declared as an interface type can be assigned an instance of a class that implements that interface • casting an interface variable to be a class type that implements that interface (after verifying this using the instanceof operator) interfaces an interface is like a class in which none of the methods have been implemented—the method signatures are there, 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 can provide a layer of abstraction to your code. they separate the specific implementation of a method from the declaration for that method. this way you can have different implementations of a method based on your specific application. defining an interface is similar to defining a new class. for example, a company can have two types of purchase orders, ones that come from customers, and others that come from their employees. both are a type of purchase order. suppose you needed a method to provide a discount. the amount of the discount can depend on the type of purchase order. 78apex developer guide classes, objects, and interfaces you can model the general concept of a purchase order as an interface and have specific implementations for customers and employees. in the following example the focus is only on the discount aspect of a purchase order. here’s the definition of the purchaseorder interface. // an interface that defines what a purchase order looks like in general public interface purchaseorder { // all other functionality excluded double discount(); } this class implements the purchaseorder interface for customer purchase orders. // one implementation of the interface for customers public class customerpurchaseorder implements purchaseorder { public double discount() { return .05; // flat 5% discount } } this class implements the purchaseorder interface for employee purchase orders. // another implementation of the interface for employees public class employeepurchaseorder implements purchaseorder { public double discount() { return .10; // it’s worth it being an employee! 10% discount } } note the following about the example: • the interface purchaseorder is defined as a general prototype. methods defined within an interface have no access modifiers and contain just their signature. • the customerpurchaseorder class implements this
interface; therefore, it must provide a definition for the discount method. any class that implements an interface must define all the methods contained in the interface. when you define a new interface, you’re defining a new data type. you can use an interface name in any place you can use another data type name. any object assigned to a variable of type interface must be an instance of a class that implements the interface, or a sub-interface data type. see also classes and casting on page 108. note: you can’t add a method to a global interface after the class has been uploaded in a managed - released package version. versioned behavior changes in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see namespaceaccessible annotation. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. in this section: 1. custom iterators 79apex developer guide classes, objects, and interfaces custom iterators an iterator traverses through every item in a collection. for example, in a while loop in apex, you define a condition for exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. in this example, count is incremented by 1 every time the loop is executed. while (count < 11) { system.debug(count); count++; } using the iterator interface you can create a custom set of instructions for traversing a list through a loop. the iterator is useful for data that exists in sources outside of salesforce that you would normally define the scope of using a select statement. iterators can also be used if you have multiple select statements. using custom iterators to use custom iterators, you must create an apex class that implements the iterator interface. the iterator interface has the following instance methods: name arguments returns description hasnext boolean returns true if there’s another item in the collection being traversed, false otherwise. next any type returns the next item in the collection. all methods in the iterator interface must be declared as global or public. you can only use a custom iterator in a while loop. for example: iterablestring x = new iterablestring('this is a really cool test.'); while(x.hasnext()){ system.debug(x.next()); } iterators aren’t currently supported in for loops. using custom iterators with iterable if you don’t want to use a custom iterator with a list, but instead want to create your own data structure, you can use the iterable interface to generate the data structure. the iterable interface has the following method: name arguments returns description iterator iterator class returns a reference to the iterator for this interface. the iterator method must be declared as global or public. it creates a reference to the iterator that you can then use to traverse the data structure. 80apex developer guide classes, objects, and interfaces in the following example a custom iterator iterates through a collection: public class customiterator implements iterator<account>{ private list<account> accounts; private integer currentindex; public customiterator(list<account> accounts){ this.accounts = accounts; this.currentindex = 0; } public boolean hasnext(){ return currentindex < accounts.size(); } public account next(){ if(hasnext()) { return accounts[currentindex++]; } else { throw new nosuchelementexception('iterator has no more elements.'); } } } public class customiterable implements iterable<account> { public iterator<account> iterator(){ list<account> accounts = [select id, name, numberofemployees from account limit 10]; return new customiterator(accounts); } } the following is a batch job that uses an iterator: public class batchclass implements database.batchable<account>{ public iterable<account> start(database.batchablecontext info){ return new customiterable(); } public void execute(database.batchablecontext info, list<account> scope){ list<account> accstoupdate = new list<account>(); for(account acc : scope){ acc.name = 'changed'; acc.numberofemployees = 69; accstoupdate.add(acc); } update accstoupdate;
} public void finish(database.batchablecontext info){ } } 81apex developer guide classes, objects, and interfaces keywords apex provides the keywords final, instanceof, super, this, transient, with sharing and without sharing. in this section: 1. using the final keyword 2. using the instanceof keyword 3. using the super keyword 4. using the this keyword 5. using the transient keyword 6. using the with sharing, without sharing, and inherited sharing keywords use the with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. use the inherited sharing keyword on a class to run the class in the sharing mode of the class that called it. using the final keyword you can use the final keyword to modify variables. • final variables can only be assigned a value once, either when you declare a variable or inside a constructor. you must assign a value to it in one of these two places. • static final variables can be changed in static initialization code or where defined. • member final variables can be changed in initialization code blocks, constructors, or with other variable declarations. • to define a constant, mark a variable as both static and final. • non-final static variables are used to communicate state at the class level (such as state between triggers). however, they are not shared across requests. • methods and classes are final by default. you cannot use the final keyword in the declaration of a class or method. this means they cannot be overridden. use the virtual keyword if you need to override a method or class. using the instanceof keyword if you need to verify at run time whether an object is actually an instance of a particular class, use the instanceof keyword. the instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable alternative for the declared type of the expression on the left. you could add the following check to the report class in the classes and casting example before you cast the item back into a customreport object. if (reports.get(0) instanceof customreport) { // can safely cast it back to a custom report object customreport c = (customreport) reports.get(0); } else { // do something with the non-custom-report. } 82apex developer guide classes, objects, and interfaces note: in apex saved with api version 32.0 and later, instanceof returns false if the left operand is a null object. for example, the following sample returns false. object o = null; boolean result = o instanceof account; system.assertequals(false, result); in api version 31.0 and earlier, instanceof returns true in this case. using the super keyword the super keyword can be used by classes that are extended from virtual or abstract classes. by using super, you can override constructors and methods from the parent class. for example, if you have the following virtual class: public virtual class superclass { public string mysalutation; public string myfirstname; public string mylastname; public superclass() { mysalutation = 'mr.'; myfirstname = 'carl'; mylastname = 'vonderburg'; } public superclass(string salutation, string firstname, string lastname) { mysalutation = salutation; myfirstname = firstname; mylastname = lastname; } public virtual void printname() { system.debug('my name is ' + mysalutation + mylastname); } public virtual string getfirstname() { return myfirstname; } } you can create the following class that extends superclass and overrides its printname method: public class subclass extends superclass { public override void printname() { super.printname(); system.debug('but you can call me ' + super.getfirstname()); } } the expected output when calling subclass.printname is my name is mr. vonderburg. but you can call me carl. 83apex developer guide classes, objects, and interfaces you can also use super to call constructors. add the following constructor to subclass: public subclass() { super('madam', 'brenda', 'clapentrap'); } now, the expected output of subclass.printname is my name is madam clapentrap. but you can call me brenda. best practices for using the super keyword • only classes that are extending from virtual or abstract classes can
use super. • you can only use super in methods that are designated with the override keyword. using the this keyword there are two different ways of using the this keyword. you can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it appears. use this form of the this keyword to access instance variables and methods. for example: public class mytestthis { string s; { this.s = 'teststring'; } } in the above example, the class mytestthis declares an instance variable s. the initialization code populates the variable using the this keyword. or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. in this format, use the this keyword with parentheses. for example: public class testthis { // first constructor for the class. it requires a string parameter. public testthis(string s2) { } // second constructor for the class. it does not require a parameter. // this constructor calls the first constructor using the this keyword. public testthis() { this('none'); } } when you use the this keyword in a constructor to do constructor chaining, it must be the first statement in the constructor. 84apex developer guide classes, objects, and interfaces using the transient keyword use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state for a visualforce page. for example: transient integer currenttotal; you can also use the transient keyword in apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the batchable or schedulable interface. in addition, you can use transient in classes that define the types of fields declared in the serializable classes. declaring variables as transient reduces view state size. a common use case for the transient keyword is a field on a visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many system resources to be recomputed many times during a request. some apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. these objects include the following: • pagereferences • xmlstream classes • collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as a collection of savepoints • most of the objects generated by system methods, such as schema.getglobaldescribe. • jsonparser class instances. static variables also don't get transmitted through the view state. the following example contains both a visualforce page and a custom controller. clicking the refresh button on the page causes the transient date to be updated because it is being recreated each time the page is refreshed. the non-transient date continues to have its original value, which has been deserialized from the view state, so it remains the same. <apex:page controller="examplecontroller"> t1: {!t1} <br/> t2: {!t2} <br/> <apex:form> <apex:commandlink value="refresh"/> </apex:form> </apex:page> public class examplecontroller { datetime t1; transient datetime t2; public string gett1() { if (t1 == null) t1 = system.now(); return '' + t1; } public string gett2() { if (t2 == null) t2 = system.now(); return '' + t2; 85apex developer guide classes, objects, and interfaces } } see also: apex reference guide: jsonparser class using the with sharing, without sharing, and inherited sharing keywords use the with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. use the inherited sharing keyword on a class to run the class in the sharing mode of the class that called it. with sharing use the with sharing keyword when declaring a class to enforce sharing rules of the current user. explicitly setting this keyword ensures that apex code runs in the current user context. apex code that is executed with the executeanonymous call and connect in apex always execute using the sharing rules of the current user. for more information on executeanonymous, see anonymous blocks on page 230. use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. for example: public with sharing class sharingclass { // code here
} without sharing use the without sharing keyword when declaring a class to ensure that the sharing rules for the current user are not enforced. for example, you can explicitly turn off sharing rule enforcement when a class is called from another class that is declared using with sharing. public without sharing class nosharing { // code here } inherited sharing use the inherited sharing keyword when declaring a class to enforce the sharing rules of the class that calls it. using inherited sharing is an advanced technique to determine the sharing mode at runtime and design apex classes that can run in either with sharing or without sharing mode. warning: because the sharing mode is determined at runtime, you must take extreme care to ensure that your apex code is secure to run in both with sharing and without sharing modes. using inherited sharing, along with other appropriate security checks, facilitates in passing appexchange security review and ensures that your privileged apex code isn’t used in unexpected or insecure ways. an apex class with inherited sharing runs as with sharing when used as: • an aura component controller 86apex developer guide classes, objects, and interfaces • a visualforce controller • an apex rest service • any other entry point to an apex transaction there’s a distinct difference between an apex class that is marked with inherited sharing and one with an omitted sharing declaration. if the class is used as the entry point to an apex transaction, an omitted sharing declaration runs as without sharing. however, inherited sharing ensures that the default is to run as with sharing. a class declared as inherited sharing runs as without sharing only when explicitly called from an already established without sharing context. example: this example declares an apex class with inherited sharing and a visualforce invocation of that apex code. because of the inherited sharing declaration, only contacts for which the running user has sharing access are displayed. if the declaration is omitted, contacts that the user has no rights to view are displayed due to the insecure default behavior. public inherited sharing class inheritedsharingclass { public list<contact> getallthesecrets() { return [select name from contact]; } } <apex:page controller="inheritedsharingclass"> <apex:repeat value="{!allthesecrets}" var="record"> {!record.name} </apex:repeat> </apex:page> implementation details • the sharing setting of the class where a method is defined is applied, not of the class where the method is called from. for example, if a method is defined in a class declared as with sharing is called by a class declared as without sharing, the method executes with sharing rules enforced. • if a class isn’t explicitly declared as either with sharing or without sharing, the current sharing rules remain in effect. therefore, the class doesn’t enforce sharing rules except when it acquires sharing rules from another class. for example, if the class is called by another class that has sharing enforced, then sharing is enforced for the called class. • both inner classes and outer classes can be declared as with sharing. inner classes do not inherit the sharing setting from their container class. otherwise, the sharing setting applies to all code contained in the class, including initialization code, constructors, and methods. • classes inherit sharing setting from a parent class when one class extends or implements another. • apex triggers can’t have an explicit sharing declaration and run as without sharing. best practices apex without an explicit sharing declaration is insecure by default. we strongly recommend that you always specify a sharing declaration for a class. regardless of the sharing mode, object-level access and field-level security are not enforced by apex. you must enforce object-level access and field-level security in your soql queries or code. for example, with sharing mechanism doesn’t enforce user’s access to view reports and dashboards. you must explicitly enforce running user’s crud (create, read, update, delete) and field-level security in your code. see enforcing object and field permissions. 87apex developer guide classes, objects, and interfaces sharing mode when to use with sharing use this mode as the default unless your use case requires otherwise. without sharing use this mode with caution. ensure that you don’t inadvertently expose sensitive data that would normally be hidden by the sharing model. this sharing mechanism is best used to grant targeted elevation of sharing privileges to the current user. for example, use without sharing to allow community users to read records to which they wouldn’t otherwise have access. inherited sharing use this mode for service classes that have to be flexible and
support use cases with different sharing modes while also defaulting to the more secure with sharing mode. annotations an apex annotation modifies the way that a method or class is used, similar to annotations in java. annotations are defined with an initial @ symbol, followed by the appropriate keyword. to add an annotation to a method, specify it immediately before the method or class definition. for example: global class myclass { @future public static void mymethod(string a) { //long-running apex code } } apex supports the following annotations. • @auraenabled • @deprecated • @future • @invocablemethod • @invocablevariable • @istest • @jsonaccess • @namespaceaccessible • @readonly • @remoteaction • @suppresswarnings • @testsetup • @testvisible • apex rest annotations: 88apex developer guide classes, objects, and interfaces – @readonly – @restresource(urlmapping='/yoururl') – @httpdelete – @httpget – @httppatch – @httppost – @httpput in this section: 1. auraenabled annotation 2. deprecated annotation 3. future annotation 4. invocablemethod annotation use the invocablemethod annotation to identify methods that can be run as invocable actions. 5. invocablevariable annotation use the invocablevariable annotation to identify variables used by invocable methods in custom classes. 6. istest annotation 7. jsonaccess annotation 8. namespaceaccessible annotation 9. readonly annotation 10. remoteaction annotation 11. suppresswarnings annotation this annotation does nothing in apex but can be used to provide information to third-party tools. 12. testsetup annotation methods defined with the @testsetup annotation are used for creating common test records that are available for all test methods in the class. 13. testvisible annotation auraenabled annotation the @auraenabled annotation enables client-side and server-side access to an apex controller method. providing this annotation makes your methods available to your lightning components (both lightning web components and aura components). only methods with this annotation are exposed. in api version 44.0 and later, you can improve runtime performance by caching method results on the client by using the annotation @auraenabled(cacheable=true). you can cache method results only for methods that retrieve data but don’t modify it. using this annotation eliminates the need to call setstorable() in javascript code on every action that calls the apex method. in api version 55.0 and later, you can use the annotation @auraenabled(cacheable=true scope='global') to enable apex methods to be cached in a global cache. for more information, see lightning aura components developer guide and lightning web components developer guide. 89apex developer guide classes, objects, and interfaces versioned behavior changes in api version 55.0 and later, overloads aren’t allowed on methods annotated with @auraenabled. deprecated annotation use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. this annotation is useful when you’re refactoring code in managed packages as the requirements evolve. new subscribers can’t see the deprecated elements, while the elements continue to function for existing subscribers and api integrations. the following code snippet shows a deprecated method. the same syntax can be used to deprecate classes, exceptions, enums, interfaces, or variables. @deprecated // this method is deprecated. use myoptimizedmethod(string a, string b) instead. global void mymethod(string a) { } note the following rules when deprecating apex identifiers: • unmanaged packages can’t contain code that uses the deprecated keyword. • when an apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be deprecated. any global method that uses the deprecated type in its signature, either in an input argument or the method return type, must also be deprecated. a deprecated item, such as a method or a class, can still be referenced internally by the package developer. • webservice methods and variables can’t be deprecated. • you can deprecate an enum but you can’t deprecate individual enum values. • you can deprecate an interface but you can
’t deprecate individual methods in an interface. • you can deprecate an abstract class but you can’t deprecate individual abstract methods in an abstract class. • you can’t remove the deprecated annotation to undeprecate something in apex after you’ve released a package version where that item in apex is deprecated. for more information about package versions, see what is a package? on page 675. future annotation use the future annotation to identify methods that are executed asynchronously. when you specify future, the method executes when salesforce has available resources. for example, you can use the future annotation when making an asynchronous web service callout to an external service. without the annotation, the web service callout is made from the same thread that is executing the apex code, and no additional processing can occur until the callout is complete (synchronous processing). methods with the future annotation must be static methods, and can only return a void type. the specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. methods with the future annotation can’t take sobjects or objects as arguments. to make a method in a class execute asynchronously, define the method with the future annotation. for example: global class myfutureclass { @future static void mymethod(string a, integer i) { 90apex developer guide classes, objects, and interfaces system.debug('method called with: ' + a + ' and ' + i); // perform long-running code } } to allow callouts in a future method, specify (callout=true). the default is (callout=false), which prevents a method from making callouts. the following snippet shows how to specify that a method executes a callout: @future (callout=true) public static void docalloutfromfuture() { //add code to perform callout } future method considerations • remember that any method using the future annotation requires special consideration because the method doesn’t necessarily execute in the same order it’s called. • methods with the future annotation can’t be used in visualforce controllers in either getmethodname or setmethodname methods, nor in the constructor. • you can’t call a method annotated with future from a method that also has the future annotation. nor can you call a trigger from an annotated method that calls another annotated method. invocablemethod annotation use the invocablemethod annotation to identify methods that can be run as invocable actions. note: if a flow invokes apex, the running user must have the corresponding apex class security set in their user profile or permission set. invocable methods are called natively from rest, apex, flow, or einstein bot that interacts with the external api source. invocable methods have dynamic input and output values and support describe calls. this code sample shows an invocable method with primitive data types. public class accountqueryaction { @invocablemethod(label='get account names' description='returns the list of account names corresponding to the specified account ids.' category='account') public static list<string> getaccountnames(list<id> ids) { list<string> accountnames = new list<string>(); map<id, account> accounts = new map<id, account>[select name from account where id in :ids]; for (id id : ids) { string accname = accounts.get(id) == null ? ' ' : accounts.get(id) .name; accountnames.add(account.name); } return accountnames; } } this code sample shows an invocable method with a specific sobject data type. public class accountinsertaction { @invocablemethod(label='insert accounts' description='inserts the accounts specified and 91apex developer guide classes, objects, and interfaces returns the ids of the new accounts.' category= 'account') public static list<id> insertaccounts(list<account> accounts) { database.saveresult[] results = database.insert(accounts, false); list<id> accountids = new list<id>(); for (database.saveresult result : results) { accountids.add (result.issuccess()) { accountids.add(result.getid()); } } return accountids; } } this code sample shows an invocable method with the generic sobject data type. public with sharing class getfirstfromcollection {
@invocablemethod public static list <results> execute (list<requests> requestlist) { //wrap the results object in a list container //(an extra step added to allow this interface to also support bulkification) list<results> responsewrapper= new list<results>(); for (request req : requestlist) { list<sobject> inputcollection = req.inputcollection; sobject outputmember; outputmember = inputcollection[0]; } //create a results object to hold the return values result response = new result(); //add the return values to the results object response.outputmember = outputmember; responsewrapper.add(response); } return responsewrapper; } public class requests { @invocablevariable(label='records for input' description='yourdescription' required=true) public list<sobject> inputcollection; } public class result { @invocablevariable(label='records for output' description='yourdescription' required=true) public sobject outputmember; } } this code sample shows an invocable method with a custom icon from an svg file. global class customsvgicon { @invocablemethod(label='myicon' iconname='resource:mypackagenamespace__google:top') global static list<integer> mymethod(list<integer> request) { 92apex developer guide classes, objects, and interfaces list<integer> results = new list<integer>(); for(integer reqint : request) { results.add(reqint); } return results; } } this code sample shows an invocable method with a custom icon from the salesforce lightning design system (slds). public class customsldsicon { @invocablemethod(iconname='slds:standard:choice') public static void run() {} } supported modifiers all modifiers are optional. label the label for the method, which appears as the action name in flow builder. the default is the method name, though we recommend that you provide a label. description the description for the method, which appears as the action description in flow builder. the default is null. callout the callout modifier identifies whether the method makes a call to an external system. if the method makes a call to an external system, add callout=true. the default value is false. category the category for the method, which appears as the action category in flow builder. if no category is provided (by default), actions appear under uncategorized. configurationeditor the custom property editor that is registered with the method and appears in flow builder when an admin configures the action. if you don’t specify this modifier, flow builder uses the standard property editor. iconname the name of the icon to use as a custom icon for the action in the flow builder canvas. you can specify an svg file that you uploaded as a static resource or a salesforce lightning design system standard icon. invocablemethod considerations implementation notes • the invocable method must be static and public or global, and its class must be an outer class. • only one method in a class can have the invocablemethod annotation. • other annotations can’t be used with the invocablemethod annotation. inputs and outputs there can be at most one input parameter and its data type must be one of the following: • a list of a primitive data type or a list of lists of a primitive data type – the generic object type isn’t supported. 93apex developer guide classes, objects, and interfaces • a list of an sobject type or a list of lists of an sobject type. • a list of the generic sobject type (list<sobject>) or a list of lists of the generic sobject type (list<list<sobject>>). • a list of a user-defined type, containing variables of the supported types or user-defined apex types, with the invocablevariable annotation. create a custom global or public apex class to implement your data type, and make sure that your class contains at least one member variable with the invocable variable annotation. if the return type isn’t null, the data type returned by the method must be one of the following: • a list of a primitive data type or a list of lists of a primitive data type – the generic object type isn’t supported. • a list of an sobject type or a list of lists of an sobject type. • a list of the generic sobject type
(list<sobject>) or a list of lists of the generic sobject type (list<list<sobject>>). • a list of a user-defined type, containing variables of the supported types or user-defined apex types, with the invocablevariable annotation. create a custom global or public apex class to implement your data type, and make sure that your class contains at least one member variable with the invocable variable annotation. note: for a correct bulkification implementation, the inputs and outputs should match on both the size and the order. for example, the i-th output entry should correspond to the i-th input entry. this is required for data correctness when your action is in bulkified execution. for example, when apex action is used in a record trigger flow. managed packages • you can use invocable methods in packages, but after you add an invocable method you can’t remove it from later versions of the package. • public invocable methods can be referred to by flows and processes within the managed package. • global invocable methods can be referred to anywhere in the subscriber org. only global invocable methods appear in flow builder and process builder in the subscriber org. for more information about invocable actions, see actions developer guide. see also: salesforce help: add a custom icon to an apex-defined action apex reference guide: action class lightning web components developer guide: develop custom property editors for flow builder making callouts to external systems from invocable actions making callouts to external systems from invocable actions invocablevariable annotation use the invocablevariable annotation to identify variables used by invocable methods in custom classes. the invocablevariable annotation identifies a class variable used as an input or output parameter for an invocablemethod method’s invocable action. if you create your own custom class to use as the input or output to an invocable method, you can annotate individual class member variables to make them available to the method. the following code sample shows an invocable method with invocable variables. global class convertleadaction { @invocablemethod(label='convert leads') global static list<convertleadactionresult> convertleads(list<convertleadactionrequest> requests) { list<convertleadactionresult> results = new list<convertleadactionresult>(); 94apex developer guide classes, objects, and interfaces for (convertleadactionrequest request : requests) { results.add(convertlead(request)); } return results; } public static convertleadactionresult convertlead(convertleadactionrequest request) { database.leadconvert lc = new database.leadconvert(); lc.setleadid(request.leadid); lc.setconvertedstatus(request.convertedstatus); if (request.accountid != null) { lc.setaccountid(request.accountid); } if (request.contactid != null) { lc.setcontactid(request.contactid); } if (request.overwriteleadsource != null && request.overwriteleadsource) { lc.setoverwriteleadsource(request.overwriteleadsource); } if (request.createopportunity != null && !request.createopportunity) { lc.setdonotcreateopportunity(!request.createopportunity); } if (request.opportunityname != null) { lc.setopportunityname(request.opportunityname); } if (request.ownerid != null) { lc.setownerid(request.ownerid); } if (request.sendemailtoowner != null && request.sendemailtoowner) { lc.setsendnotificationemail(request.sendemailtoowner); } database.leadconvertresult lcr = database.convertlead(lc, true); if (lcr.issuccess()) { convertleadactionresult result = new convertleadactionresult(); result.accountid = lcr.getaccountid(); result.contactid = lcr.getcontactid(); result.opportunityid = lcr.getopportunityid(); return result; } else { throw new convertleadactionexception(lcr.geterrors()[0].getmessage()); } } global class convertleadactionrequest { @invocablevariable(required=true) global id leadid; 95apex developer guide classes, objects, and interfaces
@invocablevariable(required=true) global string convertedstatus; @invocablevariable global id accountid; @invocablevariable global id contactid; @invocablevariable global boolean overwriteleadsource; @invocablevariable global boolean createopportunity; @invocablevariable global string opportunityname; @invocablevariable global id ownerid; @invocablevariable global boolean sendemailtoowner; } global class convertleadactionresult { @invocablevariable global id accountid; @invocablevariable global id contactid; @invocablevariable global id opportunityid; } class convertleadactionexception extends exception {} } the following code sample shows an invocable method with invocable variables that have the generic sobject data type. public with sharing class getfirstfromcollection { @invocablemethod public static list <results> execute (list<requests> requestlist) { list<sobject> inputcollection = requestlist[0].inputcollection; sobject outputmember = inputcollection[0]; //create a results object to hold the return values results response = new results(); //add the return values to the results object response.outputmember = outputmember; //wrap the results object in a list container 96
apex developer guide classes, objects, and interfaces //(an extra step added to allow this interface to also support bulkification) list<results> responsewrapper= new list<results>(); responsewrapper.add(response); return responsewrapper; } } public class requests { @invocablevariable(label='records for input' description='yourdescription' required=true) public list<sobject> inputcollection; } public class results { @invocablevariable(label='records for output' description='yourdescription' required=true) public sobject outputmember; } } supported modifiers the invocable variable annotation supports the modifiers shown in this example. @invocablevariable(label='yourlabel' description='yourdescription' required=(true | false)) all modifiers are optional. label the label for the variable. the default is the variable name. tip: this label appears in flow builder for the action element that corresponds to an invocable method. this label helps admins understand how to use the variable in the flow. description the description for the variable. the default is null. required specifies whether the variable is required. if not specified, the default is false. the value is ignored for output variables. invocablevariable considerations • other annotations can’t be used with the invocablevariable annotation. • only global and public variables can be invocable variables. • the invocable variable can’t be one of the following: – a non-member variable such as a static or local variable. – a property. – a final variable. – protected or private. • the data type of the invocable variable must be one of the following: – a primitive other than object 97apex developer guide classes, objects, and interfaces – an sobject, either the generic sobject or a specific sobject – a list or a list of lists of primitives, sobjects, objects created from apex classes, or collections • the invocable variable name in apex must match the name in the flow. the name is case-sensitive. • for managed packages: – public invocable variables can be set in flows and processes within the same managed package. – global invocable variables can be set anywhere in the subscriber org. only global invocable variables appear in flow builder and process builder in the subscriber org. for more information about invocable actions, see actions developer guide. see also: apex reference guide: action class istest annotation use the @istest annotation to define classes and methods that only contain code used for testing your application. the annotation can take multiple modifiers within parentheses and separated by blanks. note: the @istest annotation on methods is equivalent to the testmethod keyword. as best practice, salesforce recommends that you use @istest rather than testmethod. the testmethod keyword may be versioned out in a future release. classes and methods defined as @istest can be either private or public. classes defined as @istest must be top-level classes. note: classes defined with the @istest annotation don't count against your organization limit of 6 mb for all apex code. here’s an example of a private test class that contains two test methods. @istest private class mytestclass { // methods for testing @istest static void test1() { // implement test code } @istest static void test2() { // implement test code } } here’s an example of a public test class that contains utility methods for test data creation: @istest public class testutil { public static void createtestaccounts() { // create some test accounts 98apex developer guide classes, objects, and interfaces } public static void createtestcontacts() { // create some test contacts } } classes defined as @istest can't be interfaces or enums. methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method. non-test requests can’t call public methods.. to learn about the various ways you can run test methods, see run unit test methods. @istest(seealldata=true) annotation for apex code saved using salesforce api version 24.0 and later, use the @istest(seealldata=true) annotation to grant test classes and individual test methods access to all data in the organization. the access includes pre-existing data that
the test didn’t create. starting with apex code saved using salesforce api version 24.0, test methods don’t have access to pre-existing data in the organization. however, test code saved against salesforce api version 23.0 and earlier continues to have access to all data in the organization. see isolation of test data from organization data in unit tests on page 641. considerations for the @istest(seealldata=true) annotation • if a test class is defined with the @istest(seealldata=true) annotation, the seealldata=true applies to all test methods that don’t explicitly set the seealldata keyword. • the @istest(seealldata=true) annotation is used to open up data access when applied at the class or method level. however, if the containing class has been annotated with @istest(seealldata=true), annotating a method with @istest(seealldata=false) is ignored for that method. in this case, that method still has access to all the data in the organization. annotating a method with @istest(seealldata=true) overrides, for that method, an @istest(seealldata=false) annotation on the class. • @istest(seealldata=true) and @istest(isparallel=true) annotations can’t be used together on the same apex method. this example shows how to define a test class with the @istest(seealldata=true) annotation. all the test methods in this class have access to all data in the organization. // all test methods in this class can access all data. @istest(seealldata=true) public class testdataaccessclass { // this test accesses an existing account. // it also creates and accesses a new test account. @istest static void mytestmethod1() { // query an existing account in the organization. account a = [select id, name from account where name='acme' limit 1]; system.assert(a != null); // create a test account based on the queried account. account testaccount = a.clone(); testaccount.name = 'acme test'; insert testaccount; // query the test account that was inserted. 99apex developer guide classes, objects, and interfaces account testaccount2 = [select id, name from account where name='acme test' limit 1]; system.assert(testaccount2 != null); } // like the previous method, this test method can also access all data // because the containing class is annotated with @istest(seealldata=true). @istest static void mytestmethod2() { // can access all data in the organization. } } this second example shows how to apply the @istest(seealldata=true) annotation on a test method. because the test method’s class isn’t annotated, you have to annotate the method to enable access to all data for the method. the second test method doesn’t have this annotation, so it can access only the data it creates. in addition, it can access objects that are used to manage your organization, such as users. // this class contains test methods with different data access levels. @istest private class classwithdifferentdataaccess { // test method that has access to all data. @istest(seealldata=true) static void testwithalldataaccess() { // can query all data in the organization. } // test method that has access to only the data it creates // and organization setup and metadata objects. @istest static void testwithowndataaccess() { // this method can still access the user object. // this query returns the first user object. user u = [select username,email from user limit 1]; system.debug('username: ' + u.username); system.debug('email: ' + u.email); // can access the test account that is created here. account a = new account(name='test account'); insert a; // access the account that was just created. account insertedacct = [select id,name from account where name='test account']; system.assert(insertedacct != null); } } @istest(oninstall=true) annotation use the @istest(oninstall=true) annotation to specify which apex tests are executed during package installation. this annotation is used for tests in managed or
unmanaged packages. only test methods with this annotation, or methods that are part of 100apex developer guide classes, objects, and interfaces a test class that has this annotation, are executed during package installation. tests annotated to run during package installation must pass in order for the package installation to succeed. it’s no longer possible to bypass a failing test during package installation. a test method or a class that doesn't have this annotation, or that is annotated with @istest(oninstall=false) or @istest, isn’t executed during installation. tests annotated with istest(oninstall=true) that run during package install and upgrade aren’t counted towards code coverage. however, code coverage is tracked and counted during a package creation operation. because apex code installed from a managed package is excluded from org level requirements for code coverage, it’s unlikely that you’re affected. but, if you track managed package test coverage, you must rerun these tests outside of the package install or upgrade operation for code coverage statistics to be updated. package install isn’t blocked by code coverage requirements. this example shows how to annotate a test method that is executed during package installation. in this example, test1 is executed but test2 and test3 isn’t. public class oninstallclass { // implement logic for the class. public void method1(){ // some code } } @istest private class oninstallclasstest { // this test method will be executed // during the installation of the package. @istest(oninstall=true) static void test1() { // some test code } // tests excluded from running during the // the installation of a package. @istest static void test2() { // some test code } @istest static void test3() { // some test code } } @istest(isparallel=true) annotation use the @istest(isparallel=true) annotation to indicate test classes that can run in parallel. default limits on the number of concurrent tests don’t apply to these test classes. this annotation makes the execution of test classes more efficient, because more tests can be run in parallel. considerations for the @istest(isparallel=true) annotation • this annotation overrides settings that disable parallel testing. • @istest(seealldata=true) and @istest(isparallel=true) annotations can’t be used together on the same apex method. 101apex developer guide classes, objects, and interfaces jsonaccess annotation the @jsonaccess annotation defined at apex class level controls whether instances of the class can be serialized or deserialized. if the annotation restricts the json serialization and deserialization, a runtime jsonexception exception is thrown. the serializable and deserializable parameters of the @jsonaccess annotation enforce the contexts in which apex allows serialization and deserialization. you can specify one or both parameters, but you can’t specify the annotation with no parameters. the valid values for the parameters to indicate whether serialization and deserialization are allowed: • never: never allowed • samenamespace: allowed only for apex code in the same namespace • samepackage: allowed only for apex code in the same package (impacts only second-generation packages) • always: always allowed for any apex code jsonaccess considerations • if an apex class annotated with jsonaccess is extended, the extended class doesn’t inherit this property. • if the tostring method is applied on objects that mustn't be serialized, private data can be exposed. you must override the tostring method on objects whose data must be protected. for example, serializing an object stored as a key in a map invokes the tostring method. the generated map includes key (string) and value entries, thus exposing all the fields of the object. this example code shows an apex class marked with the @jsonaccess annotation. // someserializableclass is serializable in the same package and deserializable in the wider namespace @jsonaccess(serializable='samepackage' deserializable=’samenamespace’) public class someserializableclass { } // alwaysdeserializable class is always deserializable and serializable only in the same namespace (default value from version 49.0 onwards) @jsonaccess(deserializable=’always’) public class alwaysdeserializable { } versioned behavior changes in versions 48.0 and earlier, the default access for des
erialization is always and the default access for serialization is samenamespace to preserve the existing behavior. from version 49.0 onwards, the default access for both serialization and deserialization is samenamespace. namespaceaccessible annotation the @namespaceaccessible makes public apex in a package available to other packages that use the same namespace. without this annotation, apex classes, methods, interfaces, properties, and abstract classes defined in a 2gp package aren’t accessible to the other packages with which they share a namespace. apex that is declared global is always available across all namespaces, and needs no annotation. for more information on 2gp managed packages, see second-generation managed packages in salesforce dx developer guide. considerations for apex accessibility across packages • you can't use the @namespaceaccessible annotation for an @auraenabled apex method. 102apex developer guide classes, objects, and interfaces • you can add or remove the @namespaceaccessible annotation at any time, even on managed and released apex code. make sure that you don’t have dependent packages relying on the functionality of the annotation before adding or removing it. • when adding or removing @namespaceaccessible apex from a package, consider the impact to customers with installed versions of other packages that reference this package’s annotation. before pushing a package upgrade, ensure that no customer is running a package version that would fail to fully compile when the upgrade is pushed. • if a public interface is declared as @namespaceaccessible, then all interface members inherit the annotation. individual interface members can’t be annotated with @namespaceaccessible. • if a public or protected variable or method is declared as @namespaceaccessible, its defining class must be either global or public with the @namespaceaccessible annotation. • if a public or protected inner class is declared as @namespaceaccessible, its enclosing class must be either global or public with the @namespaceaccessible annotation. this example shows an apex class marked with the @namespaceaccessible annotation. the class is accessible to other packages within the same namespace. the first constructor is also visible within the namespace, but the second constructor isn’t. // a namespace-visible apex class @namespaceaccessible public class myclass { private boolean bypassfls; // a namespace-visible constructor that only allows secure use @namespaceaccessible public myclass() { bypassfls = false; } // a package private constructor that allows use in trusted contexts, // but only internal to the package public myclass (boolean bypassfls) { this.bypassfls = bypassfls; } @namespaceaccessible protected boolean getbypassfls() { return bypassfls; } } versioned behavior changes in api version 47.0 and later, @namespaceaccessible isn’t allowed on an entity marked with @auraenabled. therefore, an aura or lightning web component installed from a package can’t call an apex method from another package, even if both packages are in the same namespace. in api version 50.0 and later, scope and accessibility rules are enforced on apex variables, methods, inner classes, and interfaces that are annotated with @namespaceaccessible. for accessibility considerations, see considerations for apex acessibility across packages. for more information on namespace-based visibility, see namespace-based visibility for apex classes in second-generation packages. readonly annotation the @readonly annotation allows you to perform less restrictive queries against the lightning platform database by increasing the limit of the number of returned rows for a request to 1,000,000. all other limits still apply. the annotation blocks the following operations within the request: dml operations, calls to system.schedule, and enqueued asynchronous apex jobs. 103apex developer guide classes, objects, and interfaces the @readonly annotation is available for rest and soap web services and the schedulable interface. to use the @readonly annotation, the top-level request must be in the schedule execution or the web service invocation. for example, if a visualforce page calls a web service that contains the @readonly annotation, the request fails because visualforce is the top-level request, not the web service. visualforce pages can call controller methods with the @readonly annotation, and those methods run with the same relaxed restrictions. to increase other visualforce-specific limits, such as the size of a collection that can be used by an iteration component like <apex:pageblocktable>, you
can set the readonly attribute on the <apex:page> tag to true. for more information, see working with large sets of data in the visualforce developer's guide. versioned behavior changes prior to api version 49.0, using @readonly on apex rest methods (@httpdelete, @httpget, @httppatch, @httppost, or @httpput) also required annotating the method with @remoteaction. in api version 49.0 and later, you can annotate apex rest methods with just @readonly. remoteaction annotation the remoteaction annotation provides support for apex methods used in visualforce to be called via javascript. this process is often referred to as javascript remoting. note: methods with the remoteaction annotation must be static and either global or public. add the apex class as a custom controller or a controller extension to your page. <apex:page controller="mycontroller" extension="myextension"> warning: adding a controller or controller extension grants access to all @remoteaction methods in that apex class, even if those methods aren’t used in the page. anyone who can view the page can execute all @remoteaction methods and provide fake or malicious data to the controller. then, add the request as a javascript function call. a simple javascript remoting invocation takes the following form. [namespace.]mycontroller.method( [parameters...,] callbackfunction, [configuration] ); table 2: remote request elements element description namespace the namespace of the controller class. the namespace element is required if your organization has a namespace defined, or if the class comes from an installed package. mycontroller, the name of your apex controller or extension. myextension method the name of the apex method you’re calling. parameters a comma-separated list of parameters that your method takes. 104apex developer guide classes, objects, and interfaces element description callbackfunction the name of the javascript function that handles the response from the controller. you can also declare an anonymous function inline. callbackfunction receives the status of the method call and the result as parameters. configuration configures the handling of the remote call and response. use this element to change the behavior of a remoting call, such as whether to escape the apex method’s response. in your controller, your apex method declaration is preceded with the @remoteaction annotation like this: @remoteaction global static string getitemid(string objectname) { ... } apex @remoteaction methods must be static and either global or public. your method can take apex primitives, collections, typed and generic sobjects, and user-defined apex classes and interfaces as arguments. generic sobjects must have an id or sobjecttype value to identify actual type. interface parameters must have an apextype to identify actual type. your method can return apex primitives, sobjects, collections, user-defined apex classes and enums, saveresult, upsertresult, deleteresult, selectoption, or pagereference. for more information, see “javascript remoting for apex controllers” in the visualforce developer's guide. suppresswarnings annotation this annotation does nothing in apex but can be used to provide information to third-party tools. the @suppresswarnings annotation does nothing in apex but can be used to provide information to third-party tools. testsetup annotation methods defined with the @testsetup annotation are used for creating common test records that are available for all test methods in the class. syntax test setup methods are defined in a test class, take no arguments, and return no value. the following is the syntax of a test setup method. @testsetup static void methodname() { } if a test class contains a test setup method, the testing framework executes the test setup method first, before any test method in the class. records that are created in a test setup method are available to all test methods in the test class and are rolled back at the end of test class execution. if a test method changes those records, such as record field updates or record deletions, those changes are rolled back after each test method finishes execution. the next executing test method gets access to the original unmodified state of those records. note: you can have only one test setup method per test class. test setup methods are supported only with the default data isolation mode for a test class. if the test class or a test method has access to organization data by using the @istest(seealldata=true) annotation, test setup methods aren’t supported in this class. because data isolation for tests is available for
api versions 24.0 and later, test setup methods are also available for those versions only. 105apex developer guide classes, objects, and interfaces for more information, see using test setup methods. testvisible annotation use the testvisible annotation to allow test methods to access private or protected members of another class outside the test class. these members include methods, member variables, and inner classes. this annotation enables a more permissive access level for running tests only. this annotation doesn’t change the visibility of members if accessed by non-test classes. with this annotation, you don’t have to change the access modifiers of your methods and member variables to public if you want to access them in a test method. for example, if a private member variable isn’t supposed to be exposed to external classes but it must be accessible by a test method, you can add the testvisible annotation to the variable definition. this example shows how to annotate a private class member variable and private method with testvisible. public class testvisibleexample { // private member variable @testvisible private static integer recordnumber = 1; // private method @testvisible private static void updaterecord(string name) { // do something } } this test class uses the previous class and contains the test method that accesses the annotated member variable and method. @istest private class testvisibleexampletest { @istest static void test1() { // access private variable annotated with testvisible integer i = testvisibleexample.recordnumber; system.assertequals(1, i); // access private method annotated with testvisible testvisibleexample.updaterecord('recordname'); // perform some verification } } apex rest annotations use these annotations to expose an apex class as a restful web service. • @readonly • @restresource(urlmapping='/yoururl') • @httpdelete • @httpget • @httppatch • @httppost • @httpput 106apex developer guide classes, objects, and interfaces restresource annotation the @restresource annotation is used at the class level and enables you to expose an apex class as a rest resource. some considerations when using this annotation: • the url mapping is relative to https://instance.salesforce.com/services/apexrest/. • the url mapping can contain a wildcard (*). • the url mapping is case-sensitive. for example, a url mapping for my_url matches a rest resource containing my_url and not my_url. • to use this annotation, your apex class must be defined as global. url guidelines url path mappings are as follows: • the path must begin with a forward slash (/). • the path can be up to 255 characters long. • a wildcard (*) that appears in a path must be preceded by a forward slash (/). additionally, unless the wildcard is the last character in the path, it must be followed by a forward slash (/). the rules for mapping urls are: • an exact match always wins. • if no exact match is found, find all the patterns with wildcards that match, and then select the longest (by string length) of those. • if no wildcard match is found, an http response status code 404 is returned. the url for a namespaced class contains the namespace. for example, if your class is in namespace abc and the class is mapped to your_url, then the api url is modified as follows: https://instance.salesforce.com/services/apexrest/abc/your_url/. in the case of a url collision, the namespaced class is always used. httpdelete annotation the @httpdelete annotation is used at the method level and enables you to expose an apex method as a rest resource. this method is called when an http delete request is sent, and deletes the specified resource. to use this annotation, your apex method must be defined as global static. httpget annotation the @httpget annotation is used at the method level and enables you to expose an apex method as a rest resource. this method is called when an http get request is sent, and returns the specified resource. these are some considerations when using this annotation: • to use this annotation, your apex method must be defined as global static. • methods annotated with @httpget are also called if the http request uses the head request method. httppatch annotation the @httppatch annotation is used at the method level and enables you to expose an apex method as a rest resource. this method is called when
an http patch request is sent, and updates the specified resource. to use this annotation, your apex method must be defined as global static. 107apex developer guide classes, objects, and interfaces httppost annotation the @httppost annotation is used at the method level and enables you to expose an apex method as a rest resource. this method is called when an http post request is sent, and creates a new resource. to use this annotation, your apex method must be defined as global static. httpput annotation the @httpput annotation is used at the method level and enables you to expose an apex method as a rest resource. this method is called when an http put request is sent, and creates or updates the specified resource. to use this annotation, your apex method must be defined as global static. classes and casting in general, all type information is available at run time. this means that apex enables casting, that is, a data type of one class can be assigned to a data type of another class, but only if one class is a subclass of the other class. use casting when you want to convert an object from one data type to another. in the following example, customreport extends the class report. therefore, it is a subclass of that class. this means that you can use casting to assign objects with the parent data type (report) to the objects of the subclass data type (customreport). public virtual class report { } public class customreport extends report { } in the following code segment, a custom report object is first added to a list of report objects. then the custom report object is returned as a report object, which is then cast back into a custom report object. ... // create a list of report objects report[] reports = new report[5]; // create a custom report object customreport a = new customreport(); // because the custom report is a sub class of the report class, // you can add the custom report object a to the list of report objects reports.add(a); // the following is not legal: // customreport c = reports.get(0); // because the compiler does not know that what you are // returning is a custom report. // you must use cast to tell it that you know what // type you are returning. instead, get the first item in the list // by casting it back to a custom report object customreport c = (customreport) reports.get(0); ... 108apex developer guide classes, objects, and interfaces casting example in addition, an interface type can be cast to a sub-interface or a class type that implements that interface. tip: to verify if a class is a specific type of class, use the instanceof keyword. for more information, see using the instanceof keyword on page 82. in this section: 1. classes and collections 2. collection casting classes and collections lists and maps can be used with classes and interfaces, in the same ways that lists and maps can be used with sobjects. this means, for example, that you can use a user-defined data type for the value or the key of a map. likewise, you can create a set of user-defined objects. if you create a map or list of interfaces, any child type of the interface can be put into that collection. for instance, if the list contains an interface i1, and myc implements i1, then myc can be placed in the list. see also: using custom types in map keys and sets 109apex developer guide classes, objects, and interfaces collection casting because collections in apex have a declared type at runtime, apex allows collection casting. collections can be cast in a similar manner that arrays can be cast in java. for example, a list of customerpurchaseorder objects can be assigned to a list of purchaseorder objects if class customerpurchaseorder is a child of class purchaseorder. public virtual class purchaseorder { public class customerpurchaseorder extends purchaseorder { } { list<purchaseorder> pos = new purchaseorder[] {}; list<customerpurchaseorder> cpos = new customerpurchaseorder[]{}; pos = cpos; } } once the customerpurchaseorder list is assigned to the purchaseorder list variable, it can be cast back to a list of customerpurchaseorder objects, but only because that instance was originally instantiated as a list of customerpurchaseorder objects. a list of purchaseorder objects that is instantiated as such cannot be cast to a list of customerpurchaseorder objects, even if the list of purchaseorder objects contains only customerpurchaseorder objects. if the user
of a purchaseorder list that only includes customerpurchaseorders objects tries to insert a non-customerpurchaseorder subclass of purchaseorder (such as internalpurchaseorder), a runtime exception results. this is because apex collections have a declared type at runtime. note: maps behave in the same way as lists with regards to the value side of the map. if the value side of map a can be cast to the value side of map b, and they have the same key type, then map a can be cast to map b. a runtime error results if the casting is not valid with the particular map at runtime. differences between apex classes and java classes apex classes and java classes work in similar ways, but there are some significant differences. these are the major differences between apex classes and java classes: • inner classes and interfaces can only be declared one level deep inside an outer class. • static methods and variables can only be declared in a top-level class definition, not in an inner class. • an inner class behaves like a static java inner class, but doesn’t require the static keyword. an inner class can have instance member variables like an outer class, but there is no implicit pointer to an instance of the outer class (using the this keyword). • the private access modifier is the default, and means that the method or variable is accessible only within the apex class in which it is defined. if you do not specify an access modifier, the method or variable is private. • specifying no access modifier for a method or variable and the private access modifier are synonymous. • the public access modifier means the method or variable can be used by any apex in this application or namespace. • the global access modifier means the method or variable can be used by any apex code that has access to the class, not just the apex code in the same application. this access modifier should be used for any method that needs to be referenced outside of the application, either in the soap api or by other apex code. if you declare a method or variable as global, you must also declare the class that contains it as global. • methods and classes are final by default. – the virtual definition modifier allows extension and overrides. 110apex developer guide classes, objects, and interfaces – the override keyword must be used explicitly on methods that override base class methods. • interface methods have no modifiers—they are always global. • exception classes must extend either exception or another user-defined exception. – their names must end with the word exception. – exception classes have four implicit constructors that are built-in, although you can add others. • classes and interfaces can be defined in triggers and anonymous blocks, but only as local. see also: exceptions in apex class definition creation use the class editor to create a class in salesforce. 1. from setup, enter apex classes in the quick find box, then select apex classes. 2. click new. 3. click version settings to specify the version of apex and the api used with this class. if your organization has installed managed packages from the appexchange, you can also specify which version of each managed package to use with this class. use the default values for all versions. this associates the class with the most recent version of apex and the api, as well as each managed package. you can specify an older version of a managed package if you want to access components or functionality that differs from the most recent package version. you can specify an older version of apex and the api to maintain specific behavior. 4. in the class editor, enter the apex code for the class. a single class can be up to 1 million characters in length, not including comments, test methods, or classes defined using @istest. 5. click save to save your changes and return to the class detail screen, or click quick save to save your changes and continue editing your class. your apex class must compile correctly before you can save your class. classes can also be automatically generated from a wsdl by clicking generate from wsdl. see soap services: defining a class from a wsdl document on page 534. once saved, classes can be invoked through class methods or variables by other apex code, such as a trigger. note: to aid backwards-compatibility, classes are stored with the version settings for a specified version of apex and the api. if the apex class references components, such as a custom object, in installed managed packages, the version settings for each managed package referenced by the class is saved too. additionally, classes are stored with an isvalid flag that is set to true as long as dependent metadata hasn’t changed since the class was last compiled. if any changes are made to object names or fields that are
used in the class, including superficial changes such as edits to an object or field description, or if changes are made to a class that calls this class, the isvalid flag is set to false. when a trigger or web service call invokes the class, the code is recompiled and the user is notified if there are any errors. if there are no errors, the isvalid flag is reset to true. the apex class editor the apex and visualforce editor has the following functionality: syntax highlighting the editor automatically applies syntax highlighting for keywords and all functions and operators. search ( ) search enables you to search for text within the current page, class, or trigger. to use search, enter a string in the search textbox and click find next. 111apex developer guide classes, objects, and interfaces • to replace a found search string with another string, enter the new string in the replace textbox and click replace to replace just that instance, or replace all to replace that instance and all other instances of the search string that occur in the page, class, or trigger. • to make the search operation case sensitive, select the match case option. • to use a regular expression as your search string, select the regular expressions option. the regular expressions follow javascript's regular expression rules. a search using regular expressions can find strings that wrap over more than one line. if you use the replace operation with a string found by a regular expression, the replace operation can also bind regular expression group variables ($1, $2, and so on) from the found search string. for example, to replace an <h1> tag with an <h2> tag and keep all the attributes on the original <h1> intact, search for <h1(\s+)(.*)> and replace it with <h2$1$2>. go to line ( ) this button allows you to highlight a specified line number. if the line isn’t currently visible, the editor scrolls to that line. undo ( ) and redo ( ) use undo to reverse an editing action and redo to recreate an editing action that was undone. font size select a font size from the dropdown list to control the size of the characters displayed in the editor. line and column position the line and column position of the cursor is displayed in the status bar at the bottom of the editor. this can be used with go to line ( ) to quickly navigate through the editor. line and character count the total number of lines and characters is displayed in the status bar at the bottom of the editor. in this section: 1. naming conventions 2. name shadowing naming conventions we recommend following java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful. it is not legal to define a class and interface with the same name in the same class. it is also not legal for an inner class to have the same name as its outer class. however, methods and variables have their own namespaces within the class so these three types of names do not clash with each other. in particular it is legal for a variable, method, and a class within a class to have the same name. name shadowing member variables can be shadowed by local variables—in particular function arguments. this allows methods and constructors of the standard java form: public class shadow { string s; shadow(string s) { this.s = s; } // same name ok sets(string s) { this.s = s; } // same name ok } member variables in one class can shadow member variables with the same name in a parent classes. this can be useful if the two classes are in different top-level classes and written by different teams. for example, if one has a reference to a class c and wants to gain access 112apex developer guide classes, objects, and interfaces to a member variable m in parent class p (with the same name as a member variable in c) the reference should be assigned to a reference to p first. static variables can be shadowed across the class hierarchy—so if p defines a static s, a subclass c can also declare a static s. references to s inside c refer to that static—in order to reference the one in p, the syntax p.s must be used. static class variables cannot be referenced through a class instance. they must be referenced using the raw variable name by itself (inside that top-level class file) or prefixed with the class name. for example: public class p1 { public static final integer class_int = 1; public class c { }; } p1.c
c = new p1.c(); // this is illegal // integer i = c.class_int; // this is correct integer i = p1.class_int; namespace prefix the salesforce application supports the use of namespace prefixes. namespace prefixes are used in managed appexchange packages to differentiate custom object and field names from names used by other organizations. important: when creating a namespace, use something that’s useful and informative to users. however, don’t name a namespace after a person (for example, by using a person's name, nickname, or private information). once namespaces are assigned, they cannot be changed. after a developer registers a globally unique namespace prefix and registers it with appexchange registry, external references to custom object and field names in the developer's managed packages take on the following long format: namespace_prefix__obj_or_field_name__c these fully qualified names can be onerous to update in working soql or sosl statements, and apex once a class is marked as “managed”. therefore, apex supports a default namespace for schema names. when looking at identifiers, the parser assumes that the namespace of the current object is the namespace of all other objects and fields unless otherwise specified. therefore, a stored class must refer to custom object and field names directly (using obj_or_field_name__c) for those objects that are defined within its same application namespace. tip: only use namespace prefixes when referring to custom objects and fields in managed packages that have been installed to your organization from the appexchange. using namespaces when invoking package methods to invoke a method that is defined in a managed package, apex allows fully qualified identifiers of the form: namespace_prefix.class.method(args) versioned behavior changes in api version 34.0 and later, schema.describesobjectresult on a custom sobjecttype includes map keys prefixed with the namespace, even if the namespace is that of currently executing code. if you work with multiple namespaces and generate runtime describe data, make sure that your code accesses keys correctly using the namespace prefix. 113apex developer guide classes, objects, and interfaces in this section: 1. using the system namespace 2. using the schema namespace the schema namespace provides classes and methods for working with schema metadata information. we implicitly import schema.*, but you must fully qualify your uses of schema namespace elements when they have naming conflicts with items in your unmanaged code. if your org contains an apex class that has the same name as an sobject, add the schema namespace prefix to the sobject name in your code. 3. namespace, class, and variable name precedence 4. type resolution and system namespace for types using the system namespace the system namespace is the default namespace in apex. this means that you can omit the namespace when creating a new instance of a system class or when calling a system method. for example, because the built-in url class is in the system namespace, both of these statements to create an instance of the url class are equivalent: system.url url1 = new system.url('https://mydomainname.my.salesforce.com/'); and: url url1 = new url('https://mydomainname.my.salesforce.com/'); similarly, to call a static method on the url class, you can write either of the following: system.url.getcurrentrequesturl(); or: url.getcurrentrequesturl(); note: in addition to the system namespace, there is a built-in system class in the system namespace, which provides methods like assertequals and debug. don’t get confused by the fact that both the namespace and the class have the same name in this case. the system.debug('debug message'); and system.system.debug('debug message'); statements are equivalent. using the system namespace for disambiguation it is easier to not include the system namespace when calling static methods of system classes, but there are situations where you must include the system namespace to differentiate the built-in apex classes from custom apex classes with the same name. if your organization contains apex classes that you’ve defined with the same name as a built-in class, the apex runtime defaults to your custom class and calls the methods in your class. let’s take a look at the following example. create this custom apex class: public class database { public static string query() { return 'wherefore art thou namespace?'; } } 114apex developer guide classes,
objects, and interfaces execute this statement in the developer console: sobject[] acct = database.query('select name from account limit 1'); system.debug(acct[0].get('name')); when the database.query statement executes, apex looks up the query method on the custom database class first. however, the query method in this class doesn’t take any parameters and no match is found, hence you get an error. the custom database class overrides the built-in database class in the system namespace. to solve this problem, add the system namespace prefix to the class name to explicitly instruct the apex runtime to call the query method on the built-in database class in the system namespace: sobject[] acct = system.database.query('select name from account limit 1'); system.debug(acct[0].get('name')); see also: using the schema namespace using the schema namespace the schema namespace provides classes and methods for working with schema metadata information. we implicitly import schema.*, but you must fully qualify your uses of schema namespace elements when they have naming conflicts with items in your unmanaged code. if your org contains an apex class that has the same name as an sobject, add the schema namespace prefix to the sobject name in your code. you can omit the namespace when creating an instance of a schema class or when calling a schema method. for example, because the describesobjectresult and fieldset classes are in the schema namespace, these code segments are equivalent. schema.describesobjectresult d = account.sobjecttype.getdescribe(); map<string, schema.fieldset> fsmap = d.fieldsets.getmap(); and: describesobjectresult d = account.sobjecttype.getdescribe(); map<string, fieldset> fsmap = d.fieldsets.getmap(); using the schema namespace for disambiguation use schema.object_name to refer to an sobject that has the same name as a custom class. this disambiguation instructs the apex runtime to use the sobject. public class account { public integer myinteger; } // ... // create a standard account object myaccountsobject schema.account myaccountsobject = new schema.account(); // create accountclassinstance, a custom class in your org account accountclassinstance = new account(); 115apex developer guide classes, objects, and interfaces myaccountsobject.name = 'snazzy account'; accountclassinstance.myinteger = 1; see also: using the system namespace namespace, class, and variable name precedence because local variables, class names, and namespaces can all hypothetically use the same identifiers, the apex parser evaluates expressions in the form of name1.name2.[...].namen as follows: 1. the parser first assumes that name1 is a local variable with name2 - namen as field references. 2. if the first assumption does not hold true, the parser then assumes that name1 is a class name and name2 is a static variable name with name3 - namen as field references. 3. if the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class name, name3 is a static variable name, and name4 - namen are field references. 4. if the third assumption does not hold true, the parser reports an error. if the expression ends with a set of parentheses (for example, name1.name2.[...].namem.namen()), the apex parser evaluates the expression as follows: 1. the parser first assumes that name1 is a local variable with name2 - namem as field references, and namen as a method invocation. 2. if the first assumption does not hold true: • if the expression contains only two identifiers (name1.name2()), the parser then assumes that name1 is a class name and name2 is a method invocation. • if the expression contains more than two identifiers, the parser then assumes that name1 is a class name, name2 is a static variable name with name3 - namem as field references, and namen is a method invocation. 3. if the second assumption does not hold true, the parser then assumes that name1 is a namespace name, name2 is a class name, name3 is a static variable name, name4 - namem are field references, and namen is a method invocation. 4. if the third assumption does not hold true
, the parser reports an error. however, with class variables apex also uses dot notation to reference member variables. those member variables might refer to other class instances, or they might refer to an sobject which has its own dot notation rules to refer to field names (possibly navigating foreign keys). once you enter an sobject field in the expression, the remainder of the expression stays within the sobject domain, that is, sobject fields cannot refer back to apex expressions. for instance, if you have the following class: public class c { c1 c1 = new c1(); class c1 { c2 c2; } class c2 { account a; } } then the following expressions are all legal: c.c1.c2.a.name c.c1.c2.a.owner.lastname.tolowercase() 116apex developer guide classes, objects, and interfaces c.c1.c2.a.tasks c.c1.c2.a.contacts.size() type resolution and system namespace for types because the type system must resolve user-defined types defined locally or in other classes, the apex parser evaluates types as follows: 1. for a type reference typen, the parser first looks up that type as a scalar type. 2. if typen is not found, the parser looks up locally defined types. 3. if typen still is not found, the parser looks up a class of that name. 4. if typen still is not found, the parser looks up system types such as sobjects. for the type t1.t2 this could mean an inner type t2 in a top-level class t1, or it could mean a top-level class t2 in the namespace t1 (in that order of precedence). apex code versions to aid backwards-compatibility, classes and triggers are stored with the version settings for a specific salesforce api version. if an apex class or trigger references components, such as a custom object, in installed managed packages, the version settings for each managed package referenced by the class are saved too. this ensures that as apex, the api, and the components in managed packages evolve in subsequent released versions, a class or trigger is still bound to versions with specific, known behavior. setting a version for an installed package determines the exposed interface and behavior of any apex code in the installed package. this allows you to continue to reference apex that may be deprecated in the latest version of an installed package, if you installed a version of the package before the code was deprecated. typically, you reference the latest salesforce api version and each installed package version. if you save an apex class or trigger without specifying the salesforce api version, the class or trigger is associated with the latest installed version by default. if you save an apex class or trigger that references a managed package without specifying a version of the managed package, the class or trigger is associated with the latest installed version of the managed package by default. versioning of apex classes and methods when classes and methods are added to the apex language, those classes and methods are available to all api versions your apex code is saved with, regardless of the api version (salesforce release) they were introduced in. for example, if a method was added in api version 33.0, you can use this method in a custom class saved with api version 33.0 or another class saved with api version 25.0. there is one exception to this rule. the classes and methods of the connectapi namespace are supported only in the api versions specified in the documentation. for example, if a class or method is introduced in api version 33.0, it is not available in earlier versions. for more information, see connectapi versioning and equality checking on page 407. in this section: 1. setting the salesforce api version for classes and triggers 2. setting package versions for apex classes and triggers setting the salesforce api version for classes and triggers to set the salesforce api and apex version for a class or trigger: 1. edit either a class or trigger, and click version settings. 117apex developer guide classes, objects, and interfaces 2. select the version of the salesforce api. this version is also the version of apex associated with the class or trigger. 3. click save. if you pass an object as a parameter in a method call from one apex class, c1, to another class, c2, and c2 has different fields exposed due to the salesforce api version setting, the fields in the objects are controlled by the version settings of c2. in this example, the categories field is set to
null after calling the insertidea method in class c2 from a method in the test class c1, because the categories field isn’t available in version 13.0 of the api. the first class is saved using salesforce api version 13.0: // this class is saved using salesforce api version 13.0 // version 13.0 does not include the idea.categories field global class c2 { global idea insertidea(idea a) { insert a; // category field set to null on insert // retrieve the new idea idea insertedidea = [select title from idea where id =:a.id]; return insertedidea; } } the following class is saved using salesforce api version 16.0: @istest // this class is bound to api version 16.0 by version settings private class c1 { static testmethod void testc2method() { idea i = new idea(); i.communityid = '09ad000000004yciay'; i.title = 'testing version settings'; i.body = 'categories field is included in api version 16.0'; i.categories = 'test'; c2 c2 = new c2(); idea returnedidea = c2.insertidea(i); // retrieve the new idea idea ideamorefields = [select title, categories from idea where id = :returnedidea.id]; // assert that the categories field from the object created // in this class is not null system.assert(i.categories != null); // assert that the categories field created in c2 is null system.assert(ideamorefields.categories == null); } } setting package versions for apex classes and triggers to configure the package version settings for a class or trigger: 118apex developer guide classes, objects, and interfaces 1. edit either a class or trigger, and click version settings. 2. select a version for each managed package referenced by the class or trigger. this version of the managed package will continue to be used by the class or trigger if later versions of the managed package are installed, unless you manually update the version setting. to add an installed managed package to the settings list, select a package from the list of available packages. the list is only displayed if you have an installed managed package that is not already associated with the class or trigger. 3. click save. note the following when working with package version settings: • if you save an apex class or trigger that references a managed package without specifying a version of the managed package, the apex class or trigger is associated with the latest installed version of the managed package by default. • you cannot remove a class or trigger's version setting for a managed package if the package is referenced in the class or trigger. use show dependencies to find where a managed package is referenced by a class or trigger. lists of custom types and sorting lists can hold objects of your user-defined types (your apex classes). lists of user-defined types can be sorted. to sort such a list using the list.sort method, your apex classes must implement the comparable interface. the sort criteria and sort order depends on the implementation that you provide for the compareto method of the comparable interface. for more information on implementing the comparable interface for your own classes, see the comparable interface. using custom types in map keys and sets you can add instances of your own apex classes to maps and sets. for maps, instances of your apex classes can be added either as keys or values. if you add them as keys, there are some special rules that your class must implement for the map to function correctly; that is, for the key to fetch the right value. similarly, if set elements are instances of your custom class, your class must follow those same rules. warning: if the object in your map keys or set elements changes after being added to the collection, it won’t be found anymore because of changed field values. when using a custom type (your apex class) for the map key or set elements, provide equals and hashcode methods in your class. apex uses these two methods to determine equality and uniqueness of keys for your objects. adding equals and hashcode methods to your class to ensure that map keys of your custom type are compared correctly and their uniqueness can be determined consistently, provide an implementation of the following two methods in your class: • the equals method with this signature: public boolean equals(object obj) { // your implementation } keep in mind the following when implementing the equals method. assuming x, y, and
z are non-null instances of your class, the equals method must be: – reflexive: x.equals(x) – symmetric: x.equals(y) should return true if and only if y.equals(x) returns true – transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true 119apex developer guide classes, objects, and interfaces – consistent: multiple invocations of x.equals(y) consistently return true or consistently return false – for any non-null reference value x, x.equals(null) should return false the equals method in apex is based on the equals method in java. • the hashcode method with this signature: public integer hashcode() { // your implementation } keep in mind the following when implementing the hashcode method. – if the hashcode method is invoked on the same object more than once during execution of an apex request, it must return the same value. – if two objects are equal, based on the equals method, hashcode must return the same value. – if two objects are unequal, based on the result of the equals method, it is not required that hashcode return distinct values. the hashcode method in apex is based on the hashcode method in java. another benefit of providing the equals method in your class is that it simplifies comparing your objects. you will be able to use the == operator to compare objects, or the equals method. for example: // obj1 and obj2 are instances of myclass if (obj1 == obj2) { // do something } if (obj1.equals(obj2)) { // do something } sample this sample shows how to implement the equals and hashcode methods. the class that provides those methods is listed first. it also contains a constructor that takes two integers. the second example is a code snippet that creates three objects of the class, two of which have the same values. next, map entries are added using the pair objects as keys. the sample verifies that the map has only two entries since the entry that was added last has the same key as the first entry, and hence, overwrote it. the sample then uses the == operator, which works as expected because the class implements equals. also, some additional map operations are performed, like checking whether the map contains certain keys, and writing all keys and values to the debug log. finally, the sample creates a set and adds the same objects to it. it verifies that the set size is two, since only two objects out of the three are unique. public class pairnumbers { integer x,y; public pairnumbers(integer a, integer b) { x=a; y=b; } public boolean equals(object obj) { if (obj instanceof pairnumbers) { pairnumbers p = (pairnumbers)obj; return ((x==p.x) && (y==p.y)); } 120apex developer guide classes, objects, and interfaces return false; } public integer hashcode() { return (31 * x) ^ y; } } this code snippet makes use of the pairnumbers class. map<pairnumbers, string> m = new map<pairnumbers, string>(); pairnumbers p1 = new pairnumbers(1,2); pairnumbers p2 = new pairnumbers(3,4); // duplicate key pairnumbers p3 = new pairnumbers(1,2); m.put(p1, 'first'); m.put(p2, 'second'); m.put(p3, 'third'); // map size is 2 because the entry with // the duplicate key overwrote the first entry. system.assertequals(2, m.size()); // use the == operator if (p1 == p3) { system.debug('p1 and p3 are equal.'); } // perform some other operations system.assertequals(true, m.containskey(p1)); system.assertequals(true, m.containskey(p2)); system.assertequals(false, m.containskey(new pairnumbers(5,6))); for(pairnumbers pn : m.keyset()) { system.debug('key: ' + pn); } list<string> mvalues = m.values(); system.debug('m.values: ' + mvalues); // create a set
set<pairnumbers> s1 = new set<pairnumbers>(); s1.add(p1); s1.add(p2); s1.add(p3); // verify that we have only two elements // since the p3 is equal to p1. system.assertequals(2, s1.size()); 121apex developer guide working with data in apex working with data in apex you can add and interact with data in the lightning platform persistence layer. the sobject data type is the main data type that holds data objects. you’ll use data manipulation language (dml) to work with data, and use query languages to retrieve data, such as the (), among other things. in this section: working with sobjects in this developer guide, the term sobject refers to any object that can be stored in the lightning platform database. data manipulation language apex enables you to insert, update, delete or restore data in the database. dml operations allow you to modify records one at a time or in batches. soql and sosl queries you can evaluate salesforce object query language (soql) or salesforce object search language (sosl) statements on-the-fly in apex by surrounding the statement in square brackets. soql for loops soql for loops iterate over all of the sobject records returned by a soql query. sobject collections you can manage sobjects in lists, sets, and maps. dynamic apex apex security and sharing when you use apex, the security of your code is critical. you'll need to add user permissions for apex classes and enforce sharing rules. read on to learn about apex managed sharing and get some security tips. custom settings custom settings are similar to custom objects. application developers can create custom sets of data and associate custom data for an organization, profile, or specific user. all custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database. formula fields, validation rules, flows, apex, and soap api can then use this data. working with sobjects in this developer guide, the term sobject refers to any object that can be stored in the lightning platform database. in this section: sobject types an sobject variable represents a row of data and can only be declared in apex using soap api name of the object. accessing sobject fields validating sobjects and fields sobject types an sobject variable represents a row of data and can only be declared in apex using soap api name of the object. 122apex developer guide working with data in apex for example: account a = new account(); mycustomobject__c co = new mycustomobject__c(); similar to soap api, apex allows the use of the generic sobject abstract type to represent any object. the sobject data type can be used in code that processes different types of sobjects. the new operator still requires a concrete sobject type, so all instances are specific sobjects. for example: sobject s = new account(); you can also use casting between the generic sobject type and the specific sobject type. for example: // cast the generic variable s from the example above // into a specific account and account variable a account a = (account)s; // the following generates a runtime error contact c = (contact)s; because sobjects work like objects, you can also have the following: object obj = s; // and a = (account)obj; dml operations work on variables declared as the generic sobject data type as well as with regular sobjects. sobject variables are initialized to null, but can be assigned a valid object reference with the new operator. for example: account a = new account(); developers can also specify initial field values with comma-separated name = value pairs when instantiating a new sobject. for example: account a = new account(name = 'acme', billingcity = 'san francisco'); for information on accessing existing sobjects from the lightning platform database, see “soql and sosl queries” in the soql and sosl reference. note: the lightning platform assigns id values automatically when an object record is initially inserted to the database for the first time. for more information see lists on page 28. custom labels custom labels aren’t standard sobjects. you can’t create a new instance of a custom label. you can only access the value of a custom label using system.label.label_name. for example:
string errormsg = system.label.generic_error; for more information on custom labels, see “custom labels” in salesforce help. accessing sobject fields as in java, sobject fields can be accessed or changed with simple dot notation. for example: account a = new account(); a.name = 'acme'; // access the account name field and assign it 'acme' 123apex developer guide working with data in apex system-generated fields, such as created by or last modified date, cannot be modified. if you try, the apex runtime engine generates an error. additionally, formula field values and values for other fields that are read-only for the context user cannot be changed. if you use the generic sobject type instead of a specific object, such as account, you can retrieve only the id field using dot notation. you can set the id field for apex code saved using salesforce api version 27.0 and later). alternatively, you can use the generic sobject put and get methods. see sobject class. this example shows how you can access the id field and operations that aren’t allowed on generic sobjects. account a = new account(name = 'acme', billingcity = 'san francisco'); insert a; sobject s = [select id, name from account where name = 'acme' limit 1]; // this is allowed id id = s.id; // the following line results in an error when you try to save string x = s.name; // this line results in an error when you try to save using api version 26.0 or earlier s.id = [select id from account where name = 'acme' limit 1].id; note: if your organization has enabled person accounts, you have two different kinds of accounts: business accounts and person accounts. if your code creates a new account using name, a business account is created. if your code uses lastname, a person account is created. if you want to perform operations on an sobject, it is recommended that you first convert it into a specific object. for example: account a = new account(name = 'acme', billingcity = 'san francisco'); insert a; sobject s = [select id, name from account where name = 'acme' limit 1]; id id = s.id; account convertedaccount = (account)s; convertedaccount.name = 'acme2'; update convertedaccount; contact sal = new contact(firstname = 'sal', account = convertedaccount); the following example shows how you can use sosl over a set of records to determine their object types. once you have converted the generic sobject record into a contact, lead, or account, you can modify its fields accordingly: public class converttocla { list<contact> contacts = new list<contact>(); list<lead> leads = new list<lead>(); list<account> accounts = new list<account>(); public void converttype(string phonenumber) { list<list<sobject>> results = [find :phonenumber in phone fields returning contact(id, phone, firstname, lastname), lead(id, phone, firstname, lastname), account(id, phone, name)]; list<sobject> records = new list<sobject>(); records.addall(results[0]); //add contact results to our results super-set records.addall(results[1]); //add lead results records.addall(results[2]); //add account results if (!records.isempty()) { for (integer i = 0; i < records.size(); i++) { 124apex developer guide working with data in apex sobject record = records[i]; if (record.getsobjecttype() == contact.sobjecttype) { contacts.add((contact) record); } else if (record.getsobjecttype() == lead.sobjecttype){ leads.add((lead) record); } else if (record.getsobjecttype() == account.sobjecttype) { accounts.add((account) record); } } } } } using sobject fields sobject fields can be initially set or not set (unset); unset fields are not the same as null or blank fields. when you perform a dml operation on an sobject, you can change a field that is set; you can’t change unset fields. note: to erase the current value of a field, set the
field to null. if an apex method takes an sobject parameter, you can use the system.isset() method to identify the set fields. if you want to unset any fields to retain their values, first create an sobject instance. then apply only the fields you want to be part of the dml operation. this example code shows how sobject fields are identified as set or unset. contact nullfirst = new contact(lastname='codey', firstname=null); system.assertequals(true, nullfirst.isset('firstname'), 'firstname is set to a literal value, so it counts as set'); contact unsetfirst = new contact(lastname='astro'); system.assertequals(false, unsetfirst.isset('firstname'), ‘firstname is not set’); an expression with sobject fields of type boolean evaluates to true only if the sobject field is true. if the field is false or null, the expression evaluates to false. this example code shows an expression that checks if the isactive field of a campaign object is null. because this expression always evaluates to false, the code in the if statement is never executed. campaign cobj= new campaign(); ... if (cobj.isactive == null) { ... // isactive is evaluated to false and this code block is not executed. } validating sobjects and fields when apex code is parsed and validated, all sobject and field references are validated against actual object and field names, and a parse-time exception is thrown when an invalid name is used. in addition, the apex parser tracks the custom objects and fields that are used, both in the code's syntax as well as in embedded soql and sosl statements. the platform prevents users from making the following types of modifications when those changes cause apex code to become invalid: • changing a field or object name • converting from one data type to another • deleting a field or object • making certain organization-wide changes, such as record sharing, field history tracking, or record types 125apex developer guide working with data in apex data manipulation language apex enables you to insert, update, delete or restore data in the database. dml operations allow you to modify records one at a time or in batches. in this section: how dml works adding and retrieving data with dml apex is tightly integrated with the lightning platform persistence layer. records in the database can be inserted and manipulated through apex directly using simple statements. the language in apex that allows you to add and manage records in the database is the data manipulation language (dml). in contrast to the soql language, which is used for read operations (querying records), dml is used for write operations. dml statements vs. database class methods apex offers two ways to perform dml operations: using dml statements or database class methods. this provides flexibility in how you perform data operations. dml statements are more straightforward to use and result in exceptions that you can handle in your code. dml operations as atomic transactions dml operations using dml, you can insert new records and commit them to the database. you can also update the field values of existing records. exception handling more about dml here are some things you may want to know about using data manipulation language. locking records when an sobject record is locked, no other client or user is allowed to make updates either through code or the salesforce user interface. the client locking the records can perform logic on the records and make updates with the guarantee that the locked records won’t be changed by another client during the lock period. how dml works single vs. bulk dml operations you can perform dml operations either on a single sobject, or in bulk on a list of sobjects. performing bulk dml operations is the recommended way because it helps avoid hitting governor limits, such as the dml limit of 150 statements per apex transaction. this limit is in place to ensure fair access to shared resources in the lightning platform. performing a dml operation on a list of sobjects counts as one dml statement, not as one statement for each sobject. this example performs dml calls on single sobjects, which isn’t efficient. the for loop iterates over contacts. for each contact, if the department field matches a certain value, it sets a new value for the description__c field. if the list contains more than items, the 151st update returns an exception that can't be caught. list<contact> conlist = [select department , description from contact]; for(contact badcon :
conlist) { if (badcon.department == 'finance') { badcon.description__c = 'new description'; } // not a good practice since governor limits might be hit. 126apex developer guide working with data in apex update badcon; } this example is a modified version of the previous example that doesn't hit the governor limit. the dml operation is performed in bulk by calling update on a list of contacts. this code counts as one dml statement, which is far below the limit of 150. // list to hold the new contacts to update. list<contact> updatedlist = new list<contact>(); list<contact> conlist = [select department , description from contact]; for(contact con : conlist) { if (con.department == 'finance') { con.description = 'new description'; // add updated contact sobject to the list. updatedlist.add(con); } } // call update on the list of contacts. // this results in one dml call for the entire list. update updatedlist; another dml governor limit is the total number of rows that can be processed by dml operations in a single transaction, which is 10,000. all rows processed by all dml calls in the same transaction count incrementally toward this limit. for example, if you insert 100 contacts and update 50 contacts in the same transaction, your total dml processed rows are 150. you still have 9,850 rows left (10,000 - 150). system context and sharing rules most dml operations execute in system context, ignoring the current user's permissions, field-level security, organization-wide defaults, position in the role hierarchy, and sharing rules. for more information, see enforcing sharing rules. note: if you execute dml operations within an anonymous block, they execute using the current user’s object and field-level permissions. best practices with dml on sobjects, it’s best to construct new instances and only update the fields you wish to modify without querying other fields. if you query fields other than the fields you wish to update, you may revert queried field values that could have changed between the query and the dml. adding and retrieving data with dml apex is tightly integrated with the lightning platform persistence layer. records in the database can be inserted and manipulated through apex directly using simple statements. the language in apex that allows you to add and manage records in the database is the data manipulation language (dml). in contrast to the soql language, which is used for read operations (querying records), dml is used for write operations. before inserting or manipulating records, record data is created in memory as sobjects. the sobject data type is a generic data type and corresponds to the data type of the variable that will hold the record data. there are specific data types, subtyped from the sobject data type, which correspond to data types of standard object records, such as account or contact, and custom objects, such as invoice_statement__c. typically, you will work with these specific sobject data types. but sometimes, when you don’t know the type 127apex developer guide working with data in apex of the sobject in advance, you can work with the generic sobject data type. this is an example of how you can create a new specific account sobject and assign it to a variable. account a = new account(name='account example'); in the previous example, the account referenced by the variable a exists in memory with the required name field. however, it is not persisted yet to the lightning platform persistence layer. you need to call dml statements to persist sobjects to the database. here is an example of creating and persisting this account using the insert statement. account a = new account(name='account example'); insert a; also, you can use dml to modify records that have already been inserted. among the operations you can perform are record updates, deletions, restoring records from the recycle bin, merging records, or converting leads. after querying for records, you get sobject instances that you can modify and then persist the changes of. this is an example of querying for an existing record that has been previously persisted, updating a couple of fields on the sobject representation of this record in memory, and then persisting this change to the database. // query existing account. account a = [select name,industry from account where name='account example' limit 1]; // write the old values the debug log before updating them. system.debug('account name before
update: ' + a.name); // name is account example system.debug('account industry before update: ' + a.industry);// industry is not set // modify the two fields on the sobject. a.name = 'account of the day'; a.industry = 'technology'; // persist the changes. update a; // get a new copy of the account from the database with the two fields. account a = [select name,industry from account where name='account of the day' limit 1]; // verify that updated field values were persisted. system.assertequals('account of the day', a.name); system.assertequals('technology', a.industry); dml statements vs. database class methods apex offers two ways to perform dml operations: using dml statements or database class methods. this provides flexibility in how you perform data operations. dml statements are more straightforward to use and result in exceptions that you can handle in your code. this is an example of a dml statement to insert a new record. // create the list of sobjects to insert list<account> acctlist = new list<account>(); acctlist.add(new account(name='acme1')); acctlist.add(new account(name='acme2')); 128apex developer guide working with data in apex // dml statement insert acctlist; this is an equivalent example to the previous one but it uses a method of the database class instead of the dml verb. // create the list of sobjects to insert list<account> acctlist = new list<account>(); acctlist.add(new account(name='acme1')); acctlist.add(new account(name='acme2')); // dml statement database.saveresult[] srlist = database.insert(acctlist, false); // iterate through each returned result for (database.saveresult sr : srlist) { if (sr.issuccess()) { // operation was successful, so get the id of the record that was processed system.debug('successfully inserted account. account id: ' + sr.getid()); } else { // operation failed, so get all errors for(database.error err : sr.geterrors()) { system.debug('the following error has occurred.'); system.debug(err.getstatuscode() + ': ' + err.getmessage()); system.debug('account fields that affected this error: ' + err.getfields()); } } } one difference between the two options is that by using the database class method, you can specify whether or not to allow for partial record processing if errors are encountered. you can do so by passing an additional second boolean parameter. if you specify false for this parameter and if a record fails, the remainder of dml operations can still succeed. also, instead of exceptions, a result object array (or one result object if only one sobject was passed in) is returned containing the status of each operation and any errors encountered. by default, this optional parameter is true, which means that if at least one sobject can’t be processed, all remaining sobjects won’t and an exception will be thrown for the record that causes a failure. the following helps you decide when you want to use dml statements or database class methods. • use dml statements if you want any error that occurs during bulk dml processing to be thrown as an apex exception that immediately interrupts control flow (by using try. . .catch blocks). this behavior is similar to the way exceptions are handled in most database procedural languages. • use database class methods if you want to allow partial success of a bulk dml operation—if a record fails, the remainder of the dml operation can still succeed. your application can then inspect the rejected records and possibly retry the operation. when using this form, you can write code that never throws dml exception errors. instead, your code can use the appropriate results array to judge success or failure. note that database methods also include a syntax that supports thrown exceptions, similar to dml statements. note: most operations overlap between the two, except for a few. • the convertlead operation is only available as a database class method, not as a dml statement. • the database class also provides methods not available as dml statements, such as methods transaction control and rollback, emptying the recycle bin, and methods related to soql queries. 129apex developer guide working with data in apex dml operations as atomic transactions
dml operations execute within a transaction. all dml operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database. the boundary of a transaction can be a trigger, a class method, an anonymous block of code, an apex page, or a custom web service method. all operations that occur inside the transaction boundary represent a single unit of operations. this also applies to calls that are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running in the transaction boundary. for example, consider the following chain of operations: a custom apex web service method calls a method in a class that performs some dml operations. in this case, all changes are committed to the database only after all operations in the transaction finish executing and don’t cause any errors. if an error occurs in any of the intermediate steps, all database changes are rolled back and the transaction isn’t committed. dml operations using dml, you can insert new records and commit them to the database. you can also update the field values of existing records. in this section: inserting and updating records using dml, you can insert new records and commit them to the database. similarly, you can update the field values of existing records. upserting records merging records deleting records restoring deleted records converting leads inserting and updating records using dml, you can insert new records and commit them to the database. similarly, you can update the field values of existing records. important: where possible, we changed noninclusive terms to align with our company value of equality. we maintained certain terms to avoid any effect on customer implementations. this example inserts three account records and updates an existing account record. first, three account sobjects are created and added to a list. an insert statement bulk inserts the list of accounts as an argument. then, the second account record is updated, the billing city is updated, and the update statement is called to persist the change in the database. account[] accts = new list<account>(); for(integer i=0;i<3;i++) { account a = new account(name='acme' + i, billingcity='san francisco'); accts.add(a); } account accounttoupdate; try { insert accts; // update account acme2. accounttoupdate = 130apex developer guide working with data in apex [select billingcity from account where name='acme2' and billingcity='san francisco' limit 1]; // update the billing city. accounttoupdate.billingcity = 'new york'; // make the update call. update accounttoupdate; } catch(dmlexception e) { system.debug('an unexpected error has occurred: ' + e.getmessage()); } // verify that the billing city was updated to new york. account afterupdate = [select billingcity from account where id=:accounttoupdate.id]; system.assertequals('new york', afterupdate.billingcity); inserting related records you can insert records related to existing records if a relationship has already been defined between the two objects, such as a lookup or master-detail relationship. a record is associated with a related record through a foreign key id. for example, when inserting a new contact, you can specify the contact’s related account record by setting the value of the accountid field. this example adds a contact to an account (the related record) by setting the accountid field on the contact. contact and account are linked through a lookup relationship. try { account acct = new account(name='sfdc account'); insert acct; // once the account is inserted, the sobject will be // populated with an id. // get this id. id acctid = acct.id; // add a contact to this account. contact con = new contact( firstname='joe', lastname='smith', phone='415.555.1212', accountid=acctid); insert con; } catch(dmlexception e) { system.debug('an unexpected error has occurred: ' + e.getmessage()); } updating related records fields on related records can't be updated with the same call to the dml operation and require a separate dml call. for example, if inserting a new contact, you can specify the contact's related account record by setting
the value of the accountid field. however, you can't change the account's name without updating the account itself with a separate dml call. similarly, when updating a contact, 131apex developer guide working with data in apex if you also want to update the contact’s related account, you must make two dml calls. the following example updates a contact and its related account using two update statements. try { // query for the contact, which has been associated with an account. contact queriedcontact = [select account.name from contact where firstname = 'joe' and lastname='smith' limit 1]; // update the contact's phone number queriedcontact.phone = '415.555.1213'; // update the related account industry queriedcontact.account.industry = 'technology'; // make two separate calls // 1. this call is to update the contact's phone. update queriedcontact; // 2. this call is to update the related account's industry field. update queriedcontact.account; } catch(exception e) { system.debug('an unexpected error has occurred: ' + e.getmessage()); } in this section: relating records by using an external id add related records by using a custom external id field on the parent record. associating records through the external id field is an alternative to using the record id. you can add a related record to another record only if a relationship (such as master-detail or lookup) has been defined for the objects involved. creating parent and child records in a single statement using foreign keys relating records by using an external id add related records by using a custom external id field on the parent record. associating records through the external id field is an alternative to using the record id. you can add a related record to another record only if a relationship (such as master-detail or lookup) has been defined for the objects involved. important: where possible, we changed noninclusive terms to align with our company value of equality. we maintained certain terms to avoid any effect on customer implementations. this example relates a new opportunity to an existing account. the account sobject has a custom field marked as external id. an opportunity record is associated to the account record through the custom external id field. the example assumes that: • the account sobject has an external id field of type text and named myextid • an account record exists where myextid__c = ‘sap111111’ before the new opportunity is inserted, the account record is added to this opportunity as an sobject through the opportunity.account relationship field. opportunity newopportunity = new opportunity( name='opportunitywithaccountinsert', stagename='prospecting', 132apex developer guide working with data in apex closedate=date.today().adddays(7)); // create the parent record reference. // an account with external id = 'sap111111' already exists. // this sobject is used only for foreign key reference // and doesn't contain any other fields. account accountreference = new account( myextid__c='sap111111'); // add the account sobject to the opportunity. newopportunity.account = accountreference; // create the opportunity. database.saveresult results = database.insert(newopportunity); the previous example performs an insert operation, but you can also relate sobjects through external id fields when performing updates or upserts. if the parent record doesn’t exist, you can create it with a separate dml statement or by using the same dml statement as shown in creating parent and child records in a single statement using foreign keys. creating parent and child records in a single statement using foreign keys you can use external id fields as foreign keys to create parent and child records of different sobject types in a single step instead of creating the parent record first, querying its id, and then creating the child record. to do this: • create the child sobject and populate its required fields, and optionally other fields. • create the parent reference sobject used only for setting the parent foreign key reference on the child sobject. this sobject has only the external id field defined and no other fields set. • set the foreign key field of the child sobject to the parent reference sobject you just created. • create another parent sobject to be passed to the insert statement. this sobject must have the required fields (and optionally other fields) set in addition to the external id field. • call insert by passing it an array of sobjects to create
. the parent sobject must precede the child sobject in the array, that is, the array index of the parent must be lower than the child’s index. you can create related records that are up to 10 levels deep. also, the related records created in a single call must have different sobject types. for more information, see creating records for different object types in the soap api developer guide. the following example shows how to create an opportunity with a parent account using the same insert statement. the example creates an opportunity sobject and populates some of its fields, then creates two account objects. the first account is only for the foreign key relationship, and the second is for the account creation and has the account fields set. both accounts have the external id field, myextid__c, set. next, the sample calls database.insert by passing it an array of sobjects. the first element in the array is the parent sobject and the second is the opportunity sobject. the database.insert statement creates the opportunity with its parent account in a single step. finally, the sample checks the results and writes the ids of the created records to the debug log, or the first error if record creation fails. this sample requires an external id text field on account called myextid. public class parentchildsample { public static void insertparentchild() { date dt = date.today(); dt = dt.adddays(7); opportunity newopportunity = new opportunity( name='opportunitywithaccountinsert', stagename='prospecting', closedate=dt); 133apex developer guide working with data in apex // create the parent reference. // used only for foreign key reference // and doesn't contain any other fields. account accountreference = new account( myextid__c='sap111111'); newopportunity.account = accountreference; // create the account object to insert. // same as above but has name field. // used for the insert. account parentaccount = new account( name='hallie', myextid__c='sap111111'); // create the account and the opportunity. database.saveresult[] results = database.insert(new sobject[] { parentaccount, newopportunity }); // check results. for (integer i = 0; i < results.size(); i++) { if (results[i].issuccess()) { system.debug('successfully created id: ' + results[i].getid()); } else { system.debug('error: could not create sobject ' + 'for array element ' + i + '.'); system.debug(' the error reported was: ' + results[i].geterrors()[0].getmessage() + '\n'); } } } } upserting records using the upsert operation, you can either insert or update an existing record in one call. to determine whether a record already exists, the upsert statement or database method uses the record’s id as the key to match records, a custom external id field, or a standard field with the idlookup attribute set to true. • if the key is not matched, then a new object record is created. • if the key is matched once, then the existing object record is updated. • if the key is matched multiple times, then an error is generated and the object record is neither inserted or updated. note: custom field matching is case-insensitive only if the custom field has the unique and treat "abc" and "abc" as duplicate values (case insensitive) attributes selected as part of the field definition. if this is the case, “abc123” is matched with “abc123.” for more information, see create custom fields. 134apex developer guide working with data in apex examples the following example updates the city name for all existing accounts located in the city formerly known as bombay, and also inserts a new account located in san francisco: account[] acctslist = [select id, name, billingcity from account where billingcity = 'bombay']; for (account a : acctslist) { a.billingcity = 'mumbai'; } account newacct = new account(name = 'acme', billingcity = 'san francisco'); acctslist.add(newacct); try { upsert acctslist; } catch (dmlexception e) { // process exception here } note: for more information on processing dmlexceptions, see bulk d
ml exception handling. this next example uses the database.upsert method to upsert a collection of leads that are passed in. this example allows for partial processing of records, that is, in case some records fail processing, the remaining records are still inserted or updated. it iterates through the results and adds a new task to each record that was processed successfully. the task sobjects are saved in a list, which is then bulk inserted. this example is followed by a test class that contains a test method for testing the example. /* this class demonstrates and tests the use of the * partial processing dml operations */ public class dmlsamples { /* this method accepts a collection of lead records and creates a task for the owner(s) of any leads that were created as new, that is, not updated as a result of the upsert operation */ public static list<database.upsertresult> upsertleads(list<lead> leads) { /* perform the upsert. in this case the unique identifier for the insert or update decision is the salesforce record id. if the record id is null the row will be inserted, otherwise an update will be attempted. */ list<database.upsertresult> uresults = database.upsert(leads,false); /* this is the list for new tasks that will be inserted when new leads are created. */ list<task> tasks = new list<task>(); for(database.upsertresult result:uresults) { if (result.issuccess() && result.iscreated()) tasks.add(new task(subject = 'follow-up', whoid = result.getid())); } /* if there are tasks to be inserted, insert them */ database.insert(tasks); return uresults; 135apex developer guide working with data in apex } } @istest private class dmlsamplestest { public static testmethod void testupsertleads() { /* we only need to test the insert side of upsert */ list<lead> leads = new list<lead>(); /* create a set of leads for testing */ for(integer i = 0;i < 100; i++) { leads.add(new lead(lastname = 'testlead', company = 'testcompany')); } /* switch to the runtime limit context */ test.starttest(); /* exercise the method */ list<database.upsertresult> results = dmlsamples.upsertleads(leads); /* switch back to the test context for limits */ test.stoptest(); /* id set for asserting the tasks were created as expected */ set<id> ids = new set<id>(); /* iterate over the results, asserting success and adding the new id to the set for use in the comprehensive assertion phase below. */ for(database.upsertresult result:results) { system.assert(result.issuccess()); ids.add(result.getid()); } /* assert that exactly one task exists for each lead that was inserted. */ for(lead l:[select id, (select subject from tasks) from lead where id in :ids]) { system.assertequals(1,l.tasks.size()); } } } use of upsert with an external id can reduce the number of dml statements in your code, and help you to avoid hitting governor limits (see execution governors and limits). this next example uses upsert and an external id field line_item_id__c on the asset object to maintain a one-to-one relationship between an asset and an opportunity line item. note: before running this sample, create a custom text field on the asset object named line_item_id__c and mark it as an external id. for information on custom fields, see the salesforce online help. public void upsertexample() { opportunity opp = [select id, name, accountid, (select id, pricebookentry.product2id, pricebookentry.name from opportunitylineitems) from opportunity where hasopportunitylineitem = true limit 1]; 136apex developer guide working with data in apex asset[] assets = new asset[]{}; // create an asset for each line item on the opportunity for (opportunitylineitem lineitem:opp.opportunitylineitems) { //this code populates the line item id, accountid, and product2id for each asset asset asset = new asset(name = lineitem.pricebookentry.name, line_item_id
__c = lineitem.id, accountid = opp.accountid, product2id = lineitem.pricebookentry.product2id); assets.add(asset); } try { upsert assets line_item_id__c; // this line upserts the assets list with // the line_item_id__c field specified as the // asset field that should be used for matching // the record that should be upserted. } catch (dmlexception e) { system.debug(e.getmessage()); } } merging records when you have duplicate lead, contact, case, or account records in the database, cleaning up your data and consolidating the records might be a good idea. you can merge up to three records of the same sobject type. the merge operation merges up to three records into one of the records, deletes the others, and reparents any related records. example the following shows how to merge an existing account record into a master account. the account to merge has a related contact, which is moved to the master account record after the merge operation. also, after merging, the merge record is deleted and only one record remains in the database. this examples starts by creating a list of two accounts and inserts the list. then it executes queries to get the new account records from the database, and adds a contact to the account to be merged. next, it merges the two accounts. finally, it verifies that the contact has been moved to the master account and the second account has been deleted. // insert new accounts list<account> ls = new list<account>{ new account(name='acme inc.'), new account(name='acme') }; insert ls; // queries to get the inserted accounts account masteracct = [select id, name from account where name = 'acme inc.' limit 1]; account mergeacct = [select id, name from account where name = 'acme' limit 1]; // add a contact to the account to be merged contact c = new contact(firstname='joe',lastname='merged'); c.accountid = mergeacct.id; 137apex developer guide working with data in apex insert c; try { merge masteracct mergeacct; } catch (dmlexception e) { // process exception system.debug('an unexpected error has occurred: ' + e.getmessage()); } // once the account is merged with the master account, // the related contact should be moved to the master record. masteracct = [select id, name, (select firstname,lastname from contacts) from account where name = 'acme inc.' limit 1]; system.assert(masteracct.getsobjects('contacts').size() > 0); system.assertequals('joe', masteracct.getsobjects('contacts')[0].get('firstname')); system.assertequals('merged', masteracct.getsobjects('contacts')[0].get('lastname')); // verify that the merge record got deleted account[] result = [select id, name from account where id=:mergeacct.id]; system.assertequals(0, result.size()); this second example is similar to the previous except that it uses the database.merge method (instead of the merge statement). the last argument of database.merge is set to false to have any errors encountered in this operation returned in the merge result instead of getting exceptions. the example merges two accounts into the master account and retrieves the returned results. the example creates a master account and two duplicates, one of which has a child contact. it verifies that after the merge the contact is moved to the master account. // create master account account master = new account(name='account1'); insert master; // create duplicate accounts account[] duplicates = new account[]{ // duplicate account new account(name='account1, inc.'), // second duplicate account new account(name='account 1') }; insert duplicates; // create child contact and associate it with first account contact c = new contact(firstname='joe',lastname='smith', accountid=duplicates[0].id); insert c; // get the account contact relation id, which is created when a contact is created on "account1, inc." accountcontactrelation resultacrel = [select id from accountcontactrelation where contactid=:c.id limit 1
]; // merge accounts into master database.mergeresult[] results = database.merge(master, duplicates, false); 138apex developer guide working with data in apex for(database.mergeresult res : results) { if (res.issuccess()) { // get the master id from the result and validate it system.debug('master record id: ' + res.getid()); system.assertequals(master.id, res.getid()); // get the ids of the merged records and display them list<id> mergedids = res.getmergedrecordids(); system.debug('ids of merged records: ' + mergedids); // get the id of the reparented record and // validate that this the contact id. system.debug('reparented record id: ' + res.getupdatedrelatedids()); // make sure there are two ids (contact id and account contact relation id); the order isn't defined system.assertequals(2, res.getupdatedrelatedids().size() ); boolean flag1 = false; boolean flag2 = false; // because the order of the ids isn't defined, the id can be at index 0 or 1 of the array if (resultacrel.id == res.getupdatedrelatedids()[0] || resultacrel.id == res.getupdatedrelatedids()[1] ) flag1 = true; if (c.id == res.getupdatedrelatedids()[0] || c.id == res.getupdatedrelatedids()[1] ) flag2 = true; system.assertequals(flag1, true); system.assertequals(flag2, true); } else { for(database.error err : res.geterrors()) { // write each error to the debug output system.debug(err.getmessage()); } } } merge considerations when merging sobject records, consider the following rules and guidelines: • only leads, contacts, cases, and accounts can be merged. see sobjects that don’t support dml operations on page 152. • you can pass a master record and up to two additional sobject records to a single merge method. • using the apex merge operation, field values on the master record always supersede the corresponding field values on the records to be merged. to preserve a merged record field value, simply set this field value on the master sobject before performing the merge. • external id fields can’t be used with merge. 139apex developer guide working with data in apex for more information on merging leads, contacts and accounts, see the salesforce online help. deleting records after you persist records in the database, you can delete those records using the delete operation. deleted records aren’t deleted permanently from salesforce, but they are placed in the recycle bin for 15 days from where they can be restored. restoring deleted records is covered in a later section. example the following example deletes all accounts that are named 'dotcom': account[] doomedaccts = [select id, name from account where name = 'dotcom']; try { delete doomedaccts; } catch (dmlexception e) { // process exception here } note: for more information on processing dmlexceptions, see bulk dml exception handling. referential integrity when deleting and restoring records the delete operation supports cascading deletions. if you delete a parent object, you delete its children automatically, as long as each child record can be deleted. for example, if you delete a case record, apex automatically deletes any casecomment, casehistory, and casesolution records associated with that case. however, if a particular child record is not deletable or is currently being used, then the delete operation on the parent case record fails. the undelete operation restores the record associations for the following types of relationships: • parent accounts (as specified in the parent account field on an account) • indirect account-contact relationships (as specified on the related accounts related list on a contact or the related contacts related list on an account) • parent cases (as specified in the parent case field on a case) • master solutions for translated solutions (as specified in the master solution field on a solution) • managers of contacts (as specified in the reports to field on a contact) • products related to assets (as specified in the product field on an asset) • opportunities related to quotes (as specified in the opportunity field on a
quote) • all custom lookup relationships • relationship group members on accounts and relationship groups, with some exceptions • tags • an article's categories, publication state, and assignments note: salesforce only restores lookup relationships that have not been replaced. for example, if an asset is related to a different product prior to the original product record being undeleted, that asset-product relationship is not restored. 140apex developer guide working with data in apex restoring deleted records after you have deleted records, the records are placed in the recycle bin for 15 days, after which they are permanently deleted. while the records are still in the recycle bin, you can restore them using the undelete operation. if you accidentally deleted some records that you want to keep, restore them from the recycle bin. example the following example undeletes an account named 'universal containers'. the all rows keyword queries all rows for both top level and aggregate relationships, including deleted records and archived activities. account a = new account(name='universal containers'); insert(a); insert(new contact(lastname='carter',accountid=a.id)); delete a; account[] savedaccts = [select id, name from account where name = 'universal containers' all rows]; try { undelete savedaccts; } catch (dmlexception e) { // process exception here } note: for more information on processing dmlexceptions, see bulk dml exception handling. undelete considerations note the following when using the undelete statement. • you can undelete records that were deleted as the result of a merge. however, the merge reparents the child objects, and that reparenting can’t be undone. • to identify deleted records, including records deleted as a result of a merge, use the all rows parameters with a soql query. • see referential integrity when deleting and restoring records. see also: querying all records with a soql statement converting leads the convertlead dml operation converts a lead into an account and contact, as well as (optionally) an opportunity.convertlead is available only as a method on the database class; it is not available as a dml statement. converting leads involves the following basic steps: 1. your application determines the ids of any lead(s) to be converted. 2. optionally, your application determines the ids of any account(s) into which to merge the lead. your application can use soql to search for accounts that match the lead name, as in the following example: select id, name from account where name='companynameofleadbeingmerged' 141apex developer guide working with data in apex 3. optionally, your application determines the ids of the contact or contacts into which to merge the lead. the application can use soql to search for contacts that match the lead contact name, as in the following example: select id, name from contact where firstname='firstname' and lastname='lastname' and accountid = '001...' 4. optionally, the application determines whether opportunities should be created from the leads. 5. the application uses the query (select ... from leadstatus where isconverted=true) to obtain the leads with converted status. 6. the application calls convertlead. 7. the application iterates through the returned result or results and examines each leadconvertresult object to determine whether conversion succeeded for each lead. 8. optionally, when converting leads owned by a queue, the owner must be specified. this is because accounts and contacts can’t be owned by a queue. even if you are specifying an existing account or contact, you must still specify an owner. example this example shows how to use the database.convertlead method to convert a lead. it inserts a new lead, creates a leadconvert object, sets its status to converted, and then passes it to the database.convertlead method. finally, it verifies that the conversion was successful. lead mylead = new lead(lastname = 'fry', company='fry and sons'); insert mylead; database.leadconvert lc = new database.leadconvert(); lc.setleadid(mylead.id); leadstatus convertstatus = [select id, masterlabel from leadstatus where isconverted=true limit 1]; lc.setconvertedstatus(convertstatus.masterlabel); database.leadconvertresult lcr = database.convertlead(lc); system.assert(lcr.issuccess()); convert
leads considerations • field mappings: the system automatically maps standard lead fields to standard account, contact, and opportunity fields. for custom lead fields, your salesforce administrator can specify how they map to custom account, contact, and opportunity fields. for more information about field mappings, see salesforce help. • merged fields: if data is merged into existing account and contact objects, only empty fields in the target object are overwritten—existing data (including ids) are not overwritten. the only exception is if you specify setoverwriteleadsource on the leadconvert object to true, in which case the leadsource field in the target contact object is overwritten with the contents of the leadsource field in the source leadconvert object. • record types: if the organization uses record types, the default record type of the new owner is assigned to records created during lead conversion. the default record type of the user converting the lead determines the lead source values available during conversion. if the desired lead source values are not available, add the values to the default record type of the user converting the lead. for more information about record types, see salesforce help. 142apex developer guide working with data in apex • picklist values: the system assigns the default picklist values for the account, contact, and opportunity when mapping any standard lead picklist fields that are blank. if your organization uses record types, blank values are replaced with the default picklist values of the new record owner. • automatic feed subscriptions: when you convert a lead into a new account, contact, and opportunity, the lead owner is unsubscribed from the lead record’s chatter feed. the lead owner, the owner of the generated records, and users that were subscribed to the lead aren’t automatically subscribed to the generated records, unless they have automatic subscriptions enabled in their chatter feed settings. they must have automatic subscriptions enabled to see changes to the account, contact, and opportunity records in their news feed. to subscribe to records they create, users must enable the automatically follow records that i create option in their personal settings. a user can subscribe to a record so that changes to the record display in the news feed on the user's home page. this is a useful way to stay up-to-date with changes to records in salesforce. exception handling dml statements return run-time exceptions if something went wrong in the database during the execution of the dml operations. you can handle the exceptions in your code by wrapping your dml statements within try-catch blocks. the following example includes the insert dml statement inside a try-catch block. account a = new account(name='acme'); try { insert a; } catch(dmlexception e) { // process exception here } in this section: database class method result objects returned database errors database class method result objects database class methods return the results of the data operation. these result objects contain useful information about the data operation for each record, such as whether the operation was successful or not, and any error information. each type of operation returns a specific result object type, as outlined below. operation result class insert, update saveresult class upsert upsertresult class merge mergeresult class delete deleteresult class undelete undeleteresult class convertlead leadconvertresult class emptyrecyclebin emptyrecyclebinresult class 143apex developer guide working with data in apex returned database errors while dml statements always return exceptions when an operation fails for one of the records being processed and the operation is rolled back for all records, database class methods can either do so or allow partial success for record processing. in the latter case of partial processing, database class methods don’t throw exceptions. instead, they return a list of errors for any errors that occurred on failed records. the errors provide details about the failures and are contained in the result of the database class method. for example, a saveresult object is returned for insert and update operations. like all returned results, saveresult contains a method called geterrors that returns a list of database.error objects, representing the errors encountered, if any. example this example shows how to get the errors returned by a database.insert operation. it inserts two accounts, one of which doesn’t have the required name field, and sets the second parameter to false: database.insert(accts, false);. this sets the partial processing option. next, the example checks if the call had any failures through if (!sr.issuccess()) and then iterates through the errors, writing error information to the debug log. // create two accounts, one of which is missing a required field account
[] accts = new list<account>{ new account(name='account1'), new account()}; database.saveresult[] srlist = database.insert(accts, false); // iterate through each returned result for (database.saveresult sr : srlist) { if (!sr.issuccess()) { // operation failed, so get all errors for(database.error err : sr.geterrors()) { system.debug('the following error has occurred.'); system.debug(err.getstatuscode() + ': ' + err.getmessage()); system.debug('fields that affected this error: ' + err.getfields()); } } } more about dml here are some things you may want to know about using data manipulation language. in this section: setting dml options transaction control sobjects that cannot be used together in dml operations dml operations on certain sobjects, sometimes referred to as setup objects, can’t be mixed with dml on other sobjects in the same transaction. this restriction exists because some sobjects affect the user’s access to records in the org. you must insert or update these types of sobjects in a different transaction to prevent operations from happening with incorrect access-level permissions. for example, you can’t update an account and a user role in a single transaction. sobjects that don’t support dml operations bulk dml exception handling 144apex developer guide working with data in apex things you should know about data in apex setting dml options you can specify dml options for insert and update operations by setting the desired options in the database.dmloptions object. you can set database.dmloptions for the operation by calling the setoptions method on the sobject, or by passing it as a parameter to the database.insert and database.update methods. using dml options, you can specify: • the truncation behavior of fields. • assignment rule information. • duplicate rule information. • whether automatic emails are sent. • the user locale for labels. • whether the operation allows for partial success. the database.dmloptions class has the following properties: • allowfieldtruncation property • assignmentruleheader property • dupicateruleheader • emailheader property • localeoptions property • optallornone property dmloptions is only available for apex saved against api versions 15.0 and higher. dmloptions settings take effect only for record operations performed using apex dml and not through the salesforce user interface. allowfieldtruncation property the allowfieldtruncation property specifies the truncation behavior of strings. in apex saved against api versions previous to 15.0, if you specify a value for a string and that value is too large, the value is truncated. for api version 15.0 and later, if a value is specified that is too large, the operation fails and an error message is returned. the allowfieldtruncation property allows you to specify that the previous behavior, truncation, be used instead of the new behavior in apex saved against api versions 15.0 and later. the allowfieldtruncation property takes a boolean value. if true, the property truncates string values that are too long, which is the behavior in api versions 14.0 and earlier. for example: database.dmloptions dml = new database.dmloptions(); dml.allowfieldtruncation = true; assignmentruleheader property the assignmentruleheader property specifies the assignment rule to be used when creating a case or lead. note: the database.dmloptions object supports assignment rules for cases and leads, but not for accounts. using the assignmentruleheader property, you can set these options: 145apex developer guide working with data in apex • assignmentruleid: the id of an assignment rule for the case or lead. the assignment rule can be active or inactive. the id can be retrieved by querying the assignmentrule sobject. if specified, do not specify usedefaultrule. if the value is not in the correct id format (15-character or 18-character salesforce id), the call fails and an exception is returned. • usedefaultrule: indicates whether the default (active) assignment rule will be used for a case or lead. if specified, do not specify an assignmentruleid. the following example uses the usedefaultrule option: database.dmloptions dmo = new database.dmloptions(); dmo.assignmentruleheader.usedefaultrule= true; lead l = new lead(company
='abc', lastname='smith'); l.setoptions(dmo); insert l; the following example uses the assignmentruleid option: database.dmloptions dmo = new database.dmloptions(); dmo.assignmentruleheader.assignmentruleid= '01qd0000000eqan'; lead l = new lead(company='abc', lastname='smith'); l.setoptions(dmo); insert l; note: if there are no assignment rules in the organization, in api version 29.0 and earlier, creating a case or lead with usedefaultrule set to true results in the case or lead being assigned to the predefined default owner. in api version 30.0 and later, the case or lead is unassigned and doesn't get assigned to the default owner. dupicateruleheader property the dupicateruleheader property determines whether a record that’s identified as a duplicate can be saved. duplicate rules are part of the duplicate management feature. using the dupicateruleheader property, you can set these options. • allowsave: indicates whether a record that’s identified as a duplicate can be saved. the following example shows how to save an account record that’s been identified as a duplicate. to learn how to iterate through duplicate errors, see duplicateerror class database.dmloptions dml = new database.dmloptions(); dml.duplicateruleheader.allowsave = true; account duplicateaccount = new account(name='dupe'); database.saveresult sr = database.insert(duplicateaccount, dml); if (sr.issuccess()) { system.debug('duplicate account has been inserted in salesforce!'); } emailheader property the salesforce user interface allows you to specify whether or not to send an email when the following events occur: • creation of a new case or task • conversion of a case email to a contact • new user email notification 146
apex developer guide working with data in apex • lead queue email notification • password reset in apex saved against api version 15.0 or later, the database.dmloptions emailheader property enables you to specify additional information regarding the email that gets sent when one of the events occurs because of apex dml code execution. using the emailheader property, you can set these options. • triggerautoresponseemail: indicates whether to trigger auto-response rules (true) or not (false), for leads and cases. this email can be automatically triggered by a number of events, for example when creating a case or resetting a user password. if this value is set to true, when a case is created, if there is an email address for the contact specified in contactid, the email is sent to that address. if not, the email is sent to the address specified in suppliedemail. • triggerotheremail: indicates whether to trigger email outside the organization (true) or not (false). this email can be automatically triggered by creating, editing, or deleting a contact for a case. • triggeruseremail: indicates whether to trigger email that is sent to users in the organization (true) or not (false). this email can be automatically triggered by a number of events; resetting a password, creating a new user, or creating or modifying a task. note: adding comments to a case in apex doesn’t trigger email to users in the organization even if triggeruseremail is set to true. even though auto-sent emails can be triggered by actions in the salesforce user interface, the dmloptions settings for emailheader take effect only for dml operations carried out in apex code. in the following example, the triggerautoresponseemail option is specified: account a = new account(name='acme plumbing'); insert a; contact c = new contact(email='[email protected]', firstname='joe',lastname='plumber', accountid=a.id); insert c; database.dmloptions dlo = new database.dmloptions(); dlo.emailheader.triggerautoresponseemail = true; case ca = new case(subject='plumbing problems', contactid=c.id); database.insert(ca, dlo); email sent through apex because of a group event includes additional behaviors. a group event is an event for which isgroupevent is true. the eventattendee object tracks the users, leads, or contacts that are invited to a group event. note the following behaviors for group event email sent through apex: • sending a group event invitation to a user respects the triggeruseremail option • sending a group event invitation to a lead or contact respects the triggerotheremail option • email sent when updating or deleting a group event also respects the triggeruseremail and triggerotheremail options, as appropriate 147apex developer guide working with data in apex localeoptions property the localeoptions property specifies the language of any labels that are returned by apex. the value must be a valid user locale (language and country), such as de_de or en_gb. the value is a string, 2-5 characters long. the first two characters are always an iso language code, for example 'fr' or 'en.' if the value is further qualified by a country, then the string also has an underscore (_) and another iso country code, for example 'us' or 'uk.' for example, the string for the united states is 'en_us', and the string for french canadian is 'fr_ca'. optallornone property the optallornone property specifies whether the operation allows for partial success. if optallornone is set to true, all changes are rolled back if any record causes errors. the default for this property is false and successfully processed records are committed while records with errors aren't. this property is available in apex saved against salesforce api version 20.0 and later. transaction control all requests are delimited by the trigger, class method, web service, visualforce page or anonymous block that executes the apex code. if the entire request completes successfully, all changes are committed to the database. for example, suppose a visualforce page called an apex controller, which in turn called an additional apex class. only when all the apex code has finished running and the visualforce page has finished running, are the changes committed to the database. if the request does not complete successfully, all database changes are rolled back. sometimes during the processing of records, your business rules require that partial work (already executed dml statements) be “rolled back” so that the processing can continue in another direction. apex gives you the ability to
generate a savepoint, that is, a point in the request that specifies the state of the database at that time. any dml statement that occurs after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated the savepoint. the following limitations apply to generating savepoint variables and rolling back the database: • if you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. for example, if you generated savepoint sp1 first, savepoint sp2 after that, and then you rolled back to sp1, the variable sp2 would no longer be valid. you will receive a runtime error if you try to use it. • references to savepoints cannot cross trigger invocations because each trigger invocation is a new trigger context. if you declare a savepoint as a static variable then try to use it across trigger contexts, you will receive a run-time error. • each savepoint you set counts against the governor limit for dml statements. • static variables are not reverted during a rollback. if you try to run the trigger again, the static variables retain the values from the first run. • each rollback counts against the governor limit for dml statements. you will receive a runtime error if you try to rollback the database additional times. • the id on an sobject inserted after setting a savepoint is not cleared after a rollback. create an sobject to insert after a rollback. attempting to insert the sobject using the variable created before the rollback fails because the sobject variable has an id. updating or upserting the sobject using the same variable also fails because the sobject is not in the database and, thus, cannot be updated. the following is an example using the setsavepoint and rollback database methods. account a = new account(name = 'xxx'); insert a; system.assertequals(null, [select accountnumber from account where id = :a.id]. accountnumber); // create a savepoint while accountnumber is null savepoint sp = database.setsavepoint(); 148apex developer guide working with data in apex // change the account number a.accountnumber = '123'; update a; system.assertequals('123', [select accountnumber from account where id = :a.id]. accountnumber); // rollback to the previous null value database.rollback(sp); system.assertequals(null, [select accountnumber from account where id = :a.id]. accountnumber); sobjects that cannot be used together in dml operations dml operations on certain sobjects, sometimes referred to as setup objects, can’t be mixed with dml on other sobjects in the same transaction. this restriction exists because some sobjects affect the user’s access to records in the org. you must insert or update these types of sobjects in a different transaction to prevent operations from happening with incorrect access-level permissions. for example, you can’t update an account and a user role in a single transaction. you can’t use the following sobjects with other sobjects when performing dml operations in the same transaction. • authsession • fieldpermissions • group you can only insert and update a group in a transaction with other sobjects. other dml operations aren’t allowed. • groupmember note: with legacy apex code saved using salesforce api version 14.0 and earlier, you can insert and update a group member with other sobjects in the same transaction. • objectpermissions • objectterritory2assignmentrule • objectterritory2assignmentruleitem • permissionset • permissionsetassignment • queuesobject • ruleterritory2association • setupentityaccess • territory • territory2 • territory2model • user you can insert a user in a transaction with other sobjects in apex code saved using salesforce api version 14.0 and earlier. you can insert a user in a transaction with other sobjects in apex code saved using salesforce api version 15.0 and later when userroleid is specified as null. you can update a user in a transaction with other sobjects in apex code saved using salesforce api version 14.0 and earlier you can update a user in a transaction with other sobjects in apex code saved using salesforce api version 15.0 and later when the user isn’t included in a lightning sync configuration (either active or inactive) and
the following fields aren’t updated: 149apex developer guide working with data in apex – userroleid – isactive – forecastenabled – isportalenabled – username – profileid • userrole • userterritory • userterritory2association if you're using a visualforce page with a custom controller, you can't mix sobject types with any of these special sobjects within a single request or action. however, you can perform dml operations on these different types of sobjects in subsequent requests. for example, you can create an account with a save button, and then create a user with a non-null role with a submit button. you can perform dml operations on more than one type of sobject in a single class using the following process: 1. create a method that performs a dml operation on one type of sobject. 2. create a second method that uses the future annotation to manipulate a second sobject type. this process is demonstrated in the example in the next section. example: using a future method to perform mixed dml operations this example shows how to perform mixed dml operations by using a future method to perform a dml operation on the user object. public class mixeddmlfuture { public static void usefuturemethod() { // first dml operation account a = new account(name='acme'); insert a; // this next operation (insert a user with a role) // can't be mixed with the previous insert unless // it is within a future method. // call future method to insert a user with a role. util.insertuserwithrole( '[email protected]', 'mruiz', '[email protected]', 'ruiz'); } } public class util { @future public static void insertuserwithrole( string uname, string al, string em, string lname) { profile p = [select id from profile where name='standard user']; userrole r = [select id from userrole where name='coo']; // create new user with a non-null user role id user u = new user(alias = al, email=em, emailencodingkey='utf-8', lastname=lname, languagelocalekey='en_us', 150apex developer guide working with data in apex localesidkey='en_us', profileid = p.id, userroleid = r.id, timezonesidkey='america/los_angeles', username=uname); insert u; } } in this section: mixed dml operations in test methods test methods allow for performing mixed data manipulation language (dml) operations that include both setup sobjects and other sobjects if the code that performs the dml operations is enclosed within system.runas method blocks. you can also perform dml in an asynchronous job that your test method calls. these techniques enable you, for example, to create a user with a role and other sobjects in the same test. mixed dml operations in test methods test methods allow for performing mixed data manipulation language (dml) operations that include both setup sobjects and other sobjects if the code that performs the dml operations is enclosed within system.runas method blocks. you can also perform dml in an asynchronous job that your test method calls. these techniques enable you, for example, to create a user with a role and other sobjects in the same test. the setup sobjects are listed in sobjects that cannot be used together in dml operations. note: because validation for mixed dml operations is skipped during deployment, there can be a difference in the number of test failures when tests are deployed versus when run in the user interface. example: mixed dml operations in system.runas blocks this example shows how to enclose mixed dml operations within system.runas blocks to avoid the mixed dml error. the system.runas block runs in the current user’s context. it creates a test user with a role and a test account, which is a mixed dml operation. @istest private class mixeddml { static testmethod void mixeddmlexample() { user u; account a; user thisuser = [select id from user where id = :userinfo.getuserid()]; // insert account as current user system.runas (thisuser) { profile p = [select id from profile where name='standard user']; userrole r =
[select id from userrole where name='coo']; u = new user(alias = 'jsmith', email='[email protected]', emailencodingkey='utf-8', lastname='smith', languagelocalekey='en_us', localesidkey='en_us', profileid = p.id, userroleid = r.id, timezonesidkey='america/los_angeles', username='[email protected]'); insert u; a = new account(name='acme'); insert a; } 151apex developer guide working with data in apex } } use @future to bypass the mixed dml error in a test method mixed dml operations within a single transaction aren’t allowed. you can’t perform dml on a setup sobject and another sobject in the same transaction. however, you can perform one type of dml as part of an asynchronous job and the others in other asynchronous jobs or in the original transaction. this class contains an @future method to be called by the class in the subsequent example. public class insertfutureuser { @future public static void insertuser() { profile p = [select id from profile where name='standard user']; userrole r = [select id from userrole where name='coo']; user futureuser = new user(firstname = 'future', lastname = 'user', alias = 'future', defaultgroupnotificationfrequency = 'n', digestfrequency = 'n', email = '[email protected]', emailencodingkey = 'utf-8', languagelocalekey='en_us', localesidkey='en_us', profileid = p.id, timezonesidkey = 'america/los_angeles', username = '[email protected]', userpermissionsmarketinguser = false, userpermissionsofflineuser = false, userroleid = r.id); insert(futureuser); } } this class calls the method in the previous class. @istest public class userandcontacttest { public testmethod static void testuserandcontact() { insertfutureuser.insertuser(); contact currentcontact = new contact( firstname = string.valueof(system.currenttimemillis()), lastname = 'contact'); insert(currentcontact); } } sobjects that don’t support dml operations your organization contains standard objects provided by salesforce and custom objects that you created. these objects can be accessed in apex as instances of the sobject data type. you can query these objects and perform dml operations on them. however, some standard objects don’t support dml operations although you can still obtain them in queries. they include the following: • accountterritoryassignmentrule • accountterritoryassignmentruleitem • apexcomponent • apexpage • businesshours • businessprocess 152apex developer guide working with data in apex • categorynode • currencytype • datedconversionrate • networkmember (allows update only) • processinstance • profile • recordtype • selfserviceuser • staticresource • territory2 • useraccountteammember • userpreference • userterritory • weblink • if an account record has a record type of person account, the name field can’t be modified with dml operations. note: all standard and custom objects can also be accessed through the soap api. processinstance is an exception. you can’t create, update, or delete processinstance in the soap api. bulk dml exception handling exceptions that arise from a bulk dml call (including any recursive dml operations in triggers that are fired as a direct result of the call) are handled differently depending on where the original call came from: • when errors occur because of a bulk dml call that originates directly from the apex dml statements, or if the allornone parameter of a database dml method is specified as true, the runtime engine follows the “all or nothing” rule: during a single operation, all records must be updated successfully or the entire operation rolls back to the point immediately preceding the dml statement. if the allornone parameter of a database dml method is specified as false and a before trigger assigns an invalid value to a field, the partial set of valid records isn’t inserted. • when errors occur because of a bulk dml call that originates from soap api with default settings, or if the
allornone parameter of a database dml method was specified as false, the runtime engine attempts at least a partial save: 1. during the first attempt, the runtime engine processes all records. any record that generates an error due to issues such as validation rules or unique index violations is set aside. 2. if there were errors during the first attempt, the runtime engine makes a second attempt that includes only those records that didn’t generate errors. all records that didn't generate an error during the first attempt are processed, and if any record generates an error (perhaps because of race conditions) it’s also set aside. 3. if there were additional errors during the second attempt, the runtime engine makes a third and final attempt that includes only those records that didn’t generate errors during the first and second attempts. if any record generates an error, the entire operation fails with the error message, “too many batch retries in the presence of apex triggers and partial failures.” note: – during the second and third attempts, governor limits are reset to their original state before the first attempt. see execution governors and limits on page 311. – apex triggers are fired for the first save attempt, and if errors are encountered for some records and subsequent attempts are made to save the subset of successful records, triggers are refired on this subset of records. 153apex developer guide working with data in apex things you should know about data in apex non-null required fields values and null fields when inserting new records or updating required fields on existing records, you must supply non-null values for all required fields. unlike the soap api, apex allows you to change field values to null without updating the fieldstonull array on the sobject record. the api requires an update to this array due to the inconsistent handling of null values by many soap providers. because apex runs solely on the lightning platform, this workaround is unnecessary. dml not supported with some sobjects dml operations are not supported with certain sobjects. see sobjects that don’t support dml operations. string field truncation and api version apex classes and triggers saved (compiled) using api version 15.0 and higher produce a runtime error if you assign a string value that is too long for the field. sobject properties to enable dml operations to be able to insert, update, delete, or undelete an sobject record, the sobject must have the corresponding property (createable, updateable, deletable, or undeletable respectively) set to true. id values the insert statement automatically sets the id value of all new sobject records. inserting a record that already has an id—and therefore already exists in your organization's data—produces an error. see lists for more information. the insert and update statements check each batch of records for duplicate id values. if there are duplicates, the first five are processed. for the sixth and all additional duplicate ids, the saveresult for those entries is marked with an error similar to the following: maximum number of duplicate updates in one batch (5 allowed). attempt to update id more than once in this api call: number_of_attempts. the id of an updated sobject record cannot be modified in an update statement, but related record ids can. fields with unique constraints for some sobjects that have fields with unique constraints, inserting duplicate sobject records results in an error. for example, inserting collaborationgroup sobjects with the same names results in an error because collaborationgroup records must have unique names. system fields automatically set when inserting new records, system fields such as createddate, createdbyid, and systemmodstamp are automatically updated. you cannot explicitly specify these values in your apex. similarly, when updating records, system fields such as lastmodifieddate, lastmodifiedbyid, and systemmodstamp are automatically updated. maximum number of records processed by dml statement you can pass a maximum of 10,000 sobject records to a single insert, update, delete, and undelete method. each upsert statement consists of two operations, one for inserting records and one for updating records. each of these operations is subject to the runtime limits for insert and update, respectively. for example, if you upsert more than 10,000 records and all of them are being updated, you receive an error. (see execution governors and limits on page 311) upsert and foreign keys you can use foreign keys to upsert sobject records if they have been set as reference fields. for more information, see field types in the object reference for salesforce. creating records for multiple object types as with the
soap api, you can create records in apex for multiple object types, including custom objects, in one dml call with api version 20.0 and later. for example, you can create a contact and an account in one call. you can create records for up to 10 object types in one call. records are saved in the same order that they’re entered in the sobject input array. if you’re entering new records that have a parent-child relationship, the parent record must precede the child record in the array. for example, if you’re creating a contact that 154apex developer guide working with data in apex references an account that’s also being created in the same call, the account must have a smaller index in the array than the contact does. the contact references the account by using an external id field. you can’t add a record that references another record of the same object type in the same call. for example, the contact object has a reports to field that’s a reference to another contact. you can’t create two contacts in one call if one contact uses the reports to field to reference a second contact in the input array. you can create a contact that references another contact that has been previously created. records for multiple object types are broken into multiple chunks by salesforce. a chunk is a subset of the input array, and each chunk contains records of one object type. data is committed on a chunk-by-chunk basis. any apex triggers that are related to the records in a chunk are invoked once per chunk. consider an sobject input array that contains the following set of records: account1, account2, contact1, contact2, contact3, case1, account3, account4, contact4 salesforce splits the records into five chunks: 1. account1, account2 2. contact1, contact2, contact3 3. case1 4. account3, account4 5. contact4 each call can process up to 10 chunks. if the sobject array contains more than 10 chunks, you must process the records in more than one call. for additional information about this feature, see creating records for different object types in the soap api developer guide. note: for apex, the chunking of the input array for an insert or update dml operation has two possible causes: the existence of multiple object types or the default chunk size of 200. if chunking in the input array occurs because of both of these reasons, each chunk is counted toward the limit of 10 chunks. if the input array contains only one type of sobject, you won’t hit this limit. however, if the input array contains at least two sobject types and contains a high number of objects that are chunked into groups of 200, you might hit this limit. for example, if you have an array that contains 1,001 consecutive leads followed by 1,001 consecutive contacts, the array will be chunked into 12 groups: two groups are due to the different sobject types of lead and contact, and the remaining are due to the default chunking size of 200 objects. in this case, the insert or update operation returns an error because you reached the limit of 10 chunks in hybrid arrays. the workaround is to call the dml operation for each object type separately. dml and knowledge objects to execute dml code on knowledge articles (knowledgearticleversion types such as the custom faq__kav article type), the running user must have the knowledge user feature license. otherwise, calling a class method that contains dml operations on knowledge articles results in errors. if the running user isn’t a system administrator and doesn’t have the knowledge user feature license, calling any method in the class returns an error even if the called method doesn’t contain dml code for knowledge articles but another method in the class does. for example, the following class contains two methods, only one of which performs dml on a knowledge article. a non-administrator non-knowledge user who calls the donothing method will get the following error: dml operation update not allowed on faq__kav public class knowledgeaccess { public void donothing() { } public void dmloperation() { faq__kav[] articles = [select id from faq__kav where publishstatus = 'draft' and 155apex developer guide working with data in apex language = 'en_us']; update articles; } } as a workaround, cast the input array to the dml statement from an array of faq__kav articles to an array of the generic sobject type as follows: public void dmloperation() { faq__k
av[] articles = [select id from faq__kav where publishstatus = 'draft' and language = 'en_us']; update (sobject[]) articles; } locking records when an sobject record is locked, no other client or user is allowed to make updates either through code or the salesforce user interface. the client locking the records can perform logic on the records and make updates with the guarantee that the locked records won’t be changed by another client during the lock period. in this section: locking statements in apex, you can use for update to lock sobject records while they’re being updated in order to prevent race conditions and other thread safety problems. locking in a soql for loop avoiding deadlocks locking statements in apex, you can use for update to lock sobject records while they’re being updated in order to prevent race conditions and other thread safety problems. while an sobject record is locked, no other client or user is allowed to make updates either through code or the salesforce user interface. the client locking the records can perform logic on the records and make updates with the guarantee that the locked records won’t be changed by another client during the lock period. the lock gets released when the transaction completes. to lock a set of sobject records in apex, embed the keywords for update after any inline soql statement. for example, the following statement, in addition to querying for two accounts, also locks the accounts that are returned: account [] accts = [select id from account limit 2 for update]; note: you can’t use the order by keywords in any soql query that uses locking. locking considerations • while the records are locked by a client, the locking client can modify their field values in the database in the same transaction. other clients have to wait until the transaction completes and the records are no longer locked before being able to update the same records. other clients can still query the same records while they’re locked. • if you attempt to lock a record currently locked by another client, your process waits a maximum of 10 seconds for the lock to be released before acquiring a new lock. if the wait time exceeds 10 seconds, a queryexception is thrown. similarly, if you attempt 156apex developer guide working with data in apex to update a record currently locked by another client and the lock isn’t released within a maximum of 10 seconds, a dmlexception is thrown. • if a client attempts to modify a locked record, the update operation might succeed if the lock gets released within a short amount of time after the update call was made. in this case, it is possible that the updates will overwrite those made by the locking client if the second client obtained an old copy of the record. to prevent this from happening, the second client must lock the record first. the locking process returns a fresh copy of the record from the database through the select statement. the second client can use this copy to make new updates. • the record locks that are obtained in apex via for update clause are automatically released when making callouts. use caution while making callouts in contexts where for update queries may have been previously executed. • when you perform a dml operation on one record, related records are locked in addition to the record in question. for more information, see the record locking cheat sheet. warning: use care when setting locks in your apex code. see avoiding deadlocks. locking in a soql for loop the for update keywords can also be used within soql for loops. for example: for (account[] accts : [select id from account for update]) { // your code } as discussed in soql for loops, the example above corresponds internally to calls to the query() and querymore() methods in the soap api. note that there is no commit statement. if your apex trigger completes successfully, any database changes are automatically committed. if your apex trigger does not complete successfully, any changes made to the database are rolled back. avoiding deadlocks apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple database tables or rows. to avoid such deadlocks, the apex runtime engine: 1. first locks sobject parent records, then children. 2. locks sobject records in order of id when multiple records of the same type are being edited. as a developer, use care when locking rows to ensure that you are not introducing deadlocks. verify that you are using standard deadlock avoidance techniques by accessing tables and rows in the same order from all locations in an application. soql and sosl queries
you can evaluate salesforce object query language (soql) or salesforce object search language (sosl) statements on-the-fly in apex by surrounding the statement in square brackets. soql statements soql statements evaluate to a list of sobjects, a single sobject, or an integer for count method queries. for example, you could retrieve a list of accounts that are named acme: list<account> aa = [select id, name from account where name = 'acme']; 157apex developer guide working with data in apex from this list, you can access individual elements: if (!aa.isempty()) { // execute commands } you can also create new objects from soql queries on existing ones. this example creates a new contact for the first account with the number of employees greater than 10. contact c = new contact(account = [select name from account where numberofemployees > 10 limit 1]); c.firstname = 'james'; c.lastname = 'yoyce'; the newly created object contains null values for its fields, which must be set. the count method can be used to return the number of rows returned by a query. the following example returns the total number of contacts with the last name of weissman: integer i = [select count() from contact where lastname = 'weissman']; you can also operate on the results using standard arithmetic: integer j = 5 * [select count() from account]; soql limits apply when executing soql queries. see execution governors and limits. for a full description of soql query syntax, see the salesforce soql and sosl reference guide. sosl statements sosl statements evaluate to a list of lists of sobjects, where 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. if a sosl query doesn’t return any records for a specified sobject type, the search results include an empty list for that sobject. for example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phrase map: list<list<sobject>> searchlist = [find 'map*' in all fields returning account (id, name), contact, opportunity, lead]; note: the syntax of the find clause in apex differs from the syntax of the find clause in soap api and rest api: • in apex, the value of the find clause is demarcated with single quotes. for example: find 'map*' in all fields returning account (id, name), contact, opportunity, lead note: apex that is running in system mode ignores field-level security while scanning for a match using in all fields. • in the api, the value of the find clause is demarcated with braces. for example: find {map*} in all fields returning account (id, name), contact, opportunity, lead from searchlist, you can create arrays for each object returned: account [] accounts = ((list<account>)searchlist[0]); contact [] contacts = ((list<contact>)searchlist[1]); 158apex developer guide working with data in apex opportunity [] opportunities = ((list<opportunity>)searchlist[2]); lead [] leads = ((list<lead>)searchlist[3]); sosl limits apply when executing sosl queries. see execution governors and limits. for a full description of sosl query syntax, see the salesforce soql and sosl reference guide. in this section: 1. working with soql and sosl query results 2. accessing sobject fields through relationships 3. understanding foreign key and parent-child relationship soql queries 4. working with soql aggregate functions 5. working with very large soql queries 6. using soql queries that return one record 7. improve performance by avoiding null values 8. working with polymorphic relationships in soql queries a polymorphic relationship is a relationship between objects where a referenced object can be one of several different types. for example, the who relationship field of a task can be a contact or a lead. 9. using apex variables in soql and sosl queries 10. querying all records with a soql statement working with soql and sosl query results soql and sosl queries only return data for sobject fields that are selected in the original query. if you try to access a field that was not selected in the soql
or sosl query (other than id), you receive a runtime error, even if the field contains a value in the database. the following code example causes a runtime error: insert new account(name = 'singha'); account acc = [select id from account where name = 'singha' limit 1]; // note that name is not selected string name = [select id from account where name = 'singha' limit 1].name; the following is the same code example rewritten so it does not produce a runtime error. note that name has been added as part of the select statement, after id. insert new account(name = 'singha'); account acc = [select id from account where name = 'singha' limit 1]; // note that name is now selected string name = [select id, name from account where name = 'singha' limit 1].name; even if only one sobject field is selected, a soql or sosl query always returns data as complete records. consequently, you must dereference the field in order to access it. for example, this code retrieves an sobject list from the database with a soql query, accesses the first account record in the list, and then dereferences the record's annualrevenue field: double rev = [select annualrevenue from account where name = 'acme'][0].annualrevenue; // when only one result is returned in a soql query, it is not necessary // to include the list's index. 159apex developer guide working with data in apex double rev2 = [select annualrevenue from account where name = 'acme' limit 1].annualrevenue; the only situation in which it is not necessary to dereference an sobject field in the result of an soql query, is when the query returns an integer as the result of a count operation: integer i = [select count() from account]; fields in records returned by sosl queries must always be dereferenced. also note that sobject fields that contain formulas return the value of the field at the time the soql or sosl query was issued. any changes to other fields that are used within the formula are not reflected in the formula field value until the record has been saved and re-queried in apex. like other read-only sobject fields, the values of the formula fields themselves cannot be changed in apex. accessing sobject fields through relationships sobject records represent relationships to other records with two fields: an id and an address that points to a representation of the associated sobject. for example, the contact sobject has both an accountid field of type id, and an account field of type account that points to the associated sobject record itself. the id field can be used to change the account with which the contact is associated, while the sobject reference field can be used to access data from the account. the reference field is only populated as the result of a soql or sosl query (see note). for example, the following apex code shows how an account and a contact can be associated with one another, and then how the contact can be used to modify a field on the account: note: to provide the most complete example, this code uses some elements that are described later in this guide: • for information on insert and update, see insert statement and update statement. account a = new account(name = 'acme'); insert a; // inserting the record automatically assigns a // value to its id field contact c = new contact(lastname = 'weissman'); c.accountid = a.id; // the new contact now points at the new account insert c; // a soql query accesses data for the inserted contact, // including a populated c.account field c = [select account.name from contact where id = :c.id]; // now fields in both records can be changed through the contact c.account.name = 'salesforce.com'; c.lastname = 'roth'; // to update the database, the two types of records must be // updated separately update c; // this only changes the contact's last name update c.account; // this updates the account name 160apex developer guide working with data in apex note: the expression c.account.name, and any other expression that traverses a relationship, displays slightly different characteristics when it is read as a value than when it is modified: • when being read as a value, if c.account is null, then c.account.name evaluates to null, but does not yield a nullpointerexception.
this design allows developers to navigate multiple relationships without the tedium of having to check for null values. • when being modified, if c.account is null, then c.account.namedoes yield a nullpointerexception. in sosl, you would access data for the inserted contact in a similar way to the select statement used in the previous soql example. list<list<sobject>> searchlist = [find 'acme' in all fields returning contact(id,account.name)] in addition, the sobject field key can be used with insert, update, or upsert to resolve foreign keys by external id. for example: account refacct = new account(externalid__c = '12345'); contact c = new contact(account = refacct, lastname = 'kay'); insert c; this inserts a new contact with the accountid equal to the account with the external_id equal to ‘12345’. if there is no such account, the insert fails. tip: the following code is equivalent to the code above. however, because it uses a soql query, it is not as efficient. if this code was called multiple times, it could reach the execution limit for the maximum number of soql queries. for more information on execution limits, see execution governors and limits on page 311. account refacct = [select id from account where externalid__c='12345']; contact c = new contact(account = refacct.id); insert c; understanding foreign key and parent-child relationship soql queries the select statement of a soql query can be any valid soql statement, including foreign key and parent-child record joins. if foreign key joins are included, the resulting sobjects can be referenced using normal field notation. for example: system.debug([select account.name from contact where firstname = 'caroline'].account.name); additionally, parent-child relationships in sobjects act as soql queries as well. for example: for (account a : [select id, name, (select lastname from contacts) from account where name = 'acme']) { contact[] cons = a.contacts; } //the following example also works because we limit to only 1 contact for (account a : [select id, name, (select lastname from contacts limit 1) from account where name = 'testagg']) { 161apex developer guide working with data in apex contact c = a.contacts; } working with soql aggregate functions aggregate functions in soql, such as sum() and max(), allow you to roll up and summarize your data in a query. for more information on aggregate functions, see aggregate functions in the salesforce soql and sosl reference guide. you can use aggregate functions without using a group by clause. for example, you could use the avg() aggregate function to find the average amount for all your opportunities. aggregateresult[] groupedresults = [select avg(amount)aver from opportunity]; object avgamount = groupedresults[0].get('aver'); note that any query that includes an aggregate function returns its results in an array of aggregateresult objects. aggregateresult is a read-only sobject and is only used for query results. aggregate functions become a more powerful tool to generate reports when you use them with a group by clause. for example, you could find the average amount for all your opportunities by campaign. aggregateresult[] groupedresults = [select campaignid, avg(amount) from opportunity group by campaignid]; for (aggregateresult ar : groupedresults) { system.debug('campaign id' + ar.get('campaignid')); system.debug('average amount' + ar.get('expr0')); } any aggregated field in a select list that does not have an alias automatically gets an implied alias with a format expri, where i denotes the order of the aggregated fields with no explicit aliases. the value of i starts at 0 and increments for every aggregated field with no explicit alias. for more information, see using aliases with group by in the salesforce soql and sosl reference guide. note: queries that include aggregate functions are still subject to the limit on total number of query rows. all aggregate functions other than count() or count(fieldname) include each row used by the aggregation as a query row for the purposes of limit tracking. for count() or count(fieldname) queries, limits are counted as one query row, unless the query contains a group by cl
ause, in which case one query row per grouping is consumed. working with very large soql queries important: where possible, we changed noninclusive terms to align with our company value of equality. we maintained certain terms to avoid any effect on customer implementations. your soql query sometimes returns so many sobjects that the limit on heap size is exceeded and an error occurs. to resolve, use a soql query for loop instead, since it can process multiple batches of records by using internal calls to query and querymore. for example, if the results are too large, this syntax causes a runtime exception: account[] accts = [select id from account]; 162apex developer guide working with data in apex instead, use a soql query for loop as in one of the following examples: // use this format if you are not executing dml statements // within the for loop for (account a : [select id, name from account where name like 'acme%']) { // your code without dml statements here } // use this format for efficiency if you are executing dml statements // within the for loop for (list<account> accts : [select id, name from account where name like 'acme%']) { for (account a : accts) { // your code here } update accts; } note: using the soql query within the for loop reduces the possibility of reaching the limit on heap size. however, this approach can result in more cpu cycles being used with increased dml calls. for more information, see soql for loops versus standard soql queries. the following example demonstrates a soql query for loop that’s used to mass update records. suppose that you want to change the last name of a contact in records for contacts whose first and last names match specified criteria: public void massupdate() { for (list<contact> contacts: [select firstname, lastname from contact]) { for(contact c : contacts) { if (c.firstname == 'barbara' && c.lastname == 'gordon') { c.lastname = 'wayne'; } } update contacts; } } instead of using a soql query in a for loop, the preferred method of mass updating records is to use batch apex, which minimizes the risk of hitting governor limits. for more information, see soql for loops on page 169. more efficient soql queries for best performance, soql queries must be selective, particularly for queries inside triggers. to avoid long execution times, the system can terminate nonselective soql queries. developers receive an error message when a non-selective query in a trigger executes against an object that contains more than 1 million records. to avoid this error, ensure that the query is selective. selective soql query criteria • a query is selective when one of the query filters is on an indexed field and the query filter reduces the resulting number of rows below a system-defined threshold. the performance of the soql query improves when two or more filters used in the where clause meet the mentioned conditions. 163apex developer guide working with data in apex • the selectivity threshold is 10% of the first million records and less than 5% of the records after the first million records, up to a maximum of 333,333 records. in some circumstances, for example with a query filter that is an indexed standard field, the threshold can be higher. also, the selectivity threshold is subject to change. custom index considerations for selective soql queries • the following fields are indexed by default. – primary keys (id, name, and ownerid fields) – foreign keys (lookup or master-detail relationship fields) – audit dates (createddate and systemmodstamp fields) – recordtype fields (indexed for all standard objects that feature them) – custom fields that are marked as external id or unique • fields not indexed by default are automatically indexed when the salesforce optimizer recognizes that an index can improve performance for frequently run queries. • salesforce support can add custom indexes on request for customers. • a custom index can't be created on these types of fields: multi-select picklists, currency fields in a multicurrency organization, long text fields, some formula fields, and binary fields (fields of type blob, file, or encrypted text.) new data types, typically complex ones, are periodically added to salesforce, and fields of these types don’t always allow custom indexing. • you can’t create custom indexes on formula fields that include invocations of the text function on pick
list fields. • typically, a custom index isn’t used in these cases. – the queried values exceed the system-defined threshold. – the filter operator is a negative operator such as not equal to (or !=), not contains, and not starts with. – the contains operator is used in the filter, and the number of rows to be scanned exceeds 333,333. the contains operator requires a full scan of the index. this threshold is subject to change. – you’re comparing with an empty value (name != ''). however, there are other complex scenarios in which custom indexes can’t be used. contact your salesforce representative if your scenario isn't covered by these cases or if you need further assistance with non-selective queries. examples of selective soql queries to better understand whether a query on a large object is selective or not, let's analyze some queries. for these queries, assume that there are more than 1 million records for the account sobject. these records include soft-deleted records, that is, deleted records that are still in the recycle bin. query 1: select id from account where id in (<list of account ids>) the where clause is on an indexed field (id). if select count() from account where id in (<list of account ids>) returns fewer records than the selectivity threshold, the index on id is used. this index is typically used when the list of ids contains only a few records. query 2: select id from account where name != '' since account is a large object even though name is indexed (primary key), this filter returns most of the records, making the query non-selective. 164apex developer guide working with data in apex query 3: select id from account where name != '' and customfield__c = 'valuea' here we have to see if any filter, when considered individually, is selective. as we saw in the previous example, the first filter isn't selective. so let's focus on the second one. if the count of records returned by select count() from account where customfield__c = 'valuea' is lower than the selectivity threshold, and customfield__c is indexed, the query is selective. using soql queries that return one record soql queries can be used to assign a single sobject value when the result list contains only one element. when the l-value of an expression is a single sobject type, apex automatically assigns the single sobject record in the query result list to the l-value. a runtime exception results if zero sobjects or more than one sobject is found in the list. for example: list<account> accts = [select id from account]; // these lines of code are only valid if one row is returned from // the query. notice that the second line dereferences the field from the // query without assigning it to an intermediary sobject variable. account acct = [select id from account]; string name = [select name from account].name; improve performance by avoiding null values in your soql and sosl queries, explicitly filtering out null values in the where clause allows salesforce to improve query performance. in the following example, any records where the thread__c value is null are eliminated from the search. public class tagws { /* getthreadtags * * a quick method to pull tags not in the existing list * */ public static webservice list<string> getthreadtags(string threadid, list<string> tags) { system.debug(logginglevel.debug,tags); list<string> retvals = new list<string>(); set<string> tagset = new set<string>(); set<string> origtagset = new set<string>(); origtagset.addall(tags); // note where clause optimizes search where thread__c is not null for(cso_casethread_tag__c t : [select name from cso_casethread_tag__c where thread__c = :threadid and thread__c != null]) { tagset.add(t.name); } 165apex developer guide working with data in apex for(string x : origtagset) { // return a minus version of it so the ui knows to clear it if(!tagset.contains(x)) retvals.add('-' + x); } for(string x : tagset) { // return a plus version so the ui knows it's new if(!origtagset.contains(x
)) retvals.add('+' + x); } return retvals; } } working with polymorphic relationships in soql queries a polymorphic relationship is a relationship between objects where a referenced object can be one of several different types. for example, the who relationship field of a task can be a contact or a lead. the following describes how to use soql queries with polymorphic relationships in apex. if you want more general information on polymorphic relationships, see understanding relationship fields and polymorphic fields in the soql and sosl reference. you can use soql queries that reference polymorphic fields in apex to get results that depend on the object type referenced by the polymorphic field. one approach is to filter your results using the type qualifier. this example queries events that are related to an account or opportunity via the what field. list<event> events = [select description from event where what.type in ('account', 'opportunity')]; another approach would be to use the typeof clause in the soql select statement. this example also queries events that are related to an account or opportunity via the what field. list<event> events = [select typeof what when account then phone when opportunity then amount end from event]; these queries return a list of sobjects where the relationship field references the desired object types. if you need to access the referenced object in a polymorphic relationship, you can use the instanceof keyword to determine the object type. the following example uses instanceof to determine whether an account or opportunity is related to an event. event myevent = eventfromquery; if (myevent.what instanceof account) { // myevent.what references an account, so process accordingly } else if (myevent.what instanceof opportunity) { // myevent.what references an opportunity, so process accordingly } note that you must assign the referenced sobject that the query returns to a variable of the appropriate type before you can pass it to another method. the following example 1. queries for user or group owners of merchandise__c custom objects using a soql query with a typeof clause 2. uses instanceof to determine the owner type 3. assigns the owner objects to user or group type variables before passing them to utility methods public class polymorphismexampleclass { // utility method for a user 166apex developer guide working with data in apex public static void processuser(user theuser) { system.debug('processed user'); } // utility method for a group public static void processgroup(group thegroup) { system.debug('processed group'); } public static void processownersofmerchandise() { // select records based on the owner polymorphic relationship field list<merchandise__c> merchandiselist = [select typeof owner when user then lastname when group then email end from merchandise__c]; // we now have a list of merchandise__c records owned by either a user or group for (merchandise__c merch: merchandiselist) { // we can use instanceof to check the polymorphic relationship type // note that we have to assign the polymorphic reference to the appropriate // sobject type before passing to a method if (merch.owner instanceof user) { user userowner = merch.owner; processuser(userowner); } else if (merch.owner instanceof group) { group groupowner = merch.owner; processgroup(groupowner); } } } } using apex variables in soql and sosl queries soql and sosl statements in apex can reference apex code variables and expressions if they’re preceded by a colon (:). this use of a local code variable within a soql or sosl statement is called a bind. the apex parser first evaluates the local variable in code context before executing the soql or sosl statement. bind expressions can be used as: • the search string in find clauses. • the filter literals in where clauses. • the value of the in or not in operator in where clauses, allowing filtering on a dynamic set of values. note that this is of particular use with a list of ids or strings, though it works with lists of any type. • the division names in with division clauses. • the numeric value in limit clauses. • the numeric value in offset clauses. for example: account a = new account(name='xxx'); insert a; account b; // a simple bind b = [select id from account where id = :a.
id]; // a bind with arithmetic 167apex developer guide working with data in apex b = [select id from account where name = :('x' + 'xx')]; string s = 'xxx'; // a bind with expressions b = [select id from account where name = :'xxxx'.substring(0,3)]; // a bind with includes clause b = [select id from account where :a.type includes (‘customer – direct; customer – channel’)]; // a bind with an expression that is itself a query result b = [select id from account where name = :[select name from account where id = :a.id].name]; contact c = new contact(lastname='xxx', accountid=a.id); insert new contact[]{c, new contact(lastname='yyy', accountid=a.id)}; // binds in both the parent and aggregate queries b = [select id, (select id from contacts where id = :c.id) from account where id = :a.id]; // one contact returned contact d = b.contacts; // a limit bind integer i = 1; b = [select id from account limit :i]; // an offset bind integer offsetval = 10; list<account> offsetlist = [select id from account offset :offsetval]; // an in-bind with an id list. note that a list of sobjects // can also be used--the ids of the objects are used for // the bind contact[] cc = [select id from contact limit 2]; task[] tt = [select id from task where whoid in :cc]; // an in-bind with a string list string[] ss = new string[]{'a', 'b'}; account[] aa = [select id from account where accountnumber in :ss]; // a sosl query with binds in all possible clauses string mystring1 = 'aaa'; string mystring2 = 'bbb'; 168apex developer guide working with data in apex integer myint3 = 11; string mystring4 = 'ccc'; integer myint5 = 22; list<list<sobject>> searchlist = [find :mystring1 in all fields returning account (id, name where name like :mystring2 limit :myint3), contact, opportunity, lead with division =:mystring4 limit :myint5]; note: apex bind variables aren’t supported for the units parameter in the distance function. this query doesn’t work. string units = 'mi'; list<account> accountlist = [select id, name, billinglatitude, billinglongitude from account where distance(my_location_field__c, geolocation(10,10), :units) < 10]; querying all records with a soql statement soql statements can use the all rows keywords to query all records in an organization, including deleted records and archived activities. for example: system.assertequals(2, [select count() from contact where accountid = a.id all rows]); you can use all rows to query records in your organization's recycle bin. you cannot use the all rows keywords with the for update keywords. soql for loops soql for loops iterate over all of the sobject records returned by a soql query. the syntax of a soql for loop is either: for (variable : [soql_query]) { code_block } or for (variable_list : [soql_query]) { code_block } 169apex developer guide working with data in apex both variable and variable_list must be of the same type as the sobjects that are returned by the soql_query. as in standard soql queries, the [soql_query] statement can refer to code expressions in their where clauses using the : syntax. for example: string s = 'acme'; for (account a : [select id, name from account where name like :(s+'%')]) { // your code } the following example combines creating a list from a soql query, with the dml update method. // create a list of account records from a soql query list<account> accs = [select id, name from account where
name = 'siebel']; // loop through the list and update the name field for(account a : accs){ a.name = 'oracle'; } // update the database update accs; soql for loops versus standard soql queries soql for loops differ from standard soql statements because of the method they use to retrieve sobjects. while the standard queries discussed in soql and sosl queries can retrieve either the count of a query or a number of object records, soql for loops retrieve all sobjects, using efficient chunking with calls to the query and querymore methods of soap api. developers can avoid the limit on heap size by using a soql for loop to process query results that return multiple records. however, this approach can result in more cpu cycles being used. see total heap size. queries including an aggregate function don't support querymore. a run-time exception occurs if you use a query containing an aggregate function that returns more than 2,000 rows in a for loop. soql for loop formats soql for loops can process records one at a time using a single sobject variable, or in batches of 200 sobjects at a time using an sobject list: • the single sobject format executes the for loop's <code_block> one time per sobject record. consequently, it’s easy to understand and use, but is grossly inefficient if you want to use data manipulation language (dml) statements within the for loop body. each dml statement ends up processing only one sobject at a time. • the sobject list format executes the for loop's <code_block> one time per list of 200 sobjects. consequently, it’s a little more difficult to understand and use, but is the optimal choice if you must use dml statements within the for loop body. each dml statement can bulk process a list of sobjects at a time. for example, the following code illustrates the difference between the two types of soql query for loops: // create a savepoint because the data should not be committed to the database savepoint sp = database.setsavepoint(); insert new account[]{new account(name = 'yyy'), new account(name = 'yyy'), new account(name = 'yyy')}; 170apex developer guide working with data in apex // the single sobject format executes the for loop once per returned record integer i = 0; for (account tmp : [select id from account where name = 'yyy']) { i++; } system.assert(i == 3); // since there were three accounts named 'yyy' in the // database, the loop executed three times // the sobject list format executes the for loop once per returned batch // of records i = 0; integer j; for (account[] tmp : [select id from account where name = 'yyy']) { j = tmp.size(); i++; } system.assert(j == 3); // the lt should have contained the three accounts // named 'yyy' system.assert(i == 1); // since a single batch can hold up to 200 records and, // only three records should have been returned, the // loop should have executed only once // revert the database to the original state database.rollback(sp); note: • the break and continue keywords can be used in both types of inline query for loop formats. when using the sobject list format, continue skips to the next list of sobjects. • dml statements can only process up to 10,000 records at a time, and sobject list for loops process records in batches of 200. consequently, if you’re inserting, updating, or deleting more than one record per returned record in an sobject list for loop, it’s possible to encounter runtime limit’s errors. see execution governors and limits. • you may get a queryexception in a soql for loop with the message aggregate query has too many rows for direct assignment, use for loop. this exception is sometimes thrown when accessing a large set of child records (200 or more) of a retrieved sobject inside the loop, or when getting the size of such a record set. for example, the query in the following soql for loop retrieves child contacts for a particular account. if this account contains more than 200 child contacts, the statements in the for loop cause an exception. for (account acct : [select id, name, (select id, name from contacts) from account where id in ('<id value>')])
{ list<contact> contactlist = acct.contacts; // causes an error integer count = acct.contacts.size(); // causes an error } to avoid getting this exception, use a for loop to iterate over the child records, as follows. for (account acct : [select id, name, (select id, name from contacts) from account where id in ('<id value>')]) { integer count=0; for (contact c : acct.contacts) { count++; } } 171apex developer guide working with data in apex sobject collections you can manage sobjects in lists, sets, and maps. in this section: lists of sobjects lists can contain sobjects among other types of elements. lists of sobjects can be used for bulk processing of data. sorting lists of sobjects using the list.sort method, you can sort lists of sobjects. expanding sobject and list expressions sets of objects sets can contain sobjects among other types of elements. maps of sobjects map keys and values can be of any data type, including sobject types, such as account. lists of sobjects lists can contain sobjects among other types of elements. lists of sobjects can be used for bulk processing of data. you can use a list to store sobjects. lists are useful when working with soql queries. soql queries return sobject data and this data can be stored in a list of sobjects. also, you can use lists to perform bulk operations, such as inserting a list of sobjects with one call. to declare a list of sobjects, use the list keyword followed by the sobject type within <> characters. for example: // create an empty list of accounts list<account> mylist = new list<account>(); auto-populating a list from a soql query you can assign a list variable directly to the results of a soql query. the soql query returns a new list populated with the records returned. make sure that the declared list variable contains the same sobject that is being queried. or you can use the generic sobject data type. this example shows how to declare and assign a list of accounts to the return value of a soql query. the query returns up to 1,000 returns account records containing the id and name fields. // create a list of account records from a soql query list<account> accts = [select id, name from account limit 1000]; adding and retrieving list elements as with lists of primitive data types, you can access and set elements of sobject lists using the list methods provided by apex. for example: list<account> mylist = new list<account>(); // define a new list account a = new account(name='acme'); // create the account first mylist.add(a); // add the account sobject account a2 = mylist.get(0); // retrieve the element at index 0 172apex developer guide working with data in apex bulk processing you can bulk-process a list of sobjects by passing a list to the dml operation. this example shows how you can insert a list of accounts. // define the list list<account> acctlist = new list<account>(); // create account sobjects account a1 = new account(name='account1'); account a2 = new account(name='account2'); // add accounts to the list acctlist.add(a1); acctlist.add(a2); // bulk insert the list insert acctlist; note: if you perform a bulk insert of knowledge article versions, make the ownerid of all records the same. record id generation apex automatically generates ids for each object in an sobject list that was inserted or upserted using dml. therefore, a list that contains more than one instance of an sobject cannot be inserted or upserted even if it has a null id. this situation would imply that two ids would need to be written to the same structure in memory, which is illegal. for example, the insert statement in the following block of code generates a listexception because it tries to insert a list with two references to the same sobject (a): try { // create a list with two references to the same sobject element account a = new account(); list<account> accs = new list<account>{a, a}; // attempt to insert it... insert accs
; // will not get here system.assert(false); } catch (listexception e) { // but will get here } using array notation for one-dimensional lists of sobjects alternatively, you can use the array notation (square brackets) to declare and reference lists of sobjects. this example declares a list of accounts using the array notation. account[] accts = new account[1]; this example adds an element to the list using square brackets. accts[0] = new account(name='acme2'); these examples also use the array notation with sobject lists. 173apex developer guide working with data in apex example description defines an account list with no elements. list<account> accts = new account[]{}; defines an account list with memory allocated for three accounts: list<account> accts = new account[] a new account object in the first position, null in the second, {new account(), null, new and another new account object in the third. account()}; defines the contact list with a new list. list<contact> contacts = new list<contact> (otherlist); sorting lists of sobjects using the list.sort method, you can sort lists of sobjects. for sobjects, sorting is in ascending order and uses a sequence of comparison steps outlined in the next section. alternatively, you can also implement a custom sort order for sobjects by wrapping your sobject in an apex class and implementing the comparable interface, as shown in custom sort order of sobjects. default sort order of sobjects the list.sort method sorts sobjects in ascending order and compares sobjects using an ordered sequence of steps that specify the labels or fields used. the comparison starts with the first step in the sequence and ends when two sobjects are sorted using specified labels or fields. the following is the comparison sequence used: 1. the label of the sobject type. for example, an account sobject will appear before a contact. 2. the name field, if applicable. for example, if the list contains two accounts named alpha and beta, account alpha comes before account beta. 3. standard fields, starting with the fields that come first in alphabetical order, except for the id and name fields. for example, if two accounts have the same name, the first standard field used for sorting is accountnumber. 4. custom fields, starting with the fields that come first in alphabetical order. for example, suppose two accounts have the same name and identical standard fields, and there are two custom fields, fielda and fieldb, the value of fielda is used first for sorting. not all steps in this sequence are necessarily carried out. for example, if a list contains two sobjects of the same type and with unique name values, they’re sorted based on the name field and sorting stops at step 2. otherwise, if the names are identical or the sobject doesn’t have a name field, sorting proceeds to step 3 to sort by standard fields. for text fields, the sort algorithm uses the unicode sort order. also, empty fields precede non-empty fields in the sort order. 174apex developer guide working with data in apex here’s an example of sorting a list of account sobjects. this example shows how the name field is used to place the acme account ahead of the two sforce accounts in the list. since there are two accounts named sforce, the industry field is used to sort these remaining accounts because the industry field comes before the site field in alphabetical order. account[] acctlist = new list<account>(); acctlist.add( new account( name='sforce', industry='biotechnology', site='austin')); acctlist.add(new account( name='sforce', industry='agriculture', site='new york')); acctlist.add(new account( name='acme')); system.debug(acctlist); acctlist.sort(); assert.areequal('acme', acctlist[0].name); assert.areequal('sforce', acctlist[1].name); assert.areequal('agriculture', acctlist[1].industry); assert.areequal('sforce', acctlist[2].name); assert.areequal('biotechnology', acctlist[2].industry); system.debug(acctlist); this example is similar to the previous one, except
that it uses the merchandise__c custom object. this example shows how the name field is used to place the notebooks merchandise ahead of pens in the list. because there are two merchandise sobjects with the name field value of pens, the description field is used to sort these remaining merchandise items because the description field comes before the price and total_inventory fields in alphabetical order. merchandise__c[] merchlist = new list<merchandise__c>(); merchlist.add( new merchandise__c( name='pens', description__c='red pens', price__c=2, total_inventory__c=1000)); merchlist.add( new merchandise__c( name='notebooks', description__c='cool notebooks', price__c=3.50, total_inventory__c=2000)); merchlist.add( new merchandise__c( name='pens', description__c='blue pens', price__c=1.75, total_inventory__c=800)); system.debug(merchlist); merchlist.sort(); assert.areequal('notebooks', merchlist[0].name); assert.areequal('pens', merchlist[1].name); assert.areequal('blue pens', merchlist[1].description__c); assert.areequal('pens', merchlist[2].name); assert.areequal('red pens', merchlist[2].description__c); system.debug(merchlist); 175apex developer guide working with data in apex custom sort order of sobjects to implement a custom sort order for sobjects in lists, create a wrapper class for the sobject and implement the comparable interface. the wrapper class contains the sobject in question and implements the compareto method, in which you specify the sort logic. this example shows how to create a wrapper class for opportunity. the implementation of the compareto method in this class compares two opportunities based on the amount field—the class member variable contained in this instance, and the opportunity object passed into the method. public class opportunitywrapper implements comparable { public opportunity oppy; // constructor public opportunitywrapper(opportunity op) { // guard against wrapping a null if(op == null) { exception ex = new nullpointerexception(); ex.setmessage('opportunity argument cannot be null'); throw ex; } oppy = op; } // compare opportunities based on the opportunity amount. public integer compareto(object compareto) { // cast argument to opportunitywrapper opportunitywrapper comparetooppy = (opportunitywrapper)compareto; // the return value of 0 indicates that both elements are equal. integer returnvalue = 0; if ((oppy.amount == null) && (comparetooppy.oppy.amount == null)) { // both wrappers have null amounts returnvalue = 0; } else if ((oppy.amount == null) && (comparetooppy.oppy.amount != null)){ // nulls-first implementation returnvalue = -1; } else if ((oppy.amount != null) && (comparetooppy.oppy.amount == null)){ // nulls-first implementation returnvalue = 1; } else if (oppy.amount > comparetooppy.oppy.amount) { // set return value to a positive value. returnvalue = 1; } else if (oppy.amount < comparetooppy.oppy.amount) { // set return value to a negative value. returnvalue = -1; } return returnvalue; } } this example provides a test for the opportunitywrapper class. it sorts a list of opportunitywrapper objects and verifies that the list elements are sorted by the opportunity amount. @istest private class opportunitywrappertest { 176apex developer guide working with data in apex static testmethod void test1() { // add the opportunity wrapper objects to a list. opportunitywrapper[] oppylist = new list<opportunitywrapper>(); date closedate = date.today().adddays(10); oppylist.add( new opportunitywrapper(new opportunity( name='edge installation', closedate=closedate, stagename='prospecting', amount=50000))); oppylist.add( new opportunitywrapper(new opportunity( name='united oil installations', closedate=closedate