text
stringlengths
24
5.1k
the beginning of the string using a case-insensitive match. signature public string removestartignorecase(string substring) parameters substring type: string return value type: string example string s1 = 'salesforce and force.com'; string s2 = s1.removestartignorecase('sales'); system.assertequals( 'force and force.com', s2); repeat(numberoftimes) returns the current string repeated the specified number of times. signature public string repeat(integer numberoftimes) 3394apex reference guide string class parameters numberoftimes type: integer return value type: string example string s1 = 'sfdc'; string s2 = s1.repeat(2); system.assertequals('sfdcsfdc', s2); repeat(separator, numberoftimes) returns the current string repeated the specified number of times using the specified separator to separate the repeated strings. signature public string repeat(string separator, integer numberoftimes) parameters separator type: string numberoftimes type: integer return value type: string example string s1 = 'sfdc'; string s2 = s1.repeat('-', 2); system.assertequals( 'sfdc-sfdc', s2); replace(target, replacement) replaces each substring of a string that matches the literal target sequence target with the specified literal replacement sequence replacement. signature public string replace(string target, string replacement) 3395apex reference guide string class parameters target type: string replacement type: string return value type: string example string s1 = 'abcdbca'; string target = 'bc'; string replacement = 'xy'; string s2 = s1.replace(target, replacement); system.assertequals('axydxya', s2); replaceall(regexp, replacement) replaces each substring of a string that matches the regular expression regexp with the replacement sequence replacement. signature public string replaceall(string regexp, string replacement) parameters regexp type: string replacement type: string return value type: string usage see the java pattern class for information on regular expressions. example string s1 = 'a b c 5 xyz'; string regexp = '[a-za-z]'; string replacement = '1'; string s2 = s1.replaceall(regexp, replacement); system.assertequals('1 1 1 5 111', s2); 3396apex reference guide string class replacefirst(regexp, replacement) replaces the first substring of a string that matches the regular expression regexp with the replacement sequence replacement. signature public string replacefirst(string regexp, string replacement) parameters regexp type: string replacement type: string return value type: string usage see the java pattern class for information on regular expressions. example string s1 = 'a b c 11 xyz'; string regexp = '[a-za-z]{2}'; string replacement = '2'; string s2 = s1.replacefirst(regexp, replacement); system.assertequals('a b c 11 2z', s2); reverse() returns a string with all the characters reversed. signature public string reverse() return value type: string right(length) returns the rightmost characters of the current string of the specified length. signature public string right(integer length) 3397apex reference guide string class parameters length type: integer if length is greater than the string size, the entire string is returned. return value type: string example string s1 = 'hello max'; string s2 = s1.right(3); system.assertequals( 'max', s2); rightpad(length) returns the current string padded with spaces on the right and of the specified length. signature public string rightpad(integer length) parameters length type: integer if length is less than or equal to the current string size, the entire string is returned without space padding. return value type: string example string s1 = 'abc'; string s2 = s1.rightpad(5); system.assertequals( 'abc ', s2); rightpad(length, padstr) returns the current string
padded with string padstr on the right and of the specified length. 3398apex reference guide string class signature public string rightpad(integer length, string padstr) parameters length type: integer padstr type: string string to pad with; if null or empty treated as single blank. usage if length is less than or equal to the current string size, the entire string is returned without space padding. return value type: string example string s1 = 'abc'; string s2 = 'xy'; string s3 = s1.rightpad(7, s2); system.assertequals('abcxyxy', s3); split(regexp) returns a list that contains each substring of the string that is terminated by either the regular expression regexp or the end of the string. signature public string[] split(string regexp) parameters regexp type: string return value type: string[] note: in api version 34.0 and earlier, a zero-width regexp value produces an empty list item at the beginning of the method’s output. usage see the java pattern class for information on regular expressions. 3399apex reference guide string class the substrings are placed in the list in the order in which they occur in the string.if regexp does not match any part of the string, the resulting list has just one element containing the original string. example in the following example, a string is split using a backslash as a delimiter. public string splitpath(string filename) { if (filename == null) return null; list<string> parts = filename.split('\\\\'); filename = parts[parts.size()-1]; return filename; } // for example, if the file path is e:\\processed\\ppdsf100111.csv // this method splits the path and returns the last part. // returned filename is ppdsf100111.csv split(regexp, limit) returns a list that contains each substring of the string that is terminated by either the regular expression regexp or the end of the string. signature public string[] split(string regexp, integer limit) parameters regexp type: string a regular expression. limit type: integer return value type: string[] note: in api version 34.0 and earlier, a zero-width regexp value produces an empty list item at the beginning of the method’s output. usage the optional limit parameter controls the number of times the pattern is applied and therefore affects the length of the list. • if limit is greater than zero: – the pattern is applied a maximum of (limit – 1) times. – the list’s length is no greater than limit. – the list’s last entry contains all input beyond the last matched delimiter. 3400apex reference guide string class • if limit is non-positive, the pattern is applied as many times as possible, and the list can have any length. • if limit is zero, the pattern is applied as many times as possible, the list can have any length, and trailing empty strings are discarded. example for example, for string s = 'boo:and:moo': • s.split(':', 2) results in {'boo', 'and:moo'} • s.split(':', 5) results in {'boo', 'and', 'moo'} • s.split(':', -2) results in {'boo', 'and', 'moo'} • s.split('o', 5) results in {'b', '', ':and:m', '', ''} • s.split('o', -2) results in {'b', '', ':and:m', '', ''} • s.split('o', 0) results in {'b', '', ':and:m'} splitbycharactertype() splits the current string by character type and returns a list of contiguous character groups of the same type as complete tokens. signature public list<string> splitbycharactertype() return value type: list<string> usage for more information about the character types used, see java.lang.character.gettype(char). example string s1 = 'lightning.platform'; list<string> ls = s1.splitbycharactertype(); system.debug(ls); // writes this output: // (l, ightning, ., platform
) splitbycharactertypecamelcase() splits the current string by character type and returns a list of contiguous character groups of the same type as complete tokens, with the following exception: the uppercase character, if any, immediately preceding a lowercase character token belongs to the following character token rather than to the preceding. signature public list<string> splitbycharactertypecamelcase() 3401apex reference guide string class return value type: list<string> usage for more information about the character types used, see java.lang.character.gettype(char). example string s1 = 'lightning.platform'; list<string> ls = s1.splitbycharactertypecamelcase(); system.debug(ls); // writes this output: // (lightning, ., platform) startswith(prefix) returns true if the string that called the method begins with the specified prefix. signature public boolean startswith(string prefix) parameters prefix type: string return value type: boolean example string s1 = 'ae86 vs ek9'; system.assert(s1.startswith('ae86')); startswithignorecase(prefix) returns true if the current string begins with the specified prefix regardless of the prefix case. signature public boolean startswithignorecase(string prefix) parameters prefix type: string 3402apex reference guide string class return value type: boolean example string s1 = 'ae86 vs ek9'; system.assert(s1.startswithignorecase('ae86')); striphtmltags() removes html markup and returns plain text. signature public string striphtmltags(string htmlinput) return value type: string usage warning: the striphtmltags function does not recursively strip tags; therefore, tags may still exist in the returned string. do not use the striphtmltags function to sanitize input for inclusion as a raw html page. the unescaped output is not considered safe to include in an html document. the function will be deprecated in a future release. example string s1 = '<b>hello world</b>'; string s2 = s1.striphtmltags(); system.assertequals( 'hello world', s2); substring(startindex) returns a new string that begins with the character at the specified zero-based startindex and extends to the end of the string. signature public string substring(integer startindex) parameters startindex type: integer return value type: string 3403apex reference guide string class example string s1 = 'hamburger'; system.assertequals('burger', s1.substring(3)); substring(startindex, endindex) returns a new string that begins with the character at the specified zero-based startindex and extends to the character at endindex - 1. signature public string substring(integer startindex, integer endindex) parameters startindex type: integer endindex type: integer return value type: string example 'hamburger'.substring(4, 8); // returns "urge" 'smiles'.substring(1, 5); // returns "mile" substringafter(separator) returns the substring that occurs after the first occurrence of the specified separator. signature public string substringafter(string separator) parameters separator type: string return value type: string 3404apex reference guide string class example string s1 = 'salesforce.lightning.platform'; string s2 = s1.substringafter('.'); system.assertequals( 'lightning.platform', s2); substringafterlast(separator) returns the substring that occurs after the last occurrence of the specified separator. signature public string substringafterlast(string separator) parameters separator type: string return value type: string example string s1 = 'salesforce.lightning.platform'; string s2 = s1.substringafterlast('.'); system.assertequals( 'platform', s2); substringbefore(separator) returns the substring that occurs before the first occurrence of the specified separator. signature public string substringbefore(string separator) parameters separator type: string return value type: string
3405apex reference guide string class example string s1 = 'salesforce.lightning.platform'; string s2 = s1.substringbefore('.'); system.assertequals( 'salesforce', s2); substringbeforelast(separator) returns the substring that occurs before the last occurrence of the specified separator. signature public string substringbeforelast(string separator) parameters separator type: string return value type: string example string s1 = 'salesforce.lightning.platform'; string s2 = s1.substringbeforelast('.'); system.assertequals( 'salesforce.lightning', s2); substringbetween(tag) returns the substring that occurs between two instances of the specified tag string. signature public string substringbetween(string tag) parameters tag type: string return value type: string 3406apex reference guide string class example string s1 = 'tagyellowtag'; string s2 = s1.substringbetween('tag'); system.assertequals('yellow', s2); substringbetween(open, close) returns the substring that occurs between the two specified strings. signature public string substringbetween(string open, string close) parameters open type: string close type: string return value type: string example string s1 = 'xyellowy'; string s2 = s1.substringbetween('x','y'); system.assertequals( 'yellow', s2); swapcase() swaps the case of all characters and returns the resulting string by using the default (english us) locale. signature public string swapcase() return value type: string usage upper case and title case converts to lower case, and lower case converts to upper case. 3407apex reference guide string class example string s1 = 'force.com'; string s2 = s1.swapcase(); system.assertequals('force.com', s2); tolowercase() converts all of the characters in the string to lowercase using the rules of the default (english us) locale. signature public string tolowercase() return value type: string example string s1 = 'this is hard to read'; system.assertequals('this is hard to read', s1.tolowercase()); tolowercase(locale) converts all of the characters in the string to lowercase using the rules of the specified locale. signature public string tolowercase(string locale) parameters locale type: string return value type: string example // example in turkish // an uppercase dotted "i", \u0304, which is i̇ // note this contains both a i̇ as well as a i string s1 = 'kiymetli̇'; string s1lower = s1.tolowercase('tr'); // dotless lowercase "i", \u0131, which is ı // note this has both a i and ı string expected = 'kıymetli'; 3408apex reference guide string class system.assertequals(expected, s1lower); // note if this was done in tolowercase(‘en’), it would output ‘kiymetli’ touppercase() converts all of the characters in the string to uppercase using the rules of the default (english us) locale. signature public string touppercase() return value type: string example string mystring1 = 'abcd'; string mystring2 = 'abcd'; mystring1 = mystring1.touppercase(); boolean result = mystring1.equals(mystring2); system.assertequals(result, true); touppercase(locale) converts all of the characters in the string to the uppercase using the rules of the specified locale. signature public string touppercase(string locale) parameters locale type: string return value type: string example // example in turkish // dotless lowercase "i", \u0131, which is ı // note this has both a i and ı string s1 = 'imkansız'; string s1upper = s1.touppercase
('tr'); // an uppercase dotted "i", \u0304, which is i̇ // note this contains both a i̇ as well as a i 3409apex reference guide string class string expected = 'i̇mkansiz'; system.assertequals(expected, s1upper); trim() returns a copy of the string that no longer contains any leading or trailing white space characters. signature public string trim() return value type: string usage leading and trailing ascii control characters such as tabs and newline characters are also removed. white space and control characters that aren’t at the beginning or end of the sentence aren’t removed. example string s1 = ' hello! '; string trimmed = s1.trim(); system.assertequals('hello!', trimmed); uncapitalize() returns the current string with the first letter in lowercase. signature public string uncapitalize() return value type: string example string s1 = 'hello max'; string s2 = s1.uncapitalize(); system.assertequals( 'hello max', s2); 3410apex reference guide string class unescapecsv() returns a string representing an unescaped csv column. signature public string unescapecsv() return value type: string usage if the string is enclosed in double quotes and contains a comma, newline or double quote, quotes are removed. also, any double quote escaped characters (a pair of double quotes) are unescaped to just one double quote. if the string is not enclosed in double quotes, or is and does not contain a comma, newline or double quote, it is returned unchanged. example string s1 = '"max1, ""max2"""'; string s2 = s1.unescapecsv(); system.assertequals( 'max1, "max2"', s2); unescapeecmascript() unescapes any ecmascript literals found in the string. signature public string unescapeecmascript() return value type: string example string s1 = '\"3.8\",\"3.9\"'; string s2 = s1.unescapeecmascript(); system.assertequals( '"3.8","3.9"', s2); 3411apex reference guide string class unescapehtml3() unescapes the characters in a string using html 3.0 entities. signature public string unescapehtml3() return value type: string example string s1 = '&quot;&lt;black&amp;white&gt;&quot;'; string s2 = s1.unescapehtml3(); system.assertequals( '"<black&white>"', s2); unescapehtml4() unescapes the characters in a string using html 4.0 entities. signature public string unescapehtml4() return value type: string usage if an entity isn’t recognized, it is kept as is in the returned string. example string s1 = '&quot;&lt;black&amp;white&gt;&quot;'; string s2 = s1.unescapehtml4(); system.assertequals( '"<black&white>"', s2); 3412apex reference guide string class unescapejava() returns a string whose java literals are unescaped. literals unescaped include escape sequences for quotes (\\") and control characters, such as tab (\\t), and carriage return (\\n). signature public string unescapejava() return value type: string the unescaped string. example string s = 'company: \\"salesforce.com\\"'; string unescapedstr = s.unescapejava(); system.assertequals('company: "salesforce.com"', unescapedstr); unescapeunicode() returns a string whose escaped unicode characters are unescaped. signature public string unescapeunicode() return value type: string the unescaped string. example string s = 'de onde voc\u00ea \u00e9?'; string unescapedstr = s.unescapeunicode(); system.assertequals('de onde você é?', unescaped
str); unescapexml() unescapes the characters in a string using xml entities. signature public string unescapexml() return value type: string 3413apex reference guide string class usage supports only the five basic xml entities (gt, lt, quot, amp, apos). does not support dtds or external entities. example string s1 = '&quot;&lt;black&amp;white&gt;&quot;'; string s2 = s1.unescapexml(); system.assertequals( '"<black&white>"', s2); valueof(datetoconvert) returns a string that represents the specified date in the standard “yyyy-mm-dd” format. signature public static string valueof(date datetoconvert) parameters datetoconvert type: date return value type: string example date mydate = date.today(); string sdate = string.valueof(mydate); valueof(datetimetoconvert) returns a string that represents the specified datetime in the standard “yyyy-mm-dd hh:mm:ss” format for the local time zone. signature public static string valueof(datetime datetimetoconvert) parameters datetimetoconvert type: datetime 3414apex reference guide string class return value type: string example datetime dt = datetime.newinstance(1996, 6, 23); string sdatetime = string.valueof(dt); system.assertequals('1996-06-23 00:00:00', sdatetime); valueof(decimaltoconvert) returns a string that represents the specified decimal. signature public static string valueof(decimal decimaltoconvert) parameters decimaltoconvert type: decimal return value type: string example decimal dec = 3.14159265; string sdecimal = string.valueof(dec); system.assertequals('3.14159265', sdecimal); valueof(doubletoconvert) returns a string that represents the specified double. signature public static string valueof(double doubletoconvert) parameters doubletoconvert type: double return value type: string 3415apex reference guide string class example double mydouble = 12.34; string mystring = string.valueof(mydouble); system.assertequals( '12.34', mystring); valueof(integertoconvert) returns a string that represents the specified integer. signature public static string valueof(integer integertoconvert) parameters integertoconvert type: integer return value type: string example integer myinteger = 22; string sinteger = string.valueof(myinteger); system.assertequals('22', sinteger); valueof(longtoconvert) returns a string that represents the specified long. signature public static string valueof(long longtoconvert) parameters longtoconvert type: long return value type: string 3416apex reference guide string class example long mylong = 123456789; string slong = string.valueof(mylong); system.assertequals('123456789', slong); valueof(toconvert) returns a string representation of the specified object argument. signature public static string valueof(object toconvert) parameters toconvert type: object return value type: string usage if the argument is not a string, the valueof method converts it into a string by calling the tostring method on the argument, if available, or any overridden tostring method if the argument is a user-defined type. otherwise, if no tostring method is available, it returns a string representation of the argument. example list<integer> ls = new list<integer>(); ls.add(10); ls.add(20); string strlist = string.valueof(ls); system.assertequals( '(10, 20)', strlist); valueofgmt(datetimetoconvert) returns a string that represents the specified datetime in the standard “yyyy-mm-dd hh:mm:ss” format for the gmt time zone. signature public static string valueofgmt(datetime datetimetocon
vert) 3417apex reference guide stubprovider interface parameters datetimetoconvert type: datetime return value type: string example // for a pst timezone: datetime dt = datetime.newinstance(2001, 9, 14); string sdatetime = string.valueofgmt(dt); system.assertequals('2001-09-14 07:00:00', sdatetime); stubprovider interface stubprovider is a callback interface that you can use as part of the apex stub api to implement a mocking framework. use this interface with the test.createstub() method to create stubbed apex objects for testing. namespace system usage the stubprovider interface allows you to define the behavior of a stubbed apex class. the interface specifies a single method that requires implementing: handlemethodcall(). you specify the behavior of each method of the stubbed class in the handlemethodcall() method. in your apex test, you create a stubbed object using the test.createstub() method. when you invoke methods on the stubbed object, stubprovider.handlemethodcall() is called, which performs the behavior that you’ve specified for each method. in this section: stubprovider methods see also: apex developer guide: build a mocking framework with the stub api createstub(parenttype, stubprovider) stubprovider methods the following are methods for stubprovider. 3418apex reference guide stubprovider interface in this section: handlemethodcall(stubbedobject, stubbedmethodname, returntype, listofparamtypes, listofparamnames, listofargs) use this method to define the behavior of each method of a stubbed class. handlemethodcall(stubbedobject, stubbedmethodname, returntype, listofparamtypes, listofparamnames, listofargs) use this method to define the behavior of each method of a stubbed class. signature public object handlemethodcall(object stubbedobject, string stubbedmethodname, system.type returntype, list<system.type> listofparamtypes, list<string> listofparamnames, list<object> listofargs) parameters stubbedobject type: object the stubbed object. stubbedmethodname type: string the name of the invoked method. returntype type: system.type the return type of the invoked method. listofparamtypes type: list<system.type> a list of the parameter types of the invoked method. listofparamnames type: list<string> a list of the parameter names of the invoked method. listofargs type: list<object> the actual argument values passed into this method at runtime. return value type: object 3419apex reference guide system class usage you can use the parameters passed into this method to identify which method on the stubbed object was invoked. then you can define the behavior for each identified method. see also: apex developer guide: build a mocking framework with the stub api system class contains methods for system operations, such as writing debug messages and scheduling jobs. namespace system system methods the following are methods for system. all methods are static. in this section: abortjob(jobid) stops the specified job. the stopped job is still visible in the job queue in the salesforce user interface. assert(condition, msg) asserts that the specified condition is true. if it isn’t , a fatal error is returned that causes code execution to halt. assertequals(expected, actual, msg) asserts that the first two arguments are the same. if they aren’t, a fatal error is returned that causes code execution to halt. assertnotequals(expected, actual, msg) asserts that the first two arguments are different. if they’re the same, a fatal error is returned that causes code execution to halt. currentpagereference() returns a reference to the current page. this is used with visualforce pages. currenttimemillis() returns the current time in milliseconds, which is expressed as the difference between the current time and midnight, january 1, 1970 utc. debug(msg) writes the specified message, in string format, to the execution debug log. the debug log level is used. debug(loglevel, msg) writes the specified message, in string format, to the execution debug log with the specified log level. enqueuejob(queueableobj) adds a job to the apex job queue
that corresponds to the specified queueable class and returns the job id. enqueuejob(queueable, delay) adds a job to the apex job queue that corresponds to the specified queueable class and returns the job id. the job is scheduled with a specified minimum delay (0–10 minutes). the delay is ignored during apex testing. 3420apex reference guide system class enqueuejob(queueable, asyncoptions) adds a job to the apex job queue that corresponds to the specified queueable class and returns the job id. specify the maximum stack depth and the minimum queue delay in the asyncoptions parameter. equals(obj1, obj2) returns true if both arguments are equal. otherwise, returns false. getapplicationreadwritemode() returns the read write mode set for an organization during salesforce.com upgrades and downtimes. getquiddityshortcode(quiddityvalue) returns the short code for the quiddity value of the current request object. hashcode(obj) returns the hash code of the specified object. isbatch() returns true if a batch apex job invoked the executing code, or false if not. in api version 35.0 and earlier, also returns true if a queueable apex job invoked the code. isfunctioncallback() returns true if an asynchronous salesforce function callback invoked the executing code, or false if not. available in api version 51.0 and later. isfuture() returns true if the currently executing code is invoked by code contained in a method annotated with future; false otherwise. isqueueable() returns true if a queueable apex job invoked the executing code. returns false if not, including if a batch apex job or a future method invoked the code. isrunningelasticcompute() reserved for future use. isscheduled() returns true if the currently executing code is invoked by a scheduled apex job; false otherwise. movepassword(targetuserid,sourceuserid) moves the specified user’s password to a different user. now() returns the current date and time in the gmt time zone. process(workitemids, action, comments, nextapprover) processes the list of work item ids. purgeoldasyncjobs(dt) deletes asynchronous apex job records for jobs that have finished execution before the specified date with a completed, aborted, or failed status, and returns the number of records deleted. requestversion() returns a two-part version that contains the major and minor version numbers of a package. resetpassword(userid, senduseremail) resets the password for the specified user. 3421apex reference guide system class resetpasswordwithemailtemplate(userid, senduseremail, emailtemplatename) resets the user's password and sends an email to the user with their new password. you specify the email template that is sent to the specified user. use this method for external users of experience cloud sites. runas(version) changes the current package version to the package version specified in the argument. runas(usersobject) changes the current user to the specified user. schedule(jobname, cronexpression, schedulableclass) use schedule with an apex class that implements the schedulable interface to schedule the class to run at the time specified by a cron expression. schedulebatch(batchable, jobname, minutesfromnow) schedules a batch job to run once in the future after the specified time interval and with the specified job name. schedulebatch(batchable, jobname, minutesfromnow, scopesize) schedules a batch job to run once in the future after the specified the time interval, with the specified job name and scope size. returns the scheduled job id (crontrigger id). setpassword(userid, password) sets the password for the specified user. submit(workitemids, comments, nextapprover) submits the processed approvals. the current user is the submitter and the entry criteria is evaluated for all processes applicable to the current user. today() returns the current date in the current user's time zone. abortjob(jobid) stops the specified job. the stopped job is still visible in the job queue in the salesforce user interface. signature public static void abortjob(string jobid) parameters jobid type: string the jobid is the id associated with either asyncapexjob or crontrigger. return value type: void usage the following methods return the job id that can be passed to abortjob. • system.schedule
method—returns the crontrigger object id associated with the scheduled job as a string. 3422apex reference guide system class • schedulablecontext.gettriggerid method—returns the crontrigger object id associated with the scheduled job as a string. • getjobid method—returns the asyncapexjob object id associated with the batch job as a string. • using batch apexdatabase.executebatch method—returns the asyncapexjob object id associated with the batch job as a string. assert(condition, msg) asserts that the specified condition is true. if it isn’t , a fatal error is returned that causes code execution to halt. important: we recommend that you use the methods of the assert class rather than this method. the system.assert class provides methods that handle all types of logical assertions and comparisons, which improve the clarity of your apex code. signature public static void assert(boolean condition, object msg) parameters condition type: boolean msg type: object (optional) custom message returned as part of the error message. return value type: void usage you can’t catch an assertion failure using a try/catch block even though it’s logged as an exception. assertequals(expected, actual, msg) asserts that the first two arguments are the same. if they aren’t, a fatal error is returned that causes code execution to halt. important: we recommend that you use the methods of the assert class rather than this method. the system.assert class provides methods that handle all types of logical assertions and comparisons, which improve the clarity of your apex code. signature public static void assertequals(object expected, object actual, object msg) parameters expected type: object specifies the expected value. 3423apex reference guide system class actual type: object specifies the actual value. msg type: object (optional) custom message returned as part of the error message. return value type: void usage you can’t catch an assertion failure using a try/catch block even though it’s logged as an exception. assertnotequals(expected, actual, msg) asserts that the first two arguments are different. if they’re the same, a fatal error is returned that causes code execution to halt. important: we recommend that you use the methods of the assert class rather than this method. the system.assert class provides methods that handle all types of logical assertions and comparisons, which improve the clarity of your apex code. signature public static void assertnotequals(object expected, object actual, object msg) parameters expected type: object specifies the expected value. actual type: object specifies the actual value. msg type: object (optional) custom message returned as part of the error message. return value type: void usage you can’t catch an assertion failure using a try/catch block even though it’s logged as an exception. 3424apex reference guide system class currentpagereference() returns a reference to the current page. this is used with visualforce pages. signature public static system.pagereference currentpagereference() return value type: system.pagereference usage for more information, see pagereference class. currenttimemillis() returns the current time in milliseconds, which is expressed as the difference between the current time and midnight, january 1, 1970 utc. signature public static long currenttimemillis() return value type: long debug(msg) writes the specified message, in string format, to the execution debug log. the debug log level is used. signature public static void debug(object msg) parameters msg type: object return value type: void usage if the msg argument is not a string, the debug method calls string.valueof to convert it into a string. the string.valueof method calls the tostring method on the argument, if available, or any overridden tostring method if the argument is a user-defined type. otherwise, if no tostring method is available, it returns a string representation of the argument. 3425apex reference guide system class if the log level for apex code is set to debug or higher, the message of this debug statement will be written to the debug log. note that when a map or set is printed, the output is sorted in key order and is surrounded with square brackets ([]). when an array or list is printed, the output is enclosed in parentheses (
()). note: calls to system.debug are not counted as part of apex code coverage.calls to system.debug are not counted as part of apex code coverage. for more information on log levels, see debug log levels in the salesforce online help. debug(loglevel, msg) writes the specified message, in string format, to the execution debug log with the specified log level. signature public static void debug(logginglevel loglevel, object msg) parameters loglevel type: logginglevel enum the logging level to set for this method. msg type: object the message or object to write in string format to the execution debug log. return value type: void usage if the msg argument is not a string, the debug method calls string.valueof to convert it into a string. the string.valueof method calls the tostring method on the argument, if available, or any overridden tostring method if the argument is a user-defined type. otherwise, if no tostring method is available, it returns a string representation of the argument. note: calls to system.debug are not counted as part of apex code coverage. for more information on log levels, see debug log levels in the salesforce online help. enqueuejob(queueableobj) adds a job to the apex job queue that corresponds to the specified queueable class and returns the job id. signature public static id enqueuejob(object queueableobj) 3426apex reference guide system class parameters queueableobj type: object an instance of the class that implements the queueable interface. return value type: id the job id, which corresponds to the id of an asyncapexjob record. usage to add a job for asynchronous execution, call system.enqueuejob by passing in an instance of your class implementation of the queueable interface for execution as follows: id jobid = system.enqueuejob(new myqueueableclass()); for more information about queueable apex, including information about limits, see queueable apex. enqueuejob(queueable, delay) adds a job to the apex job queue that corresponds to the specified queueable class and returns the job id. the job is scheduled with a specified minimum delay (0–10 minutes). the delay is ignored during apex testing. signature public static id enqueuejob(object queueable, integer delay) parameters queueable type: object an instance of the class that implements the queueable interface. delay type: integer the minimum delay (0–10 minutes) before the queueable job is scheduled for execution. the delay is ignored during apex testing. warning: when you set the delay to 0 (zero), the queueable job is run as quickly as possible. with chained queueable jobs, implement a mechanism to slow down or halt the job if necessary. without such a fail-safe mechanism in place, you can rapidly reach the daily async apex limit. return value type: id the job id, which corresponds to the id of an asyncapexjob record. 3427apex reference guide system class example this example adds a job for delayed asynchronous execution by passing in an instance of your class implementation of the queueable interface for execution. there’s a minimum delay of 5 minutes before the job is executed. integer delayinminutes = 5; id jobid = system.enqueuejob(new myqueueableclass(), delayinminutes); for more information about queueable apex, including information about limits, see queueable apex. enqueuejob(queueable, asyncoptions) adds a job to the apex job queue that corresponds to the specified queueable class and returns the job id. specify the maximum stack depth and the minimum queue delay in the asyncoptions parameter. signature public static id enqueuejob(object queueable, object asyncoptions) parameters queueable type: object an instance of the class that implements the queueable interface. asyncoptions type: asyncoptions the maximum stack depth and the minimum queue delay can be specified in the asyncoptions class properties. return value type: id the job id, which corresponds to the id of an asyncapexjob record. usage the system.asyncinfo class methods help you determine if maximum stack depth is set in your queueable request and get the stack depths and queue delay for queueables that are currently running. use information about the current queueable execution to make decisions on adjusting delays on subsequent calls. these are methods in the system.asyncinfo class. • hasmaxstack
depth() • getcurrentqueueablestackdepth() • getmaximumqueueablestackdepth() • getminimumqueueabledelayinminutes() for more information about queueable apex, including information about limits, see queueable apex. equals(obj1, obj2) returns true if both arguments are equal. otherwise, returns false. 3428apex reference guide system class signature public static boolean equals(object obj1, object obj2) parameters obj1 type: object object being compared. obj2 type: object object to compare with the first argument. return value type: boolean usage obj1 and obj2 can be of any type. they can be values, or object references, such as sobjects and user-defined types. the comparison rules for system.equals are identical to the ones for the == operator. for example, string comparison is case insensitive. for information about the comparison rules, see the == operator. getapplicationreadwritemode() returns the read write mode set for an organization during salesforce.com upgrades and downtimes. signature public static system.applicationreadwritemode getapplicationreadwritemode() return value type: system.applicationreadwritemode valid values are: • default • read_only using the system.applicationreadwritemode enum use the system.applicationreadwritemode enum returned by the getapplicationreadwritemode to programmatically determine if the application is in read-only mode during salesforce upgrades and downtimes. valid values for the enum are: • default • read_only 3429apex reference guide system class example: public class myclass { public static void execute() { applicationreadwritemode mode = system.getapplicationreadwritemode(); if (mode == applicationreadwritemode.read_only) { // do nothing. if dml operaton is attempted in readonly mode, // invalidreadonlyuserdmlexception will be thrown. } else if (mode == applicationreadwritemode.default) { account account = new account(name = 'my account'); insert account; } } } getquiddityshortcode(quiddityvalue) returns the short code for the quiddity value of the current request object. signature public string getquiddityshortcode(system.quiddity quiddityvalue) parameters quiddityvalue type: system.quiddity the quiddity enum value that has an associated short code. this short code is used in event monitoring logs. for more information, see apex execution event type. return value type: string hashcode(obj) returns the hash code of the specified object. signature public static integer hashcode(object obj) parameters obj type: object the object to get the hash code for. this parameter can be of any type, including values or object references, such as sobjects or user-defined types. 3430apex reference guide system class return value type: integer versioned behavior changes in api version 51.0 and later, the hashcode() method returns the same hashcode for identical id values. in api version 50.0 and earlier, identical id values didn’t always generate the same hashcode value. isbatch() returns true if a batch apex job invoked the executing code, or false if not. in api version 35.0 and earlier, also returns true if a queueable apex job invoked the code. signature public static boolean isbatch() return value type: boolean usage a batch apex job can’t invoke a future method. before invoking a future method, use isbatch() to check whether the executing code is a batch apex job. isfunctioncallback() returns true if an asynchronous salesforce function callback invoked the executing code, or false if not. available in api version 51.0 and later. signature public static boolean isfunctioncallback() return value type: boolean usage use this method to determine if the apex code is being invoked as part of a callback from an asynchronous salesforce functions invocation. for more details on invoking salesforce functions from apex, see functions namespace isfuture() returns true if the currently executing code is invoked by code contained in a method annotated with future; false otherwise. 3431apex reference guide system class signature public static boolean isfuture() return value type: boolean usage since a future method can't be invoked from another future method, use this method to check if the current code is executing within the context
of a future method before you invoke a future method. isqueueable() returns true if a queueable apex job invoked the executing code. returns false if not, including if a batch apex job or a future method invoked the code. signature public static boolean isqueueable() return value type: boolean usage public class simplequeueable implements queueable { string name; public simplequeueable(string name) { this.name = name; system.assert(!system.isqueueable()); //should return false } public void execute(queueablecontext ctx) { account testaccount = new account(); testaccount.name = 'testacc'; insert(testaccount); system.assert(system.isqueueable()); //should return true } } global class complexbatch implements database.batchable<sobject> { global database.querylocator start(database.batchablecontext info) { system.assert(!system.isqueueable()); //should return false return database.getquerylocator([select id, name from account limit 1]); } global void execute(database.batchablecontext info, sobject[] scope) { 3432
apex reference guide system class system.assert(!system.isqueueable()); //should return false system.enqueuejob(new simplequeueable('callingfromcomplexbatch')); system.assert(!system.isqueueable()); //should return false } global void finish(database.batchablecontext info) { system.assert(!system.isqueueable()); //should return false } } isrunningelasticcompute() reserved for future use. signature public static boolean isrunningelasticcompute() return value type: boolean isscheduled() returns true if the currently executing code is invoked by a scheduled apex job; false otherwise. signature public static boolean isscheduled() return value type: boolean movepassword(targetuserid,sourceuserid) moves the specified user’s password to a different user. signature public static void movepassword(id targetuserid, id sourceuserid) parameters targetuserid type: id the user that the password is moved to. sourceuserid type: id the user that the password is moved from. 3433apex reference guide system class return value type: void usage moving a password simplifies converting a user to another type of user, such as when converting an external user to a user with less restrictive access. if you require access to the movepassword method, contact salesforce. keep in mind these requirements. • the targetuserid, sourceuserid, and user performing the move operation must all belong to the same salesforce org. • the targetuserid and the sourceuserid cannot be the same as the user performing the move operation. • a user without a password can’t be specified as the sourceuserid. for example, a source user who has already had their password moved is left without a password. that user can’t be a source user again. after the password is moved: • the target user can log in with the password. • the source user no longer has a password. to enable logins for this user, a password reset is required. now() returns the current date and time in the gmt time zone. signature public static datetime now() return value type: datetime process(workitemids, action, comments, nextapprover) processes the list of work item ids. signature public static list<id> process(list<id> workitemids, string action, string comments, string nextapprover) parameters workitemids type: list<id> action type: string comments type: string nextapprover type: string 3434apex reference guide system class return value type: list<id> purgeoldasyncjobs(dt) deletes asynchronous apex job records for jobs that have finished execution before the specified date with a completed, aborted, or failed status, and returns the number of records deleted. signature public static integer purgeoldasyncjobs(date dt) parameters dt type: date specifies the date up to which old records are deleted. the date comparison is based on the completeddate field of asyncapexjob, which is in the gmt time zone. return value type: integer usage asynchronous apex job records are records in asyncapexjob. the system cleans up asynchronous job records for jobs that have finished execution and are older than seven days. you can use this method to further reduce the size of asyncapexjob by cleaning up more records. each execution of this method counts as a single row against the governor limit for dml statements. example this example shows how to delete all job records for jobs that have finished before today’s date. integer count = system.purgeoldasyncjobs (date.today()); system.debug('deleted ' + count + ' old jobs.'); requestversion() returns a two-part version that contains the major and minor version numbers of a package. signature public static system.version requestversion() return value type: system.version 3435apex reference guide system class usage using this method, you can determine the version of an installed instance of your package from which the calling code is referencing your package. based on the version that the calling code has, you can customize the behavior of your package code. the requestversion method isn’t supported for unmanaged packages. if you call it from an unmanaged package, an exception will be thrown. resetpassword(user
id, senduseremail) resets the password for the specified user. signature public static system.resetpasswordresult resetpassword(id userid, boolean senduseremail) parameters userid type: id senduseremail type: boolean return value type: system.resetpasswordresult usage when the user logs in with the new password, they are prompted to enter a new password, and to select a security question and answer if they haven't already. if you specify true for senduseremail, the user is sent an email notifying them that their password was reset. a link to sign onto salesforce using the new password is included in the email. use setpassword(userid, password) if you don't want the user to be prompted to enter a new password when they log in. warning: be careful with this method, and do not expose this functionality to end-users. resetpasswordwithemailtemplate(userid, senduseremail, emailtemplatename) resets the user's password and sends an email to the user with their new password. you specify the email template that is sent to the specified user. use this method for external users of experience cloud sites. signature public static system.resetpasswordresult resetpasswordwithemailtemplate(id userid, boolean senduseremail, string emailtemplatename) parameters userid type: id the id of the user whose password was reset. 3436apex reference guide system class senduseremail type: boolean emailtemplatename type: string name of the email template. return value type: system.resetpasswordresult usage if you specify true for senduseremail, specify the email template that is sent to the user notifying them that their password was reset. when the user logs in with the new password in the email, they are prompted to enter a new password. a link to sign onto salesforce using the new password is included in the email. use setpassword(userid, password) if you don't want the user to be prompted to enter a new password when they log in. warning: be careful with this method, and do not expose this functionality to end-users. runas(version) changes the current package version to the package version specified in the argument. signature public static void runas(system.version version) parameters version type: system.version return value type: void usage a package developer can use version methods to continue to support existing behavior in classes and triggers in previous package versions while continuing to evolve the code. apex classes and triggers are saved with the version settings for each installed managed package that the class or trigger references. this method is used for testing your component behavior in different package versions that you upload to the appexchange. this method effectively sets a two-part version consisting of major and minor numbers in a test method so that you can test the behavior for different package versions. you can only use runas in a test method. there is no limitation to the number of calls to this method in a transaction. for sample usage of this method, see testing behavior in package versions. 3437apex reference guide system class runas(usersobject) changes the current user to the specified user. signature public static void runas(user usersobject) parameters usersobject type: user return value type: void usage all of the specified user's record sharing is enforced during the execution of runas. you can only use runas in a test method. for more information, see using the runas() method. note: the runas method ignores user license limits. you can create new users with runas even if your organization has no additional user licenses. the runas method implicitly inserts the user that is passed in as parameter if the user has been instantiated, but not inserted yet. you can also use runas to perform mixed dml operations in your test by enclosing the dml operations within the runas block. in this way, you bypass the mixed dml error that is otherwise returned when inserting or updating setup objects together with other sobjects. see sobjects that cannot be used together in dml operations. note: every call to runas counts against the total number of dml statements issued in the process. schedule(jobname, cronexpression, schedulableclass) use schedule with an apex class that implements the schedulable interface to schedule the class to run at the time specified by a cron expression. signature public static string schedule(string jobname, string cronexpression, object schedulableclass)
parameters jobname type: string cronexpression type: string schedulableclass type: object 3438apex reference guide system class return value type: string returns the scheduled job id (crontrigger id). usage use extreme care if you’re planning to schedule a class from a trigger. you must be able to guarantee that the trigger won’t add more scheduled classes than the limit. in particular, consider api bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. use the abortjob method to stop the job after it has been scheduled. note: salesforce schedules the class for execution at the specified time. actual execution may be delayed based on service availability. using the system.schedule method after you implement a class with the schedulable interface, use the system.schedule method to execute it. the scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class. note: use extreme care if you’re planning to schedule a class from a trigger. you must be able to guarantee that the trigger won’t add more scheduled classes than the limit. in particular, consider api bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. the system.schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. this expression has the following syntax: seconds minutes hours day_of_month month day_of_week optional_year note: salesforce schedules the class for execution at the specified time. actual execution may be delayed based on service availability. the system.schedule method uses the user's timezone for the basis of all schedules. the following are the values for the expression: name values special characters seconds 0–59 none minutes 0–59 none hours 0–23 , - * / day_of_month 1–31 , - * ? / l w month 1–12 or the following: , - * / • jan • feb • mar • apr • may • jun 3439apex reference guide system class name values special characters • jul • aug • sep • oct • nov • dec day_of_week 1–7 or the following: , - * ? / l # • sun • mon • tue • wed • thu • fri • sat optional_year null or 1970–2099 , - * / the special characters are defined as follows: special character description , delimits values. for example, use jan, mar, apr to specify more than one month. - specifies a range. for example, use jan-mar to specify more than one month. * specifies all values. for example, if month is specified as *, the job is scheduled for every month. ? specifies no specific value. this is only available for day_of_month and day_of_week, and is generally used when specifying a value for one and not the other. / specifies increments. the number before the slash specifies when the intervals will begin, and the number after the slash is the interval amount. for example, if you specify 1/5 for day_of_month, the apex class runs every fifth day of the month, starting on the first of the month. l specifies the end of a range (last). this is only available for day_of_month and day_of_week. when used with day of month, l always means the last day of the month, such as january 31, february 29 for leap years, and so on. when used with day_of_week by itself, it always means 7 or sat. when used with a day_of_week value, it means the last of that type of day in the month. for example, if you specify 2l, you are specifying the last monday of the month. do not use a range of values with l as the results might be unexpected. 3440apex reference guide system class special character description w specifies the nearest weekday (monday-friday) of the given day. this is only available for day_of_month. for example, if you specify 20w, and the 20th is a saturday, the class runs on the 19th. if you specify 1w, and the
first is a saturday, the class does not run in the previous month, but on the third, which is the following monday. tip: use the l and w together to specify the last weekday of the month. # specifies the nth day of the month, in the format weekday#day_of_month. this is only available for day_of_week. the number before the # specifies weekday (sun-sat). the number after the # specifies the day of the month. for example, specifying 2#1 means the class runs on the first monday of every month. the following are some examples of how to use the expression. expression description 0 0 13 * * ? class runs every day at 1 pm. 0 0 22 ? * 6l class runs the last friday of every month at 10 pm. 0 0 10 ? * mon-fri class runs monday through friday at 10 am. 0 0 20 * * ? 2010 class runs every day at 8 pm during the year 2010. in the following example, the class proschedule implements the schedulable interface. the class is scheduled to run at 8 am, on the 13 february. proschedule p = new proschedule(); string sch = '0 0 8 13 2 ?'; system.schedule('one time pro', sch, p); schedulebatch(batchable, jobname, minutesfromnow) schedules a batch job to run once in the future after the specified time interval and with the specified job name. signature public static string schedulebatch(database.batchable batchable, string jobname, integer minutesfromnow) parameters batchable type: database.batchable an instance of a class that implements the database.batchable interface. jobname type: string 3441apex reference guide system class the name if the job that this method will start. minutesfromnow type: integer the time interval in minutes after which the job should start executing. this argument must be greater than zero. return value type: string the scheduled job id (crontrigger id). usage note: some things to note about system.schedulebatch: • when you call system.schedulebatch, salesforce schedules the job for execution at the specified time. actual execution occurs at or after that time, depending on service availability. • the scheduler runs as system—all classes are executed, whether the user has permission to execute the class, or not. • when the job’s schedule is triggered, the system queues the batch job for processing. if apex flex queue is enabled in your org, the batch job is added at the end of the flex queue. for more information, see holding batch jobs in the apex flex queue. • all scheduled apex limits apply for batch jobs scheduled using system.schedulebatch. after the batch job is queued (with a status of holding or queued), all batch job limits apply and the job no longer counts toward scheduled apex limits. • after calling this method and before the batch job starts, you can use the returned scheduled job id to abort the scheduled job using the system.abortjob method. for an example, see using batch apex. schedulebatch(batchable, jobname, minutesfromnow, scopesize) schedules a batch job to run once in the future after the specified the time interval, with the specified job name and scope size. returns the scheduled job id (crontrigger id). signature public static string schedulebatch(database.batchable batchable, string jobname, integer minutesfromnow, integer scopesize) parameters batchable type: database.batchable the batch class that implements the database.batchable interface. jobname type: string the name of the job that this method will start. minutesfromnow type: integer 3442apex reference guide system class the time interval in minutes after which the job should start executing. scopesize type: integer the number of records that should be passed to the batch execute method. return value type: string usage note: some things to note about system.schedulebatch: • when you call system.schedulebatch, salesforce schedules the job for execution at the specified time. actual execution occurs at or after that time, depending on service availability. • the scheduler runs as system—all classes are executed, whether the user has permission to execute the class, or not. • when the job’s schedule is triggered, the system queues the batch job for processing. if apex
flex queue is enabled in your org, the batch job is added at the end of the flex queue. for more information, see holding batch jobs in the apex flex queue. • all scheduled apex limits apply for batch jobs scheduled using system.schedulebatch. after the batch job is queued (with a status of holding or queued), all batch job limits apply and the job no longer counts toward scheduled apex limits. • after calling this method and before the batch job starts, you can use the returned scheduled job id to abort the scheduled job using the system.abortjob method. for an example, see using the system.schedulebatch method. setpassword(userid, password) sets the password for the specified user. signature public static void setpassword(id userid, string password) parameters userid type: id password type: string return value type: void usage • if a security question hasn't been previously configured, a user who logs in with a new password that was set using setpassword() is redirected to the "change your password" page. 3443apex reference guide test class • use resetpassword(userid, senduseremail) if you want the user to go through the reset process and create their own password. warning: be careful with this method, and don’t expose this functionality to end users. submit(workitemids, comments, nextapprover) submits the processed approvals. the current user is the submitter and the entry criteria is evaluated for all processes applicable to the current user. signature public static list<id> submit(list<id> workitemids, string comments, string nextapprover) parameters workitemids type: list<id> comments type: string nextapprover type: string return value type: list<id> usage for enhanced submit and evaluation features, see the processsubmitrequest class. today() returns the current date in the current user's time zone. signature public static date today() return value type: date test class contains methods related to apex tests. 3444apex reference guide test class namespace system test methods the following are methods for test. all methods are static. in this section: calculatepermissionsetgroup(psgids) calculates aggregate permissions in specified permission set groups for testing. calculatepermissionsetgroup(psgid) calculates aggregate permissions in a specified permission set group for testing. clearapexpagemessages() clear the messages on a visualforce page while executing apex test methods. createstub(parenttype, stubprovider) creates a stubbed version of an apex class that you can use for testing. this method is part of the apex stub api. you can use it with the system.stubprovider interface to create a mocking framework. enablechangedatacapture() use this method in an apex test so that change event notifications are generated for all supported change data capture entities. call this method at the beginning of your test before performing dml operations and calling test.geteventbus().deliver();. enqueuebatchjobs(numberofjobs) adds the specified number of jobs with no-operation contents to the test-context queue. it first fills the test batch queue, up to the maximum 5 jobs, and then places jobs in the test flex queue. it throws a limit exception when the number of jobs in the test flex queue exceeds the allowed limit of 100 jobs. geteventbus() returns an instance of the test event bus broker, which lets you operate on platform event or change event messages in an apex test. for example, you can call test.geteventbus().deliver() to deliver event messages. getflexqueueorder() returns an ordered list of job ids for jobs in the test-context flex queue. the job at index 0 is the next job slated to run. this method returns only test-context results, even if it’s annotated with @istest(seealldata=true). getstandardpricebookid() returns the id of the standard price book in the organization. invokecontinuationmethod(controller, request) invokes the callback method for the specified controller and continuation in a test method. isrunningtest() returns true if the currently executing code was called by code contained in a test method, false otherwise. use this method if you need to run different code depending on whether it was being called from a test. loaddata(sobjecttoken, resourcename) inserts test records
from the specified static resource .csv file and for the specified sobject type, and returns a list of the inserted sobjects. 3445apex reference guide test class newsendemailquickactiondefaults(contextid, replytoid) creates a new quickaction.sendemailquickactiondefaults instance for testing a class implementing the quickaction.quickactiondefaultshandler interface. setcontinuationresponse(requestlabel, mockresponse) sets a mock response for a continuation http request in a test method. setcreateddate(recordid, createddatetime) sets createddate for a test-context sobject. setcurrentpage(page) a visualforce test method that sets the current pagereference for the controller. setcurrentpagereference(page) a visualforce test method that sets the current pagereference for the controller. setfixedsearchresults(fixedsearchresults) defines a list of fixed search results to be returned by all subsequent sosl statements in a test method. setmock(interfacetype, instance) sets the response mock mode and instructs the apex runtime to send a mock response whenever a callout is made through the http classes or the auto-generated code from wsdls. setreadonlyapplicationmode(applicationmode) sets the application mode for an organization to read-only in an apex test to simulate read-only mode during salesforce upgrades and downtimes. the application mode is reset to the default mode at the end of each apex test run. starttest() marks the point in your test code when your test actually begins. use this method when you are testing governor limits. stoptest() marks the point in your test code when your test ends. use this method in conjunction with the starttest method. testinstall(installimplementation, version, ispush) tests the implementation of the installhandler interface, which is used for specifying a post install script in packages. tests run as the test initiator in the development environment. testsandboxpostcopyscript(script, organizationid, sandboxid, sandboxname) tests the implementation of the sandboxpostcopy interface, which is used for specifying a script to run at the completion of a sandbox copy. tests run as the test initiator in the development environment. testsandboxpostcopyscript(script, organizationid, sandboxid, sandboxname, runasautoprocuser) tests the implementation of the sandboxpostcopy interface, which is used for specifying a script to run at the completion of a sandbox copy. when runasautoprocuser is true, tests run as automated process user in the development environment. testuninstall(uninstallimplementation) tests the implementation of the uninstallhandler interface, which is used for specifying an uninstall script in packages. tests run as the test initiator in the development environment. calculatepermissionsetgroup(psgids) calculates aggregate permissions in specified permission set groups for testing. signature public static void calculatepermissionsetgroup(list<string> psgids) 3446apex reference guide test class parameters psgids type: list<string> a list of ids for permission set groups. return value type: void calculatepermissionsetgroup(psgid) calculates aggregate permissions in a specified permission set group for testing. signature public static void calculatepermissionsetgroup(string psgid) parameters psgid type: string a single id for a specified permission set group. return value type: void clearapexpagemessages() clear the messages on a visualforce page while executing apex test methods. signature public static void clearapexpagemessages() return value type: void usage this method may only be used in tests. example: @istest static void clearmessagestest() { test.setcurrentpage(new pagereference('/')); apexpages.addmessage( new apexpages.message(apexpages.severity.warning, 'sample warning') 3447apex reference guide test class ); system.assertequals(1, apexpages.getmessages().size()); test.clearapexpagemessages(); system.assertequals(0, apexpages.getmessages().size()); } createstub(parenttype, stubprovider) creates a stubbed version of an apex class that you can use for testing. this method is part of the apex stub api. you can use it with the system.stubprovider interface to create a mocking framework. sign
ature public static object createstub(system.type parenttype, system.stubprovider stubprovider) parameters parenttype type: system.type the type of the apex class to be stubbed. stubprovider system.stubprovider an implementation of the stubprovider interface. return value type: object returns the stubbed object to use in testing. usage the createstub() method works together with the system.stubprovider interface. you define the behavior of the stubbed object by implementing the stubprovider interface. then you create a stubbed object using the createstub() method. when you invoke methods on the stubbed object, the handlemethodcall() method of the stubprovider interface is called to perform the behavior of the stubbed method. see also: apex developer guide: build a mocking framework with the stub api enablechangedatacapture() use this method in an apex test so that change event notifications are generated for all supported change data capture entities. call this method at the beginning of your test before performing dml operations and calling test.geteventbus().deliver();. signature public static void enablechangedatacapture() 3448apex reference guide test class return value type: void usage the enablechangedatacapture() method ensures that apex tests can fire change event triggers regardless of the entities selected in setup in the change data capture page. the enablechangedatacapture() method doesn’t affect the entities selected in setup. see also: change data capture developer guide enqueuebatchjobs(numberofjobs) adds the specified number of jobs with no-operation contents to the test-context queue. it first fills the test batch queue, up to the maximum 5 jobs, and then places jobs in the test flex queue. it throws a limit exception when the number of jobs in the test flex queue exceeds the allowed limit of 100 jobs. signature public static list<id> enqueuebatchjobs(integer numberofjobs) parameters numberofjobs type: integer number of test jobs to enqueue. return value type: list<id> a list of ids of enqueued test jobs. usage use this method to reduce testing time. instead of using your org's real batch jobs for testing, you can use this method to simulate batch-job enqueueing. using enqueuebatchjobs(numberofjobs) is faster than enqueuing real batch jobs. geteventbus() returns an instance of the test event bus broker, which lets you operate on platform event or change event messages in an apex test. for example, you can call test.geteventbus().deliver() to deliver event messages. signature public static eventbus.testbroker geteventbus() 3449apex reference guide test class return value type: eventbus.testbroker a broker for the test event bus. usage enclose test.geteventbus().deliver() within the test.starttest() and test.stoptest() statement block. test.starttest(); // create test events // ... // publish test events with eventbus.publish() // ... // deliver test events test.geteventbus().deliver(); // perform validation // ... test.stoptest(); see also: platform events developer guide getflexqueueorder() returns an ordered list of job ids for jobs in the test-context flex queue. the job at index 0 is the next job slated to run. this method returns only test-context results, even if it’s annotated with @istest(seealldata=true). signature public static list<id> getflexqueueorder() return value type: list<id> an ordered list of ids of the jobs in the test’s flex queue. getstandardpricebookid() returns the id of the standard price book in the organization. signature public static id getstandardpricebookid() return value type: id the id of the standard price book. 3450apex reference guide test class usage this method returns the id of the standard price book in your organization regardless of whether the test can query organization data. by default, tests can’t query organization data unless they’re annotated with @istest(seealldata=true). creating price book entries with a standard price requires the id of the standard price book. use this method to get the standard price book id so that you can create price book entries in your tests. example this example creates some test data for price book entries. the
test method in this example gets the standard price book id and uses this id to create a price book entry for a product with a standard price. next, the test creates a custom price book and uses the id of this custom price book to add a price book entry with a custom price. @istest public class pricebooktest { // utility method that can be called by apex tests to create price book entries. static testmethod void addpricebookentries() { // first, set up test price book entries. // insert a test product. product2 prod = new product2(name = 'laptop x200', family = 'hardware'); insert prod; // get standard price book id. // this is available irrespective of the state of seealldata. id pricebookid = test.getstandardpricebookid(); // 1. insert a price book entry for the standard price book. // standard price book entries require the standard price book id we got earlier. pricebookentry standardprice = new pricebookentry( pricebook2id = pricebookid, product2id = prod.id, unitprice = 10000, isactive = true); insert standardprice; // create a custom price book pricebook2 custompb = new pricebook2(name='custom pricebook', isactive=true); insert custompb; // 2. insert a price book entry with a custom price. pricebookentry customprice = new pricebookentry( pricebook2id = custompb.id, product2id = prod.id, unitprice = 12000, isactive = true); insert customprice; // next, perform some tests with your test price book entries. } } invokecontinuationmethod(controller, request) invokes the callback method for the specified controller and continuation in a test method. 3451apex reference guide test class signature public static object invokecontinuationmethod(object controller, continuation request) parameters controller type: object an instance of the controller class that invokes the continuation request. request type: continuation the continuation that is returned by an action method in the controller class. return value type: object the response of the continuation callback method. usage use the test.setcontinuationresponse and test.invokecontinuationmethod methods to test continuations. in test context, callouts of continuations aren’t sent to the external service. by using these methods, you can set a mock response and cause the runtime to call the continuation callback method to process the mock response. call test.setcontinuationresponse before you call test.invokecontinuationmethod. when you call test.invokecontinuationmethod, the runtime executes the callback method that is associated with the continuation. the callback method processes the mock response that is set by test.setcontinuationresponse. isrunningtest() returns true if the currently executing code was called by code contained in a test method, false otherwise. use this method if you need to run different code depending on whether it was being called from a test. signature public static boolean isrunningtest() return value type: boolean loaddata(sobjecttoken, resourcename) inserts test records from the specified static resource .csv file and for the specified sobject type, and returns a list of the inserted sobjects. signature public static list<sobject> loaddata(schema.sobjecttype sobjecttoken, string resourcename) 3452apex reference guide test class parameters sobjecttoken type: schema.sobjecttype the sobject type for which to insert test records. resourcename type: string the static resource that corresponds to the .csv file containing the test records to load. the name is case insensitive. return value type: list<sobject> usage you must create the static resource prior to calling this method. the static resource is a comma-delimited file ending with a .csv extension. the file contains field names and values for the test records. the first line of the file must contain the field names and subsequent lines are the field values. to learn more about static resources, see “defining static resources” in the salesforce online help. once you create a static resource for your .csv file, the static resource will be assigned a mime type. supported mime types are: • text/csv • application/vnd.ms-excel • application/octet-stream • text/plain newsendemailquickactiondefaults(contextid, replytoid) creates a new quickaction.sendemailquickactiondefaults instance for testing a class implementing the quick
action.quickactiondefaultshandler interface. signature public static quickaction.sendemailquickactiondefaults newsendemailquickactiondefaults(id contextid, id replytoid) parameters contextid type: id parent record of the email message. replytoid type: id previous email message id if this email message is a reply. return value type: sendemailquickactiondefaults class the default values used for an email message quick action. 3453apex reference guide test class setcontinuationresponse(requestlabel, mockresponse) sets a mock response for a continuation http request in a test method. signature public static void setcontinuationresponse(string requestlabel, system.httpresponse mockresponse) parameters requestlabel type: string the unique label that corresponds to the continuation http request. this label is returned by continuation.addhttprequest. mockresponse type: httpresponse the fake response to be returned by test.invokecontinuationmethod. return value type: void usage use the test.setcontinuationresponse and test.invokecontinuationmethod methods to test continuations. in test context, callouts of continuations aren’t sent to the external service. by using these methods, you can set a mock response and cause the runtime to call the continuation callback method to process the mock response. call test.setcontinuationresponse before you call test.invokecontinuationmethod. when you call test.invokecontinuationmethod, the runtime executes the callback method that is associated with the continuation. the callback method processes the mock response that is set by test.setcontinuationresponse. setcreateddate(recordid, createddatetime) sets createddate for a test-context sobject. signature public static void setcreateddate(id recordid, datetime createddatetime) parameters recordid type: id the id of an sobject. createddatetime type: datetime the value to assign to the sobject’s createddate field. 3454apex reference guide test class return value type: void usage all database changes are rolled back at the end of a test. you can’t use this method on records that existed before your test executed. you also can’t use setcreateddate in methods annotated with @istest(seealldata=true), because those methods have access to all data in your org. if you set createddate to a future value, it can cause unexpected results. this method takes two parameters—an sobject id and a datetime value—neither of which can be null. insert your test record before you set its createddate, as shown in this example. @istest private class setcreateddatetest { static testmethod void testsetcreateddate() { account a = new account(name='myaccount'); insert a; test.setcreateddate(a.id, datetime.newinstance(2012,12,12)); test.starttest(); account myaccount = [select id, name, createddate from account where name ='myaccount' limit 1]; system.assertequals(myaccount.createddate, datetime.newinstance(2012,12,12)); test.stoptest(); } } setcurrentpage(page) a visualforce test method that sets the current pagereference for the controller. signature public static void setcurrentpage(pagereference page) parameters page type: system.pagereference return value type: void setcurrentpagereference(page) a visualforce test method that sets the current pagereference for the controller. signature public static void setcurrentpagereference(pagereference page) 3455apex reference guide test class parameters page type: system.pagereference return value type: void setfixedsearchresults(fixedsearchresults) defines a list of fixed search results to be returned by all subsequent sosl statements in a test method. signature public static void setfixedsearchresults(id[] fixedsearchresults) parameters fixedsearchresults type: id[] the list of record ids specified by opt_set_search_results replaces the results that would normally be returned by the sosl queries if they were not subject to any where or limit clauses. if these clauses exist in the sosl queries, they are applied to the list of fixed search results. return value type: void usage if opt_set_search_results is not specified, all subsequent sosl queries return no results. for more information, see dynamic sosl. set
mock(interfacetype, instance) sets the response mock mode and instructs the apex runtime to send a mock response whenever a callout is made through the http classes or the auto-generated code from wsdls. signature public static void setmock(type interfacetype, object instance) parameters interfacetype type: system.type instance type: object 3456apex reference guide test class return value type: void usage note: to mock a callout if the code that performs the callout is in a managed package, call test.setmock from a test method in the same package with the same namespace. setreadonlyapplicationmode(applicationmode) sets the application mode for an organization to read-only in an apex test to simulate read-only mode during salesforce upgrades and downtimes. the application mode is reset to the default mode at the end of each apex test run. signature public static void setreadonlyapplicationmode(boolean applicationmode) parameters applicationmode type: boolean return value type: void usage also see the getapplicationreadwritemode() system method. do not use setreadonlyapplicationmode for purposes unrelated to read-only mode testing, such as simulating dml exceptions. example the following example sets the application mode to read-only and attempts to insert a new account record, which results in the exception. it then resets the application mode and performs a successful insert. @istest private class applicationreadonlymodetestclass { public static testmethod void test() { // create a test account that is used for querying later. account testaccount = new account(name = 'testaccount'); insert testaccount; // set the application read only mode. test.setreadonlyapplicationmode(true); // verify that the application is in read-only mode. system.assertequals( applicationreadwritemode.read_only, system.getapplicationreadwritemode()); 3457apex reference guide test class // create a new account object. account testaccount2 = new account(name = 'testaccount2'); try { // get the test account created earlier. should be successful. account testaccountfromdb = [select id, name from account where name = 'testaccount']; system.assertequals(testaccount.id, testaccountfromdb.id); // inserts should result in the invalidreadonlyuserdmlexception // being thrown. insert testaccount2; system.assertequals(false, true); } catch (system.invalidreadonlyuserdmlexception e) { // expected } // insertion should work after read only application mode gets disabled. test.setreadonlyapplicationmode(false); insert testaccount2; account testaccount2fromdb = [select id, name from account where name = 'testaccount2']; system.assertequals(testaccount2.id, testaccount2fromdb.id); } } starttest() marks the point in your test code when your test actually begins. use this method when you are testing governor limits. signature public static void starttest() return value type: void usage you can also use this method with stoptest to ensure that all asynchronous calls that come after the starttest method are run before doing any assertions or testing. each test method is allowed to call this method only once. all of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need to run your test. any code that executes after the call to starttest and before stoptest is assigned a new set of governor limits. stoptest() marks the point in your test code when your test ends. use this method in conjunction with the starttest method. 3458apex reference guide test class signature public static void stoptest() return value type: void usage each test method is allowed to call this method only once. any code that executes after the stoptest method is assigned the original limits that were in effect before starttest was called. all asynchronous calls made after the starttest method are collected by the system. when stoptest is executed, all asynchronous processes are run synchronously. note: asynchronous calls, such as @future or executebatch, called in a starttest, stoptest block, do not count against your limits for the number of queued jobs. testinstall(installimplementation, version, ispush) tests the implementation of the installhandler interface, which is used for specifying
a post install script in packages. tests run as the test initiator in the development environment. signature public static void testinstall(installhandler installimplementation, version version, boolean ispush) parameters installimplementation type: system.installhandler a class that implements the installhandler interface. version type: system.version the version number of the existing package installed in the subscriber organization. ispush type: boolean (optional) specifies whether the upgrade is a push. the default value is false. return value type: void usage this method throws a run-time exception if the test install fails. 3459apex reference guide test class example @istest static void test() { postinstallclass postinstall = new postinstallclass(); test.testinstall(postinstall, new version(1,0)); } testsandboxpostcopyscript(script, organizationid, sandboxid, sandboxname) tests the implementation of the sandboxpostcopy interface, which is used for specifying a script to run at the completion of a sandbox copy. tests run as the test initiator in the development environment. signature public static void testsandboxpostcopyscript(system.sandboxpostcopy script, id organizationid, id sandboxid, string sandboxname) parameters script type: system.sandboxpostcopy a class that implements the sandboxpostcopy interface. organizationid type: id the sandbox organization id sandboxid type: id the sandbox id to be provided to the sandboxpostcopy script. sandboxname type: string the sandbox name to be provided to the sandboxpostcopy script. return value type: void usage this method throws a run-time exception if the test install fails. note: salesforce recommends that you use the testsandboxpostcopyscript(script, organizationid, sandboxid, sandboxname, isrunasautoprocuser) overload instead of this method. when isrunasautoprocuser is true, the sandboxpostcopy script is tested with the same user access permissions as used by post-copy tasks during sandbox creation. using the same permissions enables the test to better simulate the actual usage of the class, and to uncover potential issues. 3460apex reference guide test class example see sandboxpostcopy example implementation testsandboxpostcopyscript(script, organizationid, sandboxid, sandboxname, runasautoprocuser) tests the implementation of the sandboxpostcopy interface, which is used for specifying a script to run at the completion of a sandbox copy. when runasautoprocuser is true, tests run as automated process user in the development environment. signature public static void testsandboxpostcopyscript(system.sandboxpostcopy script, id organizationid, id sandboxid, string sandboxname, boolean runasautoprocuser) parameters script type: system.sandboxpostcopy a class that implements the sandboxpostcopy interface. organizationid type: id the sandbox organization id. sandboxid type: id the sandbox id to be provided to the sandboxpostcopy script. sandboxname type: string the sandbox name to be provided to the sandboxpostcopy script. runasautoprocuser type: boolean when true, the sandboxpostcopy script is tested with the same user access permissions as used by post-copy tasks during sandbox creation. using the same permissions enables the test to better simulate the actual usage of the class, and to uncover potential issues. when false, the test runs as the test initiator. this option can alter the permissions with which the script is tested, such as the ability to access objects and features. return value type: void usage this method throws a run-time exception if the test install fails. 3461apex reference guide time class example see sandboxpostcopy example implementation testuninstall(uninstallimplementation) tests the implementation of the uninstallhandler interface, which is used for specifying an uninstall script in packages. tests run as the test initiator in the development environment. signature public static void testuninstall(uninstallhandler uninstallimplementation) parameters uninstallimplementation type: system.uninstallhandler a class that implements the uninstallhandler interface. return value type: void usage this method throws a run-time exception if the test uninstall fails. example @istest static void test() { uninstallclass uninstall = new uninstallclass(); test.testun
install(uninstall); } time class contains methods for the time primitive data type. namespace system usage for more information on time, see time data type. time methods the following are methods for time. 3462apex reference guide time class in this section: addhours(additionalhours) adds the specified number of hours to a time. addmilliseconds(additionalmilliseconds) adds the specified number of milliseconds to a time. addminutes(additionalminutes) adds the specified number of minutes to a time. addseconds(additionalseconds) adds the specified number of seconds to a time. hour() returns the hour component of a time. millisecond() returns the millisecond component of a time. minute() returns the minute component of a time. newinstance(hour, minutes, seconds, milliseconds) constructs a time from integer representations of the specified hour, minutes, seconds, and milliseconds. (utc is assumed.) second() returns the second component of a time. addhours(additionalhours) adds the specified number of hours to a time. signature public time addhours(integer additionalhours) parameters additionalhours type: integer return value type: time example time mytime = time.newinstance(1, 2, 3, 4); time expected = time.newinstance(4, 2, 3, 4); system.assertequals(expected, mytime.addhours(3)); addmilliseconds(additionalmilliseconds) adds the specified number of milliseconds to a time. 3463apex reference guide time class signature public time addmilliseconds(integer additionalmilliseconds) parameters additionalmilliseconds type: integer return value type: time example time mytime = time.newinstance(1, 2, 3, 0); time expected = time.newinstance(1, 2, 4, 400); system.assertequals(expected, mytime.addmilliseconds(1400)); addminutes(additionalminutes) adds the specified number of minutes to a time. signature public time addminutes(integer additionalminutes) parameters additionalminutes type: integer return value type: time example time mytime = time.newinstance(18, 30, 2, 20); integer myminutes = mytime.minute(); myminutes = myminutes + 5; system.assertequals(myminutes, 35); addseconds(additionalseconds) adds the specified number of seconds to a time. signature public time addseconds(integer additionalseconds) 3464apex reference guide time class parameters additionalseconds type: integer return value type: time example time mytime = time.newinstance(1, 2, 55, 0); time expected = time.newinstance(1, 3, 5, 0); system.assertequals(expected, mytime.addseconds(10)); hour() returns the hour component of a time. signature public integer hour() return value type: integer example time mytime = time.newinstance(18, 30, 2, 20); mytime = mytime.addhours(2); integer myhour = mytime.hour(); system.assertequals(myhour, 20); millisecond() returns the millisecond component of a time. signature public integer millisecond() return value type: integer example time mytime = time.newinstance(3, 14, 15, 926); system.assertequals(926, mytime.millisecond()); 3465apex reference guide time class minute() returns the minute component of a time. signature public integer minute() return value type: integer example time mytime = time.newinstance(3, 14, 15, 926); system.assertequals(14, mytime.minute()); newinstance(hour, minutes, seconds, milliseconds) constructs a time from integer representations of the specified hour, minutes, seconds, and milliseconds. (utc is assumed.) signature public static time newinstance(integer hour, integer minutes, integer seconds, integer milliseconds) parameters hour type: integer minutes type: integer seconds type: integer milliseconds type: integer return value type: time example the following example creates a time of 18:30
:2:20 (utc). time mytime = time.newinstance(18, 30, 2, 20); 3466apex reference guide timezone class second() returns the second component of a time. signature public integer second() return value type: integer example time mytime = time.newinstance(3, 14, 15, 926); system.assertequals(15, mytime.second()); timezone class represents a time zone. contains methods for creating a new time zone and obtaining time zone properties, such as the time zone id, offset, and display name. namespace system usage you can use the methods in this class to get properties of a time zone, such as the properties of the time zone returned by userinfo.gettimezone, or the time zone returned by gettimezone of this class. example this example shows how to get properties of the current user’s time zone and displays them to the debug log. timezone tz = userinfo.gettimezone(); system.debug('display name: ' + tz.getdisplayname()); system.debug('id: ' + tz.getid()); // during daylight saving time for the america/los_angeles time zone system.debug('offset: ' + tz.getoffset(datetime.newinstance(2012,10,23,12,0,0))); // not during daylight saving time for the america/los_angeles time zone system.debug('offset: ' + tz.getoffset(datetime.newinstance(2012,11,23,12,0,0))); system.debug('string format: ' + tz.tostring()); the output of this sample varies based on the user's time zone. this is an example output if the user’s time zone is america/los_angeles. for this time zone, daylight saving time is -7 hours from gmt (-25200000 milliseconds) and standard time is -8 hours from gmt (-28800000 milliseconds). display name: pacific standard time id: america/los_angeles offset: -25200000 3467apex reference guide timezone class offset: -28800000 string format: america/los_angeles this second example shows how to create a time zone for the new york time zone and get the offset of this time zone to the gmt time zone. the example uses two dates to get the offset from. one date is before dst (daylight saving time), and one is after dst. in 2000, dst ended on sunday, october 29 for the new york time zone. because the date occurs after dst ends, the offset on the first date is –5 hours to gmt. in 2012, dst ended on sunday, november 4. because the date is within dst, the offset on the second date is –4 hours. // get the new york time zone timezone tz = timezone.gettimezone('america/new_york'); // create a date before the 2007 shift of dst into november datetime dtpre = datetime.newinstancegmt(2000, 11, 1, 0, 0, 0); system.debug(tz.getoffset(dtpre)); //-18000000 (= -5 hours = est) // create a date after the 2007 shift of dst into november datetime dtpost = datetime.newinstancegmt(2012, 11, 1, 0, 0, 0); system.debug(tz.getoffset(dtpost)); //-14400000 (= -4 hours = edt) this next example is similar to the previous one except that it gets the offset around the boundary of dst. in 2014, dst ended on sunday, november 2 at 2:00 am local time for the new york time zone. the first offset is obtained right before dst ends, and the second offset is obtained right after dst ends. the dates are created by using the datetime.newinstancegmt method. this method expects the passed-in date values to be based on the gmt time zone. // get the new york time zone timezone tz = timezone.gettimezone('america/new_york'); // before dst ends datetime dtpre = datetime.newinstancegmt(2014, 11, 2, 5, 59, 59); //1:59:59am local edt system.debug(tz.getoffset(dtpre)); //-14400000 (= -4 hours = still on dst) // after dst ends datetime dtpost = datetime.newinstancegmt(2014, 11, 2,
6, 0, 0); //1:00:00am local est system.debug(tz.getoffset(dtpost)); //-18000000 (= -5 hours = back one hour) timezone methods the following are methods for timezone. in this section: getdisplayname() returns this time zone’s display name. getid() returns this time zone’s id. getoffset(date) returns the time zone offset, in milliseconds, of the specified date to the gmt time zone. gettimezone(timezoneidstring) returns the time zone corresponding to the specified time zone id. tostring() returns the string representation of this time zone. 3468apex reference guide timezone class getdisplayname() returns this time zone’s display name. signature public string getdisplayname() return value type: string versioned behavior changes in api version 45.0 and later, getdisplayname displays daylight savings time appropriately when daylight savings are in effect. for example, british summer time is displayed for europe/london and pacific daylight time for america/los_angeles. getid() returns this time zone’s id. signature public string getid() return value type: string getoffset(date) returns the time zone offset, in milliseconds, of the specified date to the gmt time zone. signature public integer getoffset(datetime date) parameters date type: datetime the date argument is the date and time to evaluate. return value type: integer usage note: the returned offset is adjusted for daylight saving time if the date argument falls within daylight saving time for this time zone. 3469apex reference guide trigger class gettimezone(timezoneidstring) returns the time zone corresponding to the specified time zone id. signature public static timezone gettimezone(string timezoneidstring) parameters timezoneidstring type: string the time zone values you can use for the id argument are any valid time zone values that the java timezone class supports. return value type: timezone example timezone tz = timezone.gettimezone('america/los_angeles'); string tzname = tz.getdisplayname(); system.assert(tzname.equals('(gmt-08:00) pacific standard time (america/los_angeles)') || tzname.equals('(gmt-07:00) pacific daylight time (america/los_angeles)')); tostring() returns the string representation of this time zone. signature public string tostring() return value type: string trigger class use the trigger class to access run-time context information in a trigger, such as the type of trigger or the list of sobject records that the trigger operates on. namespace system trigger context variables the trigger class provides the following context variables. 3470apex reference guide trigger class variable usage isexecuting returns true if the current context for the apex code is a trigger, not a visualforce page, a web service, or an executeanonymous() api call. isinsert returns true if this trigger was fired due to an insert operation, from the salesforce user interface, apex, or the api. isupdate returns true if this trigger was fired due to an update operation, from the salesforce user interface, apex, or the api. isdelete returns true if this trigger was fired due to a delete operation, from the salesforce user interface, apex, or the api. isbefore returns true if this trigger was fired before any record was saved. isafter returns true if this trigger was fired after all records were saved. isundelete returns true if this trigger was fired after a record is recovered from the recycle bin. this recovery can occur after an undelete operation from the salesforce user interface, apex, or the api. new returns a list of the new versions of the sobject records. this sobject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers. newmap a map of ids to the new versions of the sobject records. this map is only available in before update, after insert, after update, and after undelete triggers. old returns a list of the old versions of the sobject records. this sobject list is only available in update and delete triggers. oldmap a map of ids to the old versions of the sobject records. this map is only available in update and delete triggers. operationtype returns an enum
of type system.triggeroperation corresponding to the current operation. possible values of the system.triggeroperation enum are: before_insert, before_update, before_delete,after_insert, after_update, after_delete, and after_undelete. if you vary your programming logic based on different trigger types, consider using the switch statement with different permutations of unique trigger execution enum states. size the total number of records in a trigger invocation, both old and new. note: the record firing a trigger can include an invalid field value, such as a formula that divides by zero. in this case, the field value is set to null in these variables: • new • newmap • old • oldmap 3471apex reference guide trigger class example for example, in this simple trigger, trigger.new is a list of sobjects and can be iterated over in a for loop. it can also be used as a bind variable in the in clause of a soql query. trigger simpletrigger on account (after insert) { for (account a : trigger.new) { // iterate over each sobject } // this single query finds every contact that is associated with any of the // triggering accounts. note that although trigger.new is a collection of // records, when used as a bind variable in a soql query, apex automatically // transforms the list of records into a list of corresponding ids. contact[] cons = [select lastname from contact where accountid in :trigger.new]; } this trigger uses boolean context variables like trigger.isbefore and trigger.isdelete to define code that only executes for specific trigger conditions: trigger myaccounttrigger on account(before delete, before insert, before update, after delete, after insert, after update) { if (trigger.isbefore) { if (trigger.isdelete) { // in a before delete trigger, the trigger accesses the records that will be // deleted with the trigger.old list. for (account a : trigger.old) { if (a.name != 'oktodelete') { a.adderror('you can\'t delete this record!'); } } } else { // in before insert or before update triggers, the trigger accesses the new records // with the trigger.new list. for (account a : trigger.new) { if (a.name == 'bad') { a.name.adderror('bad name'); } } if (trigger.isinsert) { for (account a : trigger.new) { system.assertequals('xxx', a.accountnumber); system.assertequals('industry', a.industry); system.assertequals(100, a.numberofemployees); system.assertequals(100.0, a.annualrevenue); a.accountnumber = 'yyy'; } // if the trigger is not a before trigger, it must be an after trigger. } else { if (trigger.isinsert) { list<contact> contacts = new list<contact>(); 3472apex reference guide triggeroperation enum for (account a : trigger.new) { if(a.name == 'makecontact') { contacts.add(new contact (lastname = a.name, accountid = a.id)); } } insert contacts; } } }}} triggeroperation enum system.triggeroperation enum values are associated with trigger events. enum values the following are the values of the system.triggeroperation enum: • after_delete • after_insert • after_undelete • after_update • before_delete • before_insert • before_update type class contains methods for getting the apex type that corresponds to an apex class and for instantiating new types. namespace system usage use the forname methods to retrieve the type of an apex class, which can be a built-in or a user-defined class. you can use these methods to retrieve the type of public and global classes, and not private classes even if the context user has access. also, use the newinstance method if you want to instantiate a type that implements an interface and call its methods while letting someone else, such as a subscriber of your package, provide the methods’ implementations. note: a call to type.forname() can cause the class to be compiled. example: instantiating a type based on its name the following sample shows how
to use the type methods to instantiate a type based on its name. a typical application of this scenario is when a package subscriber provides a custom implementation of an interface that is part of an installed package. the package can 3473apex reference guide type class get the name of the class that implements the interface through a custom setting in the subscriber’s org. the package can then instantiate the type that corresponds to this class name and invoke the methods that the subscriber implemented. in this sample, vehicle represents the interface that the vehicleimpl class implements. the last class contains the code sample that invokes the methods implemented in vehicleimpl. this is the vehicle interface. global interface vehicle { long getmaxspeed(); string gettype(); } this is the implementation of the vehicle interface. global class vehicleimpl implements vehicle { global long getmaxspeed() { return 100; } global string gettype() { return 'sedan'; } } the method in this class gets the name of the class that implements the vehicle interface through a custom setting value. it then instantiates this class by getting the corresponding type and calling the newinstance method. next, it invokes the methods implemented in vehicleimpl. this sample requires that you create a public list custom setting named customimplementation with a text field named classname. create one record for this custom setting with a data set name of vehicle and a class name value of vehicleimpl. public class customerimplinvocationclass { public static void invokecustomimpl() { // get the class name from a custom setting. // this class implements the vehicle interface. customimplementation__c cs = customimplementation__c.getinstance('vehicle'); // get the type corresponding to the class name type t = type.forname(cs.classname__c); // instantiate the type. // the type of the instantiated object // is the interface. vehicle v = (vehicle)t.newinstance(); // call the methods that have a custom implementation system.debug('max speed: ' + v.getmaxspeed()); system.debug('vehicle type: ' + v.gettype()); } } class property the class property returns the system.type of the type it is called on. it’s exposed on all apex built-in types including primitive data types and collections, sobject types, and user-defined classes. this property can be used instead of forname methods. call this property on the type name. for example: system.type t = integer.class; 3474apex reference guide type class you can use this property for the second argument of json.deserialize, deserializestrict, jsonparser.readvalueas, and readvalueasstrict methods to get the type of the object to deserialize. for example: decimal n = (decimal)json.deserialize('100.1', decimal.class); type methods the following are methods for type. in this section: equals(typetocompare) returns true if the specified type is equal to the current type; otherwise, returns false. forname(fullyqualifiedname) returns the type that corresponds to the specified fully qualified class name. forname(namespace, name) returns the type that corresponds to the specified namespace and class name. getname() returns the name of the current type. hashcode() returns a hash code value for the current type. isassignablefrom(sourcetype) returns true if an object reference of the specified type can be assigned from the child type; otherwise, returns false. newinstance() creates an instance of the current type and returns this new instance. tostring() returns a string representation of the current type, which is the type name. equals(typetocompare) returns true if the specified type is equal to the current type; otherwise, returns false. signature public boolean equals(object typetocompare) parameters typetocompare type: object the type to compare with the current type. return value type: boolean 3475apex reference guide type class example type t1 = account.class; type t2 = type.forname('account'); system.assert(t1.equals(t2)); forname(fullyqualifiedname) returns the type that corresponds to the specified fully qualified class name. signature public static system.type forname(string fullyqualifiedname) parameters fullyqualifiedname type: string the fully qualified name of the class to get the type of. the fully qualified class name contains the namespace
name, for example, mynamespace.classname. return value type: system.type usage note: • this method returns null if called outside a managed package to get the type of a non-global class in a managed package. this is because the non-global class isn’t visible outside the managed package. for apex saved using salesforce api version 27.0 and earlier, this method does return the corresponding class type for the non-global managed package class. • when called from an installed managed package to get the name of a local type in an organization with no defined namespace, the forname(fullyqualifiedname) method returns null. instead, use the forname(namespace, name) method and specify an empty string or null for the namespace argument. • a call to type.forname() can cause the class to be compiled. forname(namespace, name) returns the type that corresponds to the specified namespace and class name. signature public static system.type forname(string namespace, string name) parameters namespace type: string the namespace of the class. if the class doesn't have a namespace, set the namespace argument to null or an empty string. 3476apex reference guide type class name type: string the name of the class. return value type: system.type usage note: • this method returns null if called outside a managed package to get the type of a non-global class in a managed package. this is because the non-global class isn’t visible outside the managed package. for apex saved using salesforce api version 27.0 and earlier, this method does return the corresponding class type for the non-global managed package class. • use this method instead of forname(fullyqualifiedname) if it’s called from a managed package installed in an organization with no defined namespace. to get the name of a local type, set the namespace argument to an empty string or null. for example, type t = type.forname('', 'classname');. • a call to type.forname() can cause the class to be compiled. example this example shows how to get the type that corresponds to the classname class and the mynamespace namespace. type mytype = type.forname('mynamespace', 'classname'); getname() returns the name of the current type. signature public string getname() return value type: string example this example shows how to get a type’s name. it first obtains a type by calling forname, then calls getname on the type object. type t = type.forname('myclassname'); string typename = t.getname(); system.assertequals('myclassname', typename); 3477apex reference guide type class hashcode() returns a hash code value for the current type. signature public integer hashcode() return value type: integer usage the returned hash code value corresponds to the type name hash code that string.hashcode returns. isassignablefrom(sourcetype) returns true if an object reference of the specified type can be assigned from the child type; otherwise, returns false. signature public boolean isassignablefrom(type sourcetype) parameters sourcetype the type of the object with which you are checking compatibility. return value type: boolean the method returns true when the method is invoked as parenttype.isassignablefrom(childtype). when invoked in any of the following ways, the method returns false: • childtype.isassignablefrom(parenttype) • typea.isassignablefrom(typeb) where typeb is a sibling of typea • typea.isassignablefrom(typeb) where typeb and typea are unrelated note: a childtype is the child of a parenttype when it implements an interface, extends a virtual or abstract class, or is the same system.type as the parenttype. usage unlike the instanceof operator, this method allows you to check type compatibility without having to create a class instance. this method eliminates static compile-time dependencies that instanceof requires. the following code demonstrates how a typical isv customer can use isassignablefrom() to check compatibility between a customer-defined type (customerprovidedplugintype) and a valid plugin type. //scenario: managed package code loading a “plugin” class that implements a managed interface; the implementation done outside of the package 3478apex reference guide type class string pluginnamestr =
config__c.getinstance().pluginapextype__c; type customerprovidedplugintype = type.forname(pluginnamestr); type plugininterface = managedplugininterface.class; // constructors may have side-effects, including potentially unsafe dml/callouts. // we want to make sure the class is really designed to be a valid plugin before we instantiate it boolean validplugin = plugininterface.isassignablefrom(customerprovidedplugintype); // validate that it implements the right interface if(!validplugin){ throw new securityexception('cannot create instance of '+customerprovidedplugintype+'. does not implement managedplugininterface'); }else{ return type.newinstance(validplugin); } example the following code snippet first defines sibling classes a and b that both implement the callable interface and an unrelated class c. then, it explores several type comparisons using isassignablefrom(). //define classes a, b, and c global class a implements database.batchable<string>, callable { global iterable<string> start(database.batchablecontext context) { return null; } global void execute(database.batchablecontext context, string[] scope) { } global void finish(database.batchablecontext context) { } global object call(string action, map<string, object> args) { return null; } } global class b implements callable { global object call(string action, map<string, object> args) { return null; } } global class c { } type listofstrings = type.forname('list<string>'); type listofintegers = type.forname('list<integer>'); boolean flaglisttypes = listofintegers.isassignablefrom(listofstrings); // false //examples with stringtype and idtype type stringtype = type.forname('string'); type idtype = type.forname('id'); boolean isid_assignablefromstring = idtype.isassignablefrom(stringtype); // true //isassignablefrom respects that string can be assigned to id without an explicit cast //examples with typea, typeb, and typec type typea = type.forname('a'); type typeb = type.forname('b'); type typec = type.forname('c'); boolean istypeb_oftypea = typeb.isassignablefrom( typea ); // false - siblings 3479apex reference guide type class boolean istypea_oftypec = typea.isassignablefrom( typec ); // false - unrelated types boolean istypea_oftypea = typea.isassignablefrom(typea); // true - identity //examples with callabletype and batchabletype type callabletype = type.forname('callable'); type batchabletype = type.forname('database.batchable'); boolean istypea_callable = callabletype.isassignablefrom( typea ); // true - type a is a child of callable type boolean istypea_batchable = batchabletype.isassignablefrom( typea ); // true - type a is a child of batchable type boolean iscallableoftypea = typea.isassignablefrom( callabletype ); // false - callable type is not a child of type a boolean isbatchableoftypea = typea.isassignablefrom( batchabletype ); // false - batchable type is not a child of type a newinstance() creates an instance of the current type and returns this new instance. signature public object newinstance() return value type: object usage because newinstance returns the generic object type, you should cast the return value to the type of the variable that will hold this value. this method enables you to instantiate a type that implements an interface and call its methods while letting someone else provide the methods’ implementation. for example, a package developer can provide an interface that a subscriber who installs the package can implement. the code in the package calls the subscriber's implementation of the interface methods by instantiating the subscriber’s type. example this example shows how to create an instance of a type. it first gets a type by calling forname with the name of a class (shapeimpl), then calls newinstance on this type object. the newobj instance is declared with the interface type (shape)
that the shapeimpl class implements. the return value of the newinstance method is cast to the shape type. type t = type.forname('shapeimpl'); shape newobj = (shape)t.newinstance(); tostring() returns a string representation of the current type, which is the type name. 3480apex reference guide uninstallhandler interface signature public string tostring() return value type: string usage this method returns the same value as getname. string.valueof and system.debug use this method to convert their type argument into a string. example this example calls tostring on the type corresponding to a list of integers. type t = list<integer>.class; string s = t.tostring(); system.assertequals('list<integer>', s); uninstallhandler interface enables custom code to run after a managed package is uninstalled. namespace system usage app developers can implement this interface to specify apex code that runs automatically after a subscriber uninstalls a managed package. this makes it possible to perform cleanup and notification tasks based on details of the subscriber’s organization. the uninstall script is subject to default governor limits. it runs as a special system user that represents your package, so all operations performed by the script will appear to be done by your package. you can access this user by using userinfo. you will only see this user at runtime, not while running tests. if the script fails, the uninstall continues but none of the changes performed by the script are committed. any errors in the script are emailed to the user specified in the notify on apex error field of the package. if no user is specified, the uninstall details will be unavailable. the uninstall script has the following restrictions. you can’t use it to initiate batch, scheduled, and future jobs, to access session ids, or to perform callouts. the uninstallhandler interface has a single method called onuninstall, which specifies the actions to be performed on uninstall. global interface uninstallhandler { void onuninstall(uninstallcontext context)}; the onuninstall method takes a context object as its argument, which provides the following information. • the org id of the organization in which the uninstall takes place. 3481apex reference guide uninstallhandler interface • the user id of the user who initiated the uninstall. the context argument is an object whose type is the uninstallcontext interface. this interface is automatically implemented by the system. the following definition of the uninstallcontext interface shows the methods you can call on the context argument. global interface uninstallcontext { id organizationid(); id uninstallerid(); } in this section: uninstallhandler methods uninstallhandler example implementation uninstallhandler methods the following are methods for uninstallhandler. in this section: onuninstall(context) specifies the actions to be performed on uninstall. onuninstall(context) specifies the actions to be performed on uninstall. signature public void onuninstall(uninstallcontext context) parameters context type: uninstallcontext return value type: void uninstallhandler example implementation example of an uninstall script the sample uninstall script below performs the following actions on package uninstall. • inserts an entry in the feed describing which user did the uninstall and in which organization 3482
apex reference guide url class • creates and sends an email message confirming the uninstall to that user global class uninstallclass implements uninstallhandler { global void onuninstall(uninstallcontext ctx) { feeditem feedpost = new feeditem(); feedpost.parentid = ctx.uninstallerid(); feedpost.body = 'thank you for using our application!'; insert feedpost; user u = [select id, email from user where id =:ctx.uninstallerid()]; string toaddress= u.email; string[] toaddresses = new string[] {toaddress}; messaging.singleemailmessage mail = new messaging.singleemailmessage(); mail.settoaddresses(toaddresses); mail.setreplyto('[email protected]'); mail.setsenderdisplayname('my package support'); mail.setsubject('package uninstall successful'); mail.setplaintextbody('thanks for uninstalling the package.'); messaging.sendemail(new messaging.email[] { mail }); } } you can test an uninstall script using the testuninstall method of the test class. this method takes as its argument a class that implements the uninstallhandler interface. this sample shows how to test an uninstall script implemented in the uninstallclass apex class. @istest static void testuninstallscript() { id uninstallerid = userinfo.getuserid(); list<feeditem> feedpostsbefore = [select id from feeditem where parentid=:uninstallerid and createddate=today]; test.testuninstall(new uninstallclass()); list<feeditem> feedpostsafter = [select id from feeditem where parentid=:uninstallerid and createddate=today]; system.assertequals(feedpostsbefore.size() + 1, feedpostsafter.size(), 'post to uninstaller failed.'); } url class represents a uniform resource locator (url) and provides access to parts of the url. enables access to the base url used to access your salesforce org. namespace system 3483apex reference guide url class usage use the methods of the system.url class to create links to objects in your organization. such objects can be files, images, logos, or records that you want to include in external emails, in activities, or in chatter posts. for example, you can create a link to a file uploaded as an attachment to a chatter post by concatenating the salesforce base url with the file id: // get a file uploaded through chatter. contentdocument doc = [select id from contentdocument where title = 'myfile']; // create a link to the file. string fullfileurl = url.getsalesforcebaseurl().toexternalform() + '/' + doc.id; system.debug(fullfileurl); the following example creates a link to a salesforce record. the full url is created by concatenating the salesforce base url with the record id. account acct = [select id from account where name = 'acme' limit 1]; string fullrecordurl = url.getsalesforcebaseurl().toexternalform() + '/' + acct.id; example in this example, the base url and the full request url of the current salesforce server instance are retrieved. next, a url pointing to a specific account object is created. finally, components of the base and full url are obtained. this example prints out all the results to the debug log output. // create a new account called acme that we will create a link for later. account myaccount = new account(name='acme'); insert myaccount; // get the base url. string sfdcbaseurl = url.getsalesforcebaseurl().toexternalform(); system.debug('base url: ' + sfdcbaseurl ); // get the url for the current request. string currentrequesturl = url.getcurrentrequesturl().toexternalform(); system.debug('current request url: ' + currentrequesturl); // create the account url from the base url. string accounturl = url.getsalesforcebaseurl().toexternalform() + '/' + myaccount.id; system.debug('url of a particular account: ' + accounturl); // get some parts of the base url. system.debug('host: ' + url.getsalesforcebaseurl().gethost()); system.debug('protocol: ' + url.getsalesforcebaseurl().getprotocol());
// get the query string of the current request. system.debug('query: ' + url.getcurrentrequesturl().getquery()); versioned behavior changes in api version 41.0 and later, apex url objects are represented by the java.net.uri type, not the java.net.url type. the api version in which the url object was instantiated determines the behavior of subsequent method calls to the specific instance. 3484apex reference guide url class salesforce strongly encourages you to use api 41.0 and later versions for fully rfc-compliant url parsing that includes proper handling of edge cases of complex url structures. api 41.0 and later versions also enforce that inputs are valid, rfc-compliant url or uri strings. in this section: url constructors url methods url constructors the following are constructors for url. in this section: url(spec) creates a new instance of the url class using the specified string representation of the url. url(context, spec) creates a new instance of the url class by parsing the specified spec within the specified context. url(protocol, host, file) creates a new instance of the url class using the specified protocol, host, and file on the host. the default port for the specified protocol is used. url(protocol, host, port, file) creates a new instance of the url class using the specified protocol, host, port, and file on the host. url(spec) creates a new instance of the url class using the specified string representation of the url. signature public url(string spec) parameters spec type: string the string to parse as a url. url(context, spec) creates a new instance of the url class by parsing the specified spec within the specified context. signature public url(url context, string spec) 3485apex reference guide url class parameters context type: url on page 3483 the context in which to parse the specification. spec type: string the string to parse as a url. usage the new url is created from the given context url and the spec argument as described in rfc2396 "uniform resource identifiers : generic * syntax" : <scheme>://<authority><path>?<query>#<fragment> for more information about the arguments of this constructor, see the corresponding url(java.net.url, java.lang.string) constructor for java. url(protocol, host, file) creates a new instance of the url class using the specified protocol, host, and file on the host. the default port for the specified protocol is used. signature public url(string protocol, string host, string file) parameters protocol type: string the protocol name for this url. host type: string the host name for this url. file type: string the file name for this url. url(protocol, host, port, file) creates a new instance of the url class using the specified protocol, host, port, and file on the host. signature public url(string protocol, string host, integer port, string file) 3486apex reference guide url class parameters protocol type: string the protocol name for this url. host type: string the host name for this url. port type: integer the port number for this url. file type: string the file name for this url. url methods the following are methods for url. in this section: getauthority() returns the authority portion of the current url. getcurrentrequesturl() returns the url of an entire request on a salesforce instance. getdefaultport() returns the default port number of the protocol associated with the current url. getfile() returns the file name of the current url. getfilefieldurl(entityid, fieldname) returns the download url for a file attachment. gethost() returns the host name of the current url. getorgdomainurl() returns the canonical url for your org. for example, https://mydomainname.my.salesforce.com. getpath() returns the path portion of the current url. getport() returns the port of the current url. getprotocol() returns the protocol name of the current url, such as, https. getquery() returns the query portion of the current url. 3487apex reference guide url class getref() returns the anchor of the current url. getsalesforce
baseurl() returns the url of the current connection to the salesforce org. getuserinfo() gets the userinfo portion of the current url. samefile(urltocompare) compares the current url with the specified url object, excluding the fragment component. toexternalform() returns a string representation of the current url. getauthority() returns the authority portion of the current url. signature public string getauthority() return value type: string getcurrentrequesturl() returns the url of an entire request on a salesforce instance. signature public static system.url getcurrentrequesturl() return value type: system.url usage an example of a url for an entire request is https://yourinstance.salesforce.com/apex/myvfpage.apexp. getdefaultport() returns the default port number of the protocol associated with the current url. signature public integer getdefaultport() 3488apex reference guide url class return value type: integer usage returns -1 if the url scheme or the stream protocol handler for the url doesn't define a default port number. getfile() returns the file name of the current url. signature public string getfile() return value type: string getfilefieldurl(entityid, fieldname) returns the download url for a file attachment. signature public static string getfilefieldurl(string entityid, string fieldname) parameters entityid type: string specifies the id of the entity that holds the file data. fieldname type: string specifies the api name of a file field component, such as attachmentbody. return value type: string usage example: example string fileurl = url.getfilefieldurl( 3489apex reference guide url class '087000000000123' , 'attachmentbody'); gethost() returns the host name of the current url. signature public string gethost() return value type: string getorgdomainurl() returns the canonical url for your org. for example, https://mydomainname.my.salesforce.com. signature public static system.url getorgdomainurl() return value type: system.url getorgdomainurl() always returns the login url for your org, regardless of context. use that url when making api calls to your org. usage use getorgdomainurl() to interact with salesforce rest and soap apis in apex code. get endpoints for user interface api calls, for creating and customizing picklist value sets and custom fields, and more. getorgdomainurl() can access the domain url only for the org in which the apex code is running. you don't need a remotesitesetting for your org to interact with the salesforce apis using domain urls retrieved with this method. example this example uses the salesforce rest api to get organization limit values. for information on limits, see limits in the rest api developer guide. http h = new http(); httprequest req = new httprequest(); req.setendpoint(url.getorgdomainurl().toexternalform() + '/services/data/v44.0/limits'); req.setmethod('get'); 3490apex reference guide url class req.setheader('authorization', 'bearer ' + userinfo.getsessionid()); httpresponse res = h.send(req); see also: getsalesforcebaseurl() lightning aura components developer guide: making api calls from apex user interface api developer guide: get default values to clone a record user interface api developer guide: get values for a picklist field user interface api developer guide: user inteface api resources getpath() returns the path portion of the current url. signature public string getpath() return value type: string getport() returns the port of the current url. signature public integer getport() return value type: integer getprotocol() returns the protocol name of the current url, such as, https. signature public string getprotocol() return value type: string getquery() returns the query portion of the current url. 3491apex reference guide url class signature public string getquery() return value type: string usage returns null if no query portion exists. getref() returns the anchor of the current url. signature public string getref() return value type: string usage returns null if no query portion exists
. getsalesforcebaseurl() returns the url of the current connection to the salesforce org. signature public static system.url getsalesforcebaseurl() return value type: system.url returns the url for the current connection: for example, https://mydomainname.my.salesforce.com or https://mydomainname.lightning.force.com. see also: getorgdomainurl() getuserinfo() gets the userinfo portion of the current url. 3492apex reference guide userinfo class signature public string getuserinfo() return value type: string usage returns null if no userinfo portion exists. samefile(urltocompare) compares the current url with the specified url object, excluding the fragment component. signature public boolean samefile(system.url urltocompare) parameters urltocompare type: system.url return value type: boolean returns true if both url objects reference the same remote resource; otherwise, returns false. usage for more information about the syntax of uris and fragment components, see rfc3986. toexternalform() returns a string representation of the current url. signature public string toexternalform() return value type: string userinfo class contains methods for obtaining information about the context user. 3493apex reference guide userinfo class namespace system userinfo methods the following are methods for userinfo. all methods are static. in this section: getdefaultcurrency() returns the context user's default currency code for multiple currency organizations or the organization's currency code for single currency organizations. getfirstname() returns the context user's first name getlanguage() returns the context user's language getlastname() returns the context user's last name getlocale() returns the context user's locale. getname() returns the context user's full name. the format of the name depends on the language preferences specified for the organization. getorganizationid() returns the context organization's id. getorganizationname() returns the context organization's company name. getprofileid() returns the context user's profile id. getsessionid() returns the session id for the current session. gettimezone() returns the current user’s local time zone. getuitheme() returns the preferred theme for the current user. use getuithemedisplayed to determine the theme actually displayed to the current user. getuithemedisplayed() returns the theme being displayed for the current user. getuseremail() returns the current user’s email address. getuserid() returns the context user's id 3494apex reference guide userinfo class getusername() returns the context user's login name. getuserroleid() returns the context user's role id. getusertype() returns the context user's type. haspackagelicense(packageid) returns true if the context user has a license to the managed package via a package license only. otherwise, returns false. iscurrentuserlicensed(namespace) returns true if the context user has a license to any managed package denoted by the namespace. otherwise, returns false. iscurrentuserlicensedforpackage(packageid) returns true if the context user has a license to the managed package denoted by the package id. otherwise, returns false. if the context user has access, it’s determined either via the package license or a namespace permission set license for the package namespace. ismulticurrencyorganization() specifies whether the organization uses multiple currencies. getdefaultcurrency() returns the context user's default currency code for multiple currency organizations or the organization's currency code for single currency organizations. signature public static string getdefaultcurrency() return value type: string usage note: for apex saved using salesforce api version 22.0 or earlier, getdefaultcurrency returns null for single currency organizations. getfirstname() returns the context user's first name signature public static string getfirstname() return value type: string 3495apex reference guide userinfo class getlanguage() returns the context user's language signature public static string getlanguage() return value type: string getlastname() returns the context user's last name signature public static string getlastname() return value type: string getlocale() returns the context user's locale. signature public static string getlocale() return value type: string
example string result = userinfo.getlocale(); system.assertequals('en_us', result); getname() returns the context user's full name. the format of the name depends on the language preferences specified for the organization. signature public static string getname() 3496apex reference guide userinfo class return value type: string usage the format is one of the following: • firstname lastname • lastname, firstname getorganizationid() returns the context organization's id. signature public static string getorganizationid() return value type: string getorganizationname() returns the context organization's company name. signature public static string getorganizationname() return value type: string getprofileid() returns the context user's profile id. signature public static string getprofileid() return value type: string getsessionid() returns the session id for the current session. 3497apex reference guide userinfo class signature public static string getsessionid() return value type: string usage you can use getsessionid() both synchronously and asynchronously. in asynchronous apex (batch, future, queueable, or scheduled apex), this method returns the session id only when the code is run by an active, valid user. when the code is run by an internal user, such as the automated process user or a proxy user, the method returns null. as a best practice, ensure that your code handles both cases: when a session id is or is not available. gettimezone() returns the current user’s local time zone. signature public static system.timezone gettimezone() return value type: system.timezone example timezone tz = userinfo.gettimezone(); system.debug( 'display name: ' + tz.getdisplayname()); system.debug( 'id: ' + tz.getid()); getuitheme() returns the preferred theme for the current user. use getuithemedisplayed to determine the theme actually displayed to the current user. signature public static string getuitheme() return value type: string the preferred theme for the current user. 3498apex reference guide userinfo class valid values include: • theme1—obsolete salesforce theme • theme2—salesforce classic 2005 user interface theme • theme3—salesforce classic 2010 user interface theme • theme4d—modern “lightning experience” salesforce theme • theme4t—salesforce mobile app theme • theme4u—lightning console theme • portaldefault—salesforce customer portal theme that applies to customer portals only and not to experience builder sites • webstore—appexchange theme getuithemedisplayed() returns the theme being displayed for the current user. signature public static string getuithemedisplayed() return value type: string the theme being displayed for the current user valid values include: • theme1—obsolete salesforce theme • theme2—salesforce classic 2005 user interface theme • theme3—salesforce classic 2010 user interface theme • theme4d—modern “lightning experience” salesforce theme • theme4t—salesforce mobile app theme • theme4u—lightning console theme • portaldefault—salesforce customer portal theme that applies to customer portals only and not to experience builder sites • webstore—appexchange theme getuseremail() returns the current user’s email address. signature public static string getuseremail() return value type: string 3499apex reference guide userinfo class example string emailaddress = userinfo.getuseremail(); system.debug( 'email address: ' + emailaddress); getuserid() returns the context user's id signature public static string getuserid() return value type: string getusername() returns the context user's login name. signature public static string getusername() return value type: string getuserroleid() returns the context user's role id. signature public static string getuserroleid() return value type: string getusertype() returns the context user's type. signature public static string getusertype() 3500apex reference guide userinfo class return value type: string haspackagelicense(packageid) returns true if the context user has a license to the managed package via a
package license only. otherwise, returns false. signature public static boolean haspackagelicense(id packageid) parameters packageid type: string return value type: boolean iscurrentuserlicensed(namespace) returns true if the context user has a license to any managed package denoted by the namespace. otherwise, returns false. signature public static boolean iscurrentuserlicensed(string namespace) parameters namespace type: string return value type: boolean usage a typeexception is thrown if namespace is an invalid type. iscurrentuserlicensedforpackage(packageid) returns true if the context user has a license to the managed package denoted by the package id. otherwise, returns false. if the context user has access, it’s determined either via the package license or a namespace permission set license for the package namespace. signature public static boolean iscurrentuserlicensedforpackage(id packageid) 3501apex reference guide usermanagement class parameters packageid type: string return value type: boolean usage retrieve packageid at runtime, with the getcurrentpackageid() method. then, use packageid to confirm that the contextual user is licensed to use that managed package. a typeexception is thrown if packageid is an invalid type. a systemexception is thrown if packageid is the id of an unlocked or unmanaged package, or if the contextual user doesn’t have a license to the managed package. ismulticurrencyorganization() specifies whether the organization uses multiple currencies. signature public static boolean ismulticurrencyorganization() return value type: boolean usermanagement class contains methods to manage end users, for example, to register their verification methods, verify their identity, or remove their personal information. namespace system usage let users register and deregister identity verification methods. create custom login and verify pages for passwordless login and self-registration. convert mobile phone numbers to the proper format before registering users. scramble user data when users request that salesforce remove their personal information. this class is available in api version 43.0 and later. in this section: usermanagement methods 3502apex reference guide usermanagement class usermanagement methods the following are methods for usermanagement. in this section: clone() makes a duplicate copy of the system.usermanagement object. deregisterverificationmethod(userid, method) deregisters an identity verification method. use this method to let users delete an existing verification method. formatphonenumber(countrycode, phonenumber) formats a mobile phone number for a user. call this method to ensure that the phone number is formatted properly before updating a user’s mobile phone number. initpasswordlesslogin(userid, method) invokes a verification challenge for passwordless login when creating custom (visualforce) login and verify pages for customers and partners. initregisterverificationmethod(method) invokes a verification challenge for registering identity verification methods with a custom (visualforce) page. users can register either their email address or phone number. initselfregistration(method, user) invokes a verification challenge for self-registration when creating a custom (visualforce) verify page for experience cloud self-registration. initverificationmethod(method) initiates a verification service for email, phone (sms), and the salesforce authenticator verification methods. initverificationmethod(method, actionname, extras) initiates a verification service for email, phone (sms), and the salesforce authenticator verification methods. obfuscateuser(userid, username) scrambles users’ data on their request when they no longer want their personal data recognized in salesforce. when you invoke the method for the user, the data becomes anonymous, and you can never recover it. use this method to set the username to a specific value after it’s scrambled. obfuscateuser(userid) scrambles users’ data on their request when they no longer want their personal data recognized in salesforce. when you invoke the method for the user, the data becomes anonymous, and you can never recover it. registerverificationmethod(method, starturl) registers an identity verification method. verification methods can be a time-based one-time password (totp), email or text verification code, salesforce authenticator, or u2f-compatible security key. end users register verification methods for themselves. sendasyncemailconfirmation(userid, emailtemplateid, networkid, starturl) send an email message to a user�
�s email address for verification. the message contains a verification link (url) that the user clicks to verify the email address later on. you can send email verifications in bulk. verifypasswordlesslogin(userid, method, identifier, code, starturl) completes a verification challenge during a passwordless login that uses a custom verify page (visualforce only). if the user who is trying to log in enters the verification code successfully, the user is logged in. 3503apex reference guide usermanagement class verifyregisterverificationmethod(code, method) completes registering a user’s email address or phone number as a verification method when customizing the identity verification process. verifyselfregistration(method, identifier, code, starturl) completes a verification challenge when creating a custom (visualforce) verify page for experience cloud site self-registration. if the person who is attempting to register enters the verification code successfully, the user is created and logged in. verifyverificationmethod(identifier, code, method) completes the verification service for email, phone (sms), salesforce authenticator, password, or time-based one-time password (totp) verification methods. clone() makes a duplicate copy of the system.usermanagement object. signature public object clone() return value type: user management deregisterverificationmethod(userid, method) deregisters an identity verification method. use this method to let users delete an existing verification method. signature public static void deregisterverificationmethod(id userid, auth.verificationmethod method) parameters userid type: id user id of the user deregistering the verification method. method type: auth.verificationmethod verification method used to verify the identity of the user. return value type: void 3504apex reference guide usermanagement class usage use this method to deregister an existing identity verification method. for example, your users can deregister a phone number when their phone number changes. while only end users can register an identity verification method, you and your users can deregister one. keep this behavior in mind when you implement a custom registration page. this method is available in api version 43.0 and later. note: this method doesn't support deregistering built-in authenticators. formatphonenumber(countrycode, phonenumber) formats a mobile phone number for a user. call this method to ensure that the phone number is formatted properly before updating a user’s mobile phone number. signature global static string formatphonenumber(string countrycode, string phonenumber) parameters countrycode type: string a valid country code. phonenumber type: string a mobile number that contains from 3 through 49 numeric characters, without the country code. for example, (415) 555-1234. return value type: string returns a user’s mobile phone number in the proper format. usage use this method to ensure a user’s mobile phone number is formatted as required by salesforce. then use the method’s return value to update the mobile field of the user’s record. this mobile number is used for sms-based device activation. for example, mobile phone numbers are stored along with other identity verification methods in auth.verificationmethod enum. this method is introduced in api version 43.0. it isn't available in earlier versions. here are some acceptable ways that users can enter their mobile number: • +1, (415) 555-1234 (with plus signs, parentheses, and dashes) • 1, 4155551234 (only numbers, no symbols) • 1 , 415-555-1234 (extra spaces) now, consider the following examples. • correct examples: – formatphonenumber('1', '4155551234'); – formatphonenumber('+1','(415) 555-1234'); 3505apex reference guide usermanagement class – formatphonenumber('1', '415-555-1234'); • incorrect example, because the country code and mobile number aren’t separated: – formatphonenumber(null, '+1 415-555-1234'); • example that doesn’t generate an error, but likely won’t work as intended: – formatphonenumber('+1', '+1 (415) 555-1234'); format phone number code example here's a code example that uses the formatphonenumber method. it gets the mobile number from the user and converts it to the format required by salesforce. then it updates
the user’s record with the formatted mobile number. global with sharing class phoneregistrationcontroller { //input variables global string countrycode {get; set;} global string phonenumber {get; set;} global string addphonenumber() { if(countrycode == null) return 'country code is required'; if(phonenumber == null) return 'phone number is required'; string userid = userinfo.getuserid(); user u = [select id from user where id=:userid limit 1]; string formatnum = system.usermanagement.formatphonenumber(countrycode, phonenumber); u.mobilephone = formatnum; update u; return null; } } as long as the country code and phone number are separated, formatphonenumber returns a value in the proper format. initpasswordlesslogin(userid, method) invokes a verification challenge for passwordless login when creating custom (visualforce) login and verify pages for customers and partners. signature public static string initpasswordlesslogin(id userid, auth.verificationmethod method) parameters userid type: id id of the user who’s logging in. method type: auth.verificationmethod 3506apex reference guide usermanagement class method used to verify the user’s identity, which can be email or sms. return value type: string identifier of the verification attempt. usage use this method along with its paired verifypasswordlesslogin to customize the login experience with your own visualforce login and verify pages. invoke initpasswordlesslogin from the login page where the user enters an email address or phone number. note: an alternative to using this combination of methods is to use site.passwordlesslogin. both approaches let you customize the login page in visualforce. with the paired methods, you can create custom login and verify pages. with site.passwordlesslogin, salesforce supplies the verify page. first call the initpasswordlesslogin method to initiate an authentication challenge. this method: • gets the user id and verification method, such as email or sms, from the login page. • looks up the user and checks that the user is unique and active. • sends a verification code to the user. • adds an entry for the verification attempt to the identity verification history log, assigning an identifier to the verification attempt and setting the status to user challenged, waiting for response. • adds an entry for the passwordless login to the login history log. • returns the identifier to verifypasswordlesslogin to link the transactions. then call verifypasswordlesslogin, which, if the user enters the verification code correctly, logs in the user. note: users must verify their identity by email address or phone number before they can log in without a password. you can check whether the user is verified from the user’s detail page in setup. or you can check programmatically with twofactormethodsinfo. initregisterverificationmethod(method) invokes a verification challenge for registering identity verification methods with a custom (visualforce) page. users can register either their email address or phone number. signature public static string initregisterverificationmethod(auth.verificationmethod method) parameters method type: auth.verificationmethod method used to verify the user’s identity, which can be email or sms. return value type: string 3507apex reference guide usermanagement class the method returns an error message if the phone number is already registered, the user isn’t a customer or partner, or if the context isn’t an experience cloud site. usage use this method along with its paired verifyregisterverificationmethod on page 3517 to customize the process for registering a user’s verification method using a visualforce verify page. first call the initregisterverificationmethod method to get the verification code sent to the user as input, and validate it. if the verification code isn’t valid, it returns an error message. example here’s a code example that registers a user’s phone number as a verification method. when the user enters a verification code on the visualforce page, it invokes registeruser(). the method gets the user id of the user who’s registering the verification method and the user’s phone number. it also gets the user’s registration status to check whether the phone number is verified already. if the user is registered with a different phone number, the number is updated. public void registeruser() { try { exceptiontext=''; string userid = userinfo.getuserid();
user u = [select mobilephone, id from user where id=:userid]; currphone = u.mobilephone; mobilephone = getformattedsms(mobilephone); if (mobilephone != null && mobilephone != '') { u.mobilephone = mobilephone; update u; // we're updating the email and phone number before verifying. roll back // the change in the verify api if it is unsuccessful. exceptiontext = system. usermanagement.initregisterverificationmethod(auth.verificationmethod.sms); if(exceptiontext!= null && exceptiontext!=''){ isinit = false; showinitexception = true; } else { isinit = false; isverify = true; } } else { showinitexception = true; } } catch (exception e) { exceptiontext = e.getmessage(); isinit = false; showinitexception = true; } } public void verifyuser() { // take the user’s input for the code sent to their phone number exceptiontext = system.usermanagement. verifyregisterverificationmethod(code, auth.verificationmethod.sms); if(exceptiontext != null && exceptiontext !=''){ 3508apex reference guide usermanagement class showinitexception = true; } else { //success } } initselfregistration(method, user) invokes a verification challenge for self-registration when creating a custom (visualforce) verify page for experience cloud self-registration. signature public static string initselfregistration(auth.verificationmethod method, user user) parameters method type: auth.verificationmethod method used to verify the identity of the user, which can be email or sms. user type: user user object to insert after successful registration. return value type: string identifier of the registration attempt. usage by default, when users sign up for your experience cloud site with an email address or phone number, salesforce sends them a verification code. at the same time, it generates a verify page for users to confirm their identity. you can replace the default salesforce verify page with your own visualforce page and then invoke the verification process. call this method to initiate the authentication challenge, and include a user object to insert if the registration is successful. the method returns the identifier for the self-registration attempt. note: if you specify a language in the languagelocalekey field on the user object, salesforce uses this language for verification email and sms messages. then call verifyselfregistration, which, if the user enters the verification code correctly, logs in the user. example this code contains the result of a verification challenge that registers a new user. string id = system.usermanagement.initselfregistration (auth.verificationmethod.sms, user); auth.verificationresult res = system.usermanagement.verifyselfregistration (auth.verificationmethod.sms, id, ‘123456’, null); if(res.success == true){ 3509apex reference guide usermanagement class //redirect } initverificationmethod(method) initiates a verification service for email, phone (sms), and the salesforce authenticator verification methods. signature public static string initverificationmethod(auth.verificationmethod method) parameters method type: auth.verificationmethod method used to initiate a verification service for email, sms, or salesforce_authenticator verification methods. return value type: string the returned identifier must be passed into verifyverificationmethod. usage use this method along with its paired verifyverificationmethod to customize a verification service for email, sms, or salesforce_authenticator verification methods. the returned identifier from initverificationmethod must be passed into verifyverificationmethod. first invoke the initverificationmethod method to send a verification code to the user’s email or phone number, or to send a push notification to the salesforce authenticator. the user then enters the code or approves the push notification. if the verification code isn’t valid or the push notification isn’t approved, the service returns an error message. email example this example shows multi-factor authentication using email. public void initverification() { // user will receive code on their registered verified email identifier = usermanagement.initverificationmethod(auth.verificationmethod.email); } public auth.verificationresult
verifyverification() { // requiring identifier from the initverification // the code will need to be entered in this method return usermanagement.verifyverificationmethod(identifier, code , auth.verificationmethod.email); } initverificationmethod(method, actionname, extras) initiates a verification service for email, phone (sms), and the salesforce authenticator verification methods. 3510apex reference guide usermanagement class signature public static string initverificationmethod(auth.verificationmethod method, string actionname, map<string,string> extras) parameters method type: auth.verificationmethod method used to initiate a verification service for email, sms, or salesforce_authenticator verification methods. actionname type: string for the salesforce_authenticator verification method only, the name of the action to display on the salesforce authenticator, such as connect to my salesforce org. the default action name is apex-defined activity. extras type: map<string,string> for the salesforce_authenticator verification method only, the following extra settings. • secure_device_required–if set to true, the user’s device must be secured. for example, the user must enter the device’s passcode to approve the request. default setting is false. • challenge_required–if set to true, the user must complete a biometric challenge, such as face recognition, on the device to approve the request. default setting is false. return value type: string the returned identifier must be passed into verifyverificationmethod method. usage use this method along with its paired verifyverificationmethod to customize a verification service for email, sms, or salesforce_authenticator verification methods. the returned identifier from initverificationmethod must be passed into verifyverificationmethod method. first invoke the initverificationmethod method to send a verification code to the user’s email or phone number, or to send a push notification to the salesforce authenticator. the user then enters the code or approves the push notification. if the verification code isn’t valid or the push notification isn’t approved, the service returns an error message. salesforce authenticator example this example shows multi-factor authentication (mfa) using the salesforce authenticator mobile app. in this example, the actionname parameter is set to the default setting and the extra parameter settings are set to false. public void initverification() { // user will receive push notification on their registered mfa devices identifier = usermanagement.initverificationmethod(auth.verificationmethod.salesforce_authenticator); } public auth.verificationresult verifyverification() { 3511apex reference guide usermanagement class // requiring identifier from the initverification // user will need to take the action on their registered mfa devices return usermanagement.verifyverificationmethod(identifier, '' , auth.verificationmethod.salesforce_authenticator); } this example shows multi-factor authentication using salesforce authenticator. in this example, the actionname parameter is set to connect to my salesforce org and the challenge_required extra parameter is set to true. public void initverification() { map<string,string> extras = new map<string,string>(); extras.put('challenge_required','true'); // user will receive push notification in their registered mfa devices identifier = usermanagement.initverificationmethod(auth.verificationmethod.salesforce_authenticator, 'connect to my salesforce org', extras); } public auth.verificationresult verifyverification() { // requiring identifier from the initverification // user will need to take the action on their registered mfa devices return usermanagement.verifyverificationmethod(identifier, '' , auth.verificationmethod.salesforce_authenticator); } obfuscateuser(userid, username) scrambles users’ data on their request when they no longer want their personal data recognized in salesforce. when you invoke the method for the user, the data becomes anonymous, and you can never recover it. use this method to set the username to a specific value after it’s scrambled. signature public static void obfuscateuser(id userid, string username) parameters userid type: id
id of the user whose data this method scrambles. username type: string the username after the user’s data is scrambled. sets the value of the scrambled username to a specific string. return value type: void usage this method is introduced in api version 43.0. it isn't available in earlier versions. 3512apex reference guide usermanagement class you can use the obfuscateuser method to protect the personal information of your org’s users. when invoked, salesforce permanently scrambles the user’s object data and replaces it with random character strings. the user’s detail page exists, but the fields contain meaningless strings of characters. salesforce merely obfuscates (scrambles) personal data because you can't delete a user in salesforce; you can only disable or deactivate a user. in other words, the user record remains in the database and this method performs a soft delete. note: take care when using this method. the users’ data becomes anonymous and can never be recovered. considerations • this method requires that the org’s user management setting, scramble specific users' data, is enabled from setup. • this method affects the standard fields of the user object—excluding a few fields such as the user id, timezone, locale, and profile. • it is recommended that you note the user's id and other attributes for post processing, such as the email address, if you want to send the user a confirmation. • this method changes only the user object. the association between the user and other objects is removed, but no other objects are changed. for example, contact, thirdpartyaccountlink (tpal), and user password authentication (upa) objects remain unchanged. note: assure your admins that invoking this method doesn’t trigger an email change notification. this method is part of our effort to protect users’ personal data and privacy. for more information on what you can do to actively protect user data, see data protection and privacy in salesforce help. obfuscateuser(userid) scrambles users’ data on their request when they no longer want their personal data recognized in salesforce. when you invoke the method for the user, the data becomes anonymous, and you can never recover it. signature public static void obfuscateuser(id userid) parameters userid type: id id of the user whose data this method scrambles. return value type: void usage this method is introduced in api version 43.0. it isn't available in earlier versions. you can use the obfuscateuser method to protect the personal information of your org’s users. when invoked, salesforce permanently scrambles the user’s object data and replaces it with random character strings. the user’s detail page exists, but the fields contain meaningless strings of characters. salesforce merely obfuscates (scrambles) personal data because you can't delete a user in salesforce; you can only disable or deactivate a user. in other words, the user record remains in the database and this method performs a soft delete. note: take care when using this method. the users’ data becomes anonymous and can never be recovered. 3513apex reference guide usermanagement class considerations • this method requires that the org’s user management setting, scramble specific users' data, is enabled from setup. • this method affects the standard fields of the user object—excluding a few fields such as the user id, timezone, locale, and profile. • if you want to send the user a confirmation, it’s recommended that you note the user's id and other attributes for post processing, such as the email address. • this method changes only the user object. the association between the user and other objects is removed, but no other objects are changed. for example, contact, thirdpartyaccountlink (tpal), and user password authentication (upa) objects remain unchanged. note: assure your admins that invoking this method doesn’t trigger an email change notification. this method is part of our effort to protect users’ personal data and privacy. for more information on what you can do to actively protect user data, see data protection and privacy in salesforce help. obfuscateuser code example public class usermanagementcontroller{ public list <user> users {get; set;} public usermanagementcontroller() { profile p = [select id from profile where name = 'customer community user']; users = [select username, id from user where profileid=:p.id and isactive=true]; } //use method with extreme caution
. data can't be recovered. @invocablemethod(label='user management' description='obfuscate user data and more') static public void obfuscate(list<user> users) { string uid = apexpages.currentpage().getparameters().get('uid'); if(uid == null) return; user u = [select contactid from user where id=:uid]; system.usermanagement.obfuscateuser(uid); } } registerverificationmethod(method, starturl) registers an identity verification method. verification methods can be a time-based one-time password (totp), email or text verification code, salesforce authenticator, or u2f-compatible security key. end users register verification methods for themselves. signature public static system.pagereference registerverificationmethod(auth.verificationmethod method, string starturl) 3514apex reference guide usermanagement class parameters method type: auth.verificationmethod verification method used to verify the identity of the user. starturl type: string path to the page that users see after they log in. return value type:system.pagereference usage use this method to enable users to complete identity verification, such as multi-factor authentication (mfa), or to log in to their experience cloud site without a password. users register these methods to verify their identity when logging in. you create a custom registration page when implementing mobile-centric passwordless logins. see verifypasswordlesslogin. the pagereference returned by registerverificationmethod redirects the user to the salesforce verify page. if the user enters the correct code, the user is redirected to the experience cloud site page specified by the start url. for example: pagereference pr = system.usermanagement.registerverificationmethod(auth.verificationmethod.totp,starturl); pagereference p = system.usermanagement.deregisterverificationmethod(userid,auth.verificationmethod.salesforce_authenticator); this method is available in api version 43.0 and later. note: as a security measure, when users add or update mobile numbers in their detail page, they must log in again to verify their identity. as a result, unsaved changes in the app are lost. to disable this security measure, contact salesforce support. sendasyncemailconfirmation(userid, emailtemplateid, networkid, starturl) send an email message to a user’s email address for verification. the message contains a verification link (url) that the user clicks to verify the email address later on. you can send email verifications in bulk. signature public static boolean sendasyncemailconfirmation(string userid, string emailtemplateid, string networkid, string starturl) parameters userid type: string id of the user to receive the email confirmation. 3515apex reference guide usermanagement class emailtemplateid type: string id of the email template in which the verification link is defined. networkid type: string id of the experience cloud site. starturl type: string the user is redirected to this page after verification, with a success or error message as the parameter. if null, the user is redirected to the login page. return value type: boolean indicates whether sending the email message succeeded or failed. usage sending an async email message is good practice to ensure that users are registered with a valid email address that they truly own. to determine which users receive an email with the verification link, check whether the user verified email field in the user detail page is set to true. you can also get this information from the twofactormethodsinfo api. send async email verification to customers and partners to verify their email address. these users must verify their email address before they can log in with email otp (passwordless login). the error code and description are passed as query parameters so that you can process any errors when building a custom landing page. example system.usermanagement.sendasyncemailconfirmation('005rm000001a0ox', '00xrm000000hxng','0dbrm000000015i', '/s/contactsupport'); verifypasswordlesslogin(userid, method, identifier, code, starturl) completes a verification challenge during a passwordless login that uses a custom verify page (visualforce only). if the user who is trying to log in enters the verification code successfully, the user is logged in. signature public static auth.verificationresult verifypasswordlesslogin(id userid, auth.verification
method method, string identifier, string code, string starturl) parameters userid type: id id of the user who’s logging in. 3516apex reference guide usermanagement class method type: auth.verificationmethod method used to verify the identity of the user, which can be either email or sms. identifier type: string id of the verification attempt received from the initpasswordlesslogin method. code type: string code used to verify the identity of the user. starturl type: string the page where the user is directed after successful login. return value type: auth.verificationresult result of the verification challenge, which includes the message displayed, and where the user is directed if they enter the verification code correctly. usage call this method to complete the passwordless login authentication process. it validates the verification method and verification code. it also checks that the identifier is the same as the one returned by initpasswordlesslogin on page 3506. example for an example, see auth.verificationresult. verifyregisterverificationmethod(code, method) completes registering a user’s email address or phone number as a verification method when customizing the identity verification process. signature public static string verifyregisterverificationmethod(string code, auth.verificationmethod method) parameters code type: string code used to verify the identity of the user. method type: auth.verificationmethod method used to verify the identity of the user, which can be either email or sms. 3517apex reference guide usermanagement class return value type: string if the user enters an incorrect verification code, the method returns an error message. usage call verifyregisterverificationmethod to complete the process of registering a user’s verification method. this method checks whether the user entered the correct verification code. if the verification code is correct, the method • confirms that the user entered the correct verification code • from the user’s detail page, updates the user's verification method status (sets the verification bit) • sends an email to the user confirming that a verification method has been added to their record if the verification code is incorrect, an error message is returned. note: if users want to change their email address after registering one, don’t use the initregisterverificationmethod and verify registerverificationmethod methods. to enable automatic identity verification for email address changes, from the identity verification setup page, select the field require email confirmations for email address changes (applies to users in experience builder sites). example here’s a code example that registers a user’s phone number as a verification method. when the user enters a verification code on the visualforce page, it invokes registeruser(). the method gets the user id of the user who’s registering the verification method and the user’s phone number. it also gets the user’s registration status to check whether the phone number is verified already. if the user is registered with a different phone number, the number is updated. public void registeruser() { try { exceptiontext=''; string userid = userinfo.getuserid(); user u = [select mobilephone, id from user where id=:userid]; currphone = u.mobilephone; mobilephone = getformattedsms(mobilephone); if (mobilephone != null && mobilephone != '') { u.mobilephone = mobilephone; update u; // we're updating the email and phone number before verifying. roll back // the change in the verify api if it is unsuccessful. exceptiontext = system. usermanagement.initregisterverificationmethod(auth.verificationmethod.sms); if(exceptiontext!= null && exceptiontext!=''){ isinit = false; showinitexception = true; } else { isinit = false; isverify = true; } } else { showinitexception = true; } } catch (exception e) { exceptiontext = e.getmessage(); 3518apex reference guide usermanagement class isinit = false; showinitexception = true; } } public void verifyuser() { // take the user’s input for the code sent to their phone number exceptiontext = system.usermanagement. verifyregisterverificationmethod(code, auth.verificationmethod.sms); if(exceptiontext != null && exceptiontext !=''){ showinitexception = true; } else { //success }
} verifyselfregistration(method, identifier, code, starturl) completes a verification challenge when creating a custom (visualforce) verify page for experience cloud site self-registration. if the person who is attempting to register enters the verification code successfully, the user is created and logged in. signature public static auth.verificationresult verifyselfregistration(auth.verificationmethod method, string identifier, string code, string starturl) parameters method type: auth.verificationmethod method used to verify the identity of the user, which can be either email or sms. identifier type: string the unique identifier received from the initselfregistration method. code type: string code used to verify the identity of the user. starturl type: string the page where the user is directed after successful self-registration. return value type: auth.verificationresult result of the verification challenge, which includes the message displayed, and where the user is directed when they enter the verification code correctly. 3519apex reference guide usermanagement class usage by default, when users sign up for your experience cloud site with an email address or phone number, salesforce sends them a verification code and generates a verify page. this verify page is where users enter the verification code to confirm their identity. you can replace this salesforce-generated verify page with a custom verify page that you create with visualforce. then you invoke the verification process with apex methods. first, call the initselfregistration method, which returns the identifier of the user to create. then call this verifyselfregistration method to complete the verification process. if the user enters the verification code correctly, the user is created and directed to the page specified in the starturl. this method returns the verification result, which contains the verification status and, if the user is created, the session id. if the verification method is sms, the user object must contain a properly formatted mobile number, which is country code, space, and then phone number, for example, +1 1234567890. use system.usermanagement.formatphonenumber to ensure that the phone number is formatted correctly. example this code contains the result of a verification challenge that registers a new user. string id = system.usermanagement.initselfregistration (auth.verificationmethod.sms, user); auth.verificationresult res = system.usermanagement.verifyselfregistration (auth.verificationmethod.sms, id, ‘123456’, null); if(res.success == true){ //redirect } verifyverificationmethod(identifier, code, method) completes the verification service for email, phone (sms), salesforce authenticator, password, or time-based one-time password (totp) verification methods. signature public static verificationresult verifyverificationmethod(string identifier, string code, auth.verificationmethod method) parameters identifier type: string identifier returned from initverificationmethod for email, sms, and salesforce_authenticator. code type: string code used to verify the user’s identity for email, sms, or password. method type: auth.verificationmethod method used to verify the user’s identity, which can be email, password, salesforce_authenticator, sms, or totp. 3520apex reference guide version class return value type: verificationresult usage use this method along with its paired initverificationmethod to customize a verification service for email, sms, or salesforce_authenticator verification methods. or use this method alone to provide a complete verification service for password and totp verification methods. this method checks whether the user entered the correct verification code or password. if the verification code or password is correct, the method verifies the user’s identity. if the verification code or password isn’t valid, the service returns an error message. examples this example shows multi-factor authentication using email. public void initverification() { // user will receive code on their registered verified email identifier = usermanagement.initverificationmethod(auth.verificationmethod.email); } public auth.verificationresult verifyverification() { // requiring identifier from the initverification // the code will need to be entered in this method return usermanagement.verifyverificationmethod(identifier, code , auth.verificationmethod.email); }
the next two examples show multi-factor authentication using only the verifyverificationmethod for password and totp verifications. public auth.verificationresult verifyverification() { // user will enter their password as a param in the verifyverificationmethod for password verification method return usermanagement.verifyverificationmethod('', password , auth.verificationmethod.password); } public auth.verificationresult verifyverification() { // user will enter their registered time-based one-time password (totp) code (token) return usermanagement.verifyverificationmethod('', code , auth.verificationmethod.totp); } version class use the version methods to get the version of a first-generation managed package, and to compare package versions. namespace system 3521apex reference guide version class usage a package version is a number that identifies the set of components uploaded in a package. the version number has the format majornumber.minornumber.patchnumber (for example, 2.1.3). the major and minor numbers increase to a chosen value during every major release. the patchnumber is generated and updated only for a patch release. a called component can check the version against which the caller was compiled using the system.requestversion method and behave differently depending on the caller’s expectations. this allows you to continue to support existing behavior in classes and triggers in previous package versions while continuing to evolve the code. the value returned by the system.requestversion method is an instance of this class with a two-part version number containing a major and a minor number. since the system.requestversion method doesn’t return a patch number, the patch number in the returned version object is null. the system.version class can also hold also a three-part version number that includes a patch number. example this example shows how to use the methods in this class, along with the requestversion method, to determine the managed package version of the code that is calling your package. if (system.requestversion() == new version(1,0)) { // do something } if ((system.requestversion().major() == 1) && (system.requestversion().minor() > 0) && (system.requestversion().minor() <=9)) { // do something different for versions 1.1 to 1.9 } else if (system.requestversion().compareto(new version(2,0)) >= 0) { // do something completely different for versions 2.0 or greater } in this section: version constructors version methods version constructors the following are constructors for version. in this section: version(major, minor) creates a new instance of the version class as a two-part package version using the specified major and minor version numbers. version(major, minor, patch) creates a new instance of the version class as a three-part package version using the specified major, minor, and patch version numbers. 3522apex reference guide version class version(major, minor) creates a new instance of the version class as a two-part package version using the specified major and minor version numbers. signature public version(integer major, integer minor) parameters major type: integer the major version number. minor type: integer the minor version number. version(major, minor, patch) creates a new instance of the version class as a three-part package version using the specified major, minor, and patch version numbers. signature public version(integer major, integer minor, integer patch) parameters major type: integer the major version number. minor type: integer the minor version number. patch type: integer the patch version number. version methods the following are methods for version. all are instance methods. in this section: compareto(version) compares the current version with the specified version. 3523apex reference guide version class major() returns the major package version of the of the calling code. minor() returns the minor package version of the calling code. patch() returns the patch package version of the calling code or null if there is no patch version. compareto(version) compares the current version with the specified version. signature public integer compareto(system.version version) parameters version type: system.version return value type: integer returns one of the following values: • zero if the current package version is equal to the specified package version • an
integer value greater than zero if the current package version is greater than the specified package version • an integer value less than zero if the current package version is less than the specified package version usage if a two-part version is being compared to a three-part version, the patch number is ignored and the comparison is based only on the major and minor numbers. major() returns the major package version of the of the calling code. signature public integer major() return value type: integer minor() returns the minor package version of the calling code. 3524apex reference guide webservicecallout class signature public integer minor() return value type: integer patch() returns the patch package version of the calling code or null if there is no patch version. signature public integer patch() return value type: integer webservicecallout class enables making callouts to soap operations on an external web service. this class is used in the apex stub class that is auto-generated from a wsdl. namespace system in this section: webservicecallout methods see also: apex developer guide: soap services: defining a class from a wsdl document webservicecallout methods the following is the static method for webservicecallout. in this section: invoke(stub, request, response, infoarray) invokes an external soap web service operation based on an apex class that is auto-generated from a wsdl. invoke(stub, request, response, infoarray) invokes an external soap web service operation based on an apex class that is auto-generated from a wsdl. 3525apex reference guide webservicemock interface signature public static void invoke(object stub, object request, map<string,object> response, list<string> infoarray) parameters stub type: object an instance of the apex class that is auto-generated from a wsdl (the stub class). request type: object the request to the external service. the request is an instance of a type that is created as part of the auto-generated stub class. response type: map<string, object> a map of key-value pairs that represent the response that the external service sends after receiving the request. in each pair, the key is a response identifier. the value is the response object, which is an instance of a type that is created as part of the auto-generated stub class. infoarray type: string[] an array of strings that contains information about the callout—web service endpoint, soap action, request, and response. the order of the elements in the array matters. • element at index 0 ([0]): one of the following options for identifying the url of the external web service. – endpoint url. for example: 'http://yourserver/yourservice' – named credential url, which contains the scheme callout, the name of the named credential, and optionally, an appended path. for example: 'callout:mynamedcredential/some/path' • element at index 1 ([1]): the soap action. for example: 'urn:dotnet.callouttest.soap.sforce.com/echostring' • element at index 2 ([2]): the request namespace. for example: 'http://doc.sample.com/docsample' • element at index 3 ([3]): the request name. for example: 'echostring' • element at index 4 ([4]): the response namespace. for example: 'http://doc.sample.com/docsample' • element at index 5 ([5]): the response name. for example: 'echostringresponse' • element at index 6 ([6]): the response type. for example: 'docsample.echostringresponse_element' return value type: void see also: apex developer guide: named credentials as callout endpoints webservicemock interface enables sending fake responses when testing web service callouts of a class auto-generated from a wsdl. 3526apex reference guide webservicemock interface namespace system usage for an implementation example, see test web service callouts. webservicemock methods the following are methods for webservicemock. in this section: doinvoke(stub, soaprequest, responsemap, endpoint, soapaction, requestname, responsenamespace, responsename, responsetype) the implementation of this method is called by the apex runtime to send a fake response when a web service call
out is made after test.setmock has been called. doinvoke(stub, soaprequest, responsemap, endpoint, soapaction, requestname, responsenamespace, responsename, responsetype) the implementation of this method is called by the apex runtime to send a fake response when a web service callout is made after test.setmock has been called. signature public void doinvoke(object stub, object soaprequest, map<string,object> responsemap, string endpoint, string soapaction, string requestname, string responsenamespace, string responsename, string responsetype) parameters stub type: object an instance of the auto-generated class. soaprequest type: object the soap web service request being invoked. responsemap type: map<string, object> a collection of key/value pairs representing the response to send for the request. when implementing this interface, set the responsemap argument to a key/value pair representing the response desired. endpoint type: string the endpoint url for the request. 3527apex reference guide xmlstreamreader class soapaction type: string the requested soap operation. requestname type: string the requested soap operation name. responsenamespace type: string the response namespace. responsename type: string the name of the response element as defined in the wsdl. responsetype type: string the class for the response as defined in the auto-generated class. return value type: void usage xmlstreamreader class the xmlstreamreader class provides methods for forward, read-only access to xml data. you can pull data from xml or skip unwanted events. you can parse nested xml content that’s up to 50 nodes deep. namespace system usage the xmlstreamreader class is similar to the xmlstreamreader utility class from stax (streaming api for xml). stax is an api to read and write xml documents, originating from the java programming language community. note: the xmlstreamreader class in apex is based on its counterpart in java. see java xmlstreamreader class. in this section: xmlstreamreader constructors 3528apex reference guide xmlstreamreader class xmlstreamreader methods see also: apex developer guide: reading xml using streams xmlstreamreader constructors the following are constructors for xmlstreamreader. in this section: xmlstreamreader(xmlinput) creates a new instance of the xmlstreamreader class for the specified xml input. xmlstreamreader(xmlinput) creates a new instance of the xmlstreamreader class for the specified xml input. signature public xmlstreamreader(string xmlinput) parameters xmlinput type: string the xml string input. xmlstreamreader methods the following are methods for xmlstreamreader. all are instance methods. in this section: getattributecount() returns the number of attributes on the start element, excluding namespace definitions. getattributelocalname(index) returns the local name of the attribute at the specified index. getattributenamespace(index) returns the namespace uri of the attribute at the specified index. getattributeprefix(index) returns the prefix of this attribute at the specified index. getattributetype(index) returns the xml type of the attribute at the specified index. getattributevalue(namespaceuri, localname) returns the value of the attribute in the specified localname at the specified uri. 3529apex reference guide xmlstreamreader class getattributevalueat(index) returns the value of the attribute at the specified index. geteventtype() returns the type of xml event the cursor is pointing to. getlocalname() returns the local name of the current event. getlocation() return the current location of the cursor. getnamespace() if the current event is a start element or end element, this method returns the uri of the prefix or the default namespace. getnamespacecount() returns the number of namespaces declared on a start element or end element. getnamespaceprefix(index) returns the prefix for the namespace declared at the index. getnamespaceuri(prefix) return the uri for the given prefix. getnamespaceuriat(index) returns the uri for the namespace declared at the index. getpidata() returns the data section of a processing instruction. getpitarget() returns the target section of a processing instruction. getprefix()
returns the prefix of the current xml event or null if the event does not have a prefix. gettext() returns the current value of the xml event as a string. getversion() returns the xml version specified on the xml declaration. returns null if none was declared. hasname() returns true if the current xml event has a name. returns false otherwise. hasnext() returns true if there are more xml events and false if there are no more xml events. hastext() returns true if the current event has text, false otherwise. ischaracters() returns true if the cursor points to a character data xml event. otherwise, returns false. isendelement() returns true if the cursor points to an end tag. otherwise, it returns false. isstartelement() returns true if the cursor points to a start tag. otherwise, it returns false. 3530apex reference guide xmlstreamreader class iswhitespace() returns true if the cursor points to a character data xml event that consists of all white space. otherwise it returns false. next() reads the next xml event. a processor may return all contiguous character data in a single chunk, or it may split it into several chunks. returns an integer which indicates the type of event. nexttag() skips any white space (the iswhitespace method returns true), comment, or processing instruction xml events, until a start element or end element is reached. returns the index for that xml event. setcoalescing(returnassingleblock) if you specify true for returnassingleblock, text is returned in a single block, from a start element to the first end element or the next start element, whichever comes first. if you specify it as false, the parser may return text in multiple blocks. setnamespaceaware(isnamespaceaware) if you specify true for isnamespaceaware, the parser recognizes namespace. if you specify it as false, the parser does not. the default value is true. tostring() returns a string containing the length of the input xml given to xmlstreamreader and the first 50 characters of the input xml. getattributecount() returns the number of attributes on the start element, excluding namespace definitions. signature public integer getattributecount() return value type: integer usage this method is only valid on a start element or attribute xml events. the count for the number of attributes for an attribute xml event starts with zero. getattributelocalname(index) returns the local name of the attribute at the specified index. signature public string getattributelocalname(integer index) parameters index type: integer 3531apex reference guide xmlstreamreader class return value type: string usage if there is no name, an empty string is returned. this method is only valid with start element or attribute xml events. getattributenamespace(index) returns the namespace uri of the attribute at the specified index. signature public string getattributenamespace(integer index) parameters index type: integer return value type: string usage if no namespace is specified, null is returned. this method is only valid with start element or attribute xml events. getattributeprefix(index) returns the prefix of this attribute at the specified index. signature public string getattributeprefix(integer index) parameters index type: integer return value type: string usage if no prefix is specified, null is returned. this method is only valid with start element or attribute xml events. 3532
apex reference guide xmlstreamreader class getattributetype(index) returns the xml type of the attribute at the specified index. signature public string getattributetype(integer index) parameters index type: integer return value type: string usage for example, id is an attribute type. this method is only valid with start element or attribute xml events. getattributevalue(namespaceuri, localname) returns the value of the attribute in the specified localname at the specified uri. signature public string getattributevalue(string namespaceuri, string localname) parameters namespaceuri type: string localname type: string return value type: string usage returns null if the value is not found. you must specify a value for localname. this method is only valid with start element or attribute xml events. getattributevalueat(index) returns the value of the attribute at the specified index. 3533apex reference guide xmlstreamreader class signature public string getattributevalueat(integer index) parameters index type: integer return value type: string usage this method is only valid with start element or attribute xml events. geteventtype() returns the type of xml event the cursor is pointing to. signature public system.xmltag geteventtype() return value type: system.xmltag xmltag enum the values for xmltag are: • attribute • cdata • characters • comment • dtd • end_document • end_element • entity_declaration • entity_reference • namespace • notation_declaration • processing_instruction • space • start_document • start_element 3534apex reference guide xmlstreamreader class getlocalname() returns the local name of the current event. signature public string getlocalname() return value type: string usage for start element or end element xml events, it returns the local name of the current element. for the entity reference xml event, it returns the entity name. the current xml event must be start element, end element, or entity reference. getlocation() return the current location of the cursor. signature public string getlocation() return value type: string usage if the location is unknown, returns -1. the location information is only valid until the next method is called. getnamespace() if the current event is a start element or end element, this method returns the uri of the prefix or the default namespace. signature public string getnamespace() return value type: string usage returns null if the xml event does not have a prefix. 3535apex reference guide xmlstreamreader class getnamespacecount() returns the number of namespaces declared on a start element or end element. signature public integer getnamespacecount() return value type: integer usage this method is only valid on a start element, end element, or namespace xml event. getnamespaceprefix(index) returns the prefix for the namespace declared at the index. signature public string getnamespaceprefix(integer index) parameters index type: integer return value type: string usage returns null if this is the default namespace declaration. this method is only valid on a start element, end element, or namespace xml event. getnamespaceuri(prefix) return the uri for the given prefix. signature public string getnamespaceuri(string prefix) parameters prefix type: string 3536apex reference guide xmlstreamreader class return value type: string usage the returned uri depends on the current state of the processor. getnamespaceuriat(index) returns the uri for the namespace declared at the index. signature public string getnamespaceuriat(integer index) parameters index type: integer return value type: string usage this method is only valid on a start element, end element, or namespace xml event. getpidata() returns the data section of a processing instruction. signature public string getpidata() return value type: string getpitarget() returns the target section of a processing instruction. signature public string getpitarget() return value type: string 3537apex reference guide xmlstreamreader class getprefix()
returns the prefix of the current xml event or null if the event does not have a prefix. signature public string getprefix() return value type: string gettext() returns the current value of the xml event as a string. signature public string gettext() return value type: string usage the valid values for the different events are: • the string value of a character xml event • the string value of a comment • the replacement value for an entity reference. for example, assume gettext reads the following xml snippet: <!entity title "salesforce for dummies" > ]> <moo a=\"b\">name &title;</moo>'; the gettext method returns salesforce for dummies, not &title. • the string value of a cdata section • the string value for a space xml event • the string value of the internal subset of the dtd getversion() returns the xml version specified on the xml declaration. returns null if none was declared. signature public string getversion() 3538apex reference guide xmlstreamreader class return value type: string hasname() returns true if the current xml event has a name. returns false otherwise. signature public boolean hasname() return value type: boolean usage this method is only valid for start element and stop element xml events. hasnext() returns true if there are more xml events and false if there are no more xml events. signature public boolean hasnext() return value type: boolean usage this method returns false if the current xml event is end document. hastext() returns true if the current event has text, false otherwise. signature public boolean hastext() return value type: boolean usage the following xml events have text: characters, entity reference, comment and space. 3539apex reference guide xmlstreamreader class ischaracters() returns true if the cursor points to a character data xml event. otherwise, returns false. signature public boolean ischaracters() return value type: boolean isendelement() returns true if the cursor points to an end tag. otherwise, it returns false. signature public boolean isendelement() return value type: boolean isstartelement() returns true if the cursor points to a start tag. otherwise, it returns false. signature public boolean isstartelement() return value type: boolean iswhitespace() returns true if the cursor points to a character data xml event that consists of all white space. otherwise it returns false. signature public boolean iswhitespace() return value type: boolean 3540apex reference guide xmlstreamreader class next() reads the next xml event. a processor may return all contiguous character data in a single chunk, or it may split it into several chunks. returns an integer which indicates the type of event. signature public integer next() return value type: integer nexttag() skips any white space (the iswhitespace method returns true), comment, or processing instruction xml events, until a start element or end element is reached. returns the index for that xml event. signature public integer nexttag() return value type: integer usage this method throws an error if elements other than white space, comments, processing instruction, start elements or stop elements are encountered. setcoalescing(returnassingleblock) if you specify true for returnassingleblock, text is returned in a single block, from a start element to the first end element or the next start element, whichever comes first. if you specify it as false, the parser may return text in multiple blocks. signature public void setcoalescing(boolean returnassingleblock) parameters returnassingleblock type: boolean return value type: void 3541apex reference guide xmlstreamwriter class setnamespaceaware(isnamespaceaware) if you specify true for isnamespaceaware, the parser recognizes namespace. if you specify it as false, the parser does not. the default value is true. signature public void setnamespaceaware(boolean isnamespaceaware) parameters isnamespaceaware type: boolean return value type: void tostring() returns a string containing the length of the input xml given to xmlstreamreader and the first 50 characters of the input xml. signature public string tostring() return value type: string xmlstreamwriter class the xmlstreamwriter class provides methods for writing xml
data. namespace system usage you can use the xmlstreamwriter class to programmatically construct an xml document, then use http classes to send the document to an external server. the xmlstreamwriter class is similar to the xmlstreamwriter utility class from stax (streaming api for xml). stax is an api to read and write xml documents, originating from the java programming language community. note: the xmlstreamwriter class in apex is based on its counterpart in java. see java xmlstreamwriter class. in this section: xmlstreamwriter constructors 3542apex reference guide xmlstreamwriter class xmlstreamwriter methods see also: http class httprequest class httpresponse class xmlstreamwriter constructors the following are constructors for xmlstreamwriter. in this section: xmlstreamwriter() creates a new instance of the xmlstreamwriter class. xmlstreamwriter() creates a new instance of the xmlstreamwriter class. signature public xmlstreamwriter() xmlstreamwriter methods the following are methods for xmlstreamwriter. all are instance methods. in this section: close() closes this instance of an xmlstreamwriter and free any resources associated with it. getxmlstring() returns the xml written by the xmlstreamwriter instance. setdefaultnamespace(uri) binds the specified uri to the default namespace. this uri is bound in the scope of the current start_element – end_element pair. writeattribute(prefix, namespaceuri, localname, value) writes an attribute to the output stream. writecdata(data) writes the specified cdata to the output stream. writecharacters(text) writes the specified text to the output stream. writecomment(comment) writes the specified comment to the output stream. 3543apex reference guide xmlstreamwriter class writedefaultnamespace(namespaceuri) writes the specified namespace to the output stream. writeemptyelement(prefix, localname, namespaceuri) writes an empty element tag to the output stream. writeenddocument() closes any start tags and writes corresponding end tags to the output stream. writeendelement() writes an end tag to the output stream, relying on the internal state of the writer to determine the prefix and local name. writenamespace(prefix, namespaceuri) writes the specified namespace to the output stream. writeprocessinginstruction(target, data) writes the specified processing instruction. writestartdocument(encoding, version) writes the xml declaration using the specified xml encoding and version. writestartelement(prefix, localname, namespaceuri) writes the start tag specified by localname to the output stream. close() closes this instance of an xmlstreamwriter and free any resources associated with it. signature public void close() return value type: void getxmlstring() returns the xml written by the xmlstreamwriter instance. signature public string getxmlstring() return value type: string setdefaultnamespace(uri) binds the specified uri to the default namespace. this uri is bound in the scope of the current start_element – end_element pair. 3544apex reference guide xmlstreamwriter class signature public void setdefaultnamespace(string uri) parameters uri type: string return value type: void writeattribute(prefix, namespaceuri, localname, value) writes an attribute to the output stream. signature public void writeattribute(string prefix, string namespaceuri, string localname, string value) parameters prefix type: string namespaceuri type: string localname type: string specifies the name of the attribute. value type: string return value type: void writecdata(data) writes the specified cdata to the output stream. signature public void writecdata(string data) parameters data type: string 3545apex reference guide xmlstreamwriter class return value type: void writecharacters(text) writes the specified text to the output stream. signature public void writecharacters(string text) parameters text type: string return value type: void writecomment(comment) writes the specified comment to the output stream. signature public void writecomment(string comment) parameters comment type: string
return value type: void writedefaultnamespace(namespaceuri) writes the specified namespace to the output stream. signature public void writedefaultnamespace(string namespaceuri) parameters namespaceuri type: string 3546apex reference guide xmlstreamwriter class return value type: void writeemptyelement(prefix, localname, namespaceuri) writes an empty element tag to the output stream. signature public void writeemptyelement(string prefix, string localname, string namespaceuri) parameters prefix type: string localname type: string specifies the name of the tag to be written. namespaceuri type: string return value type: void writeenddocument() closes any start tags and writes corresponding end tags to the output stream. signature public void writeenddocument() return value type: void writeendelement() writes an end tag to the output stream, relying on the internal state of the writer to determine the prefix and local name. signature public void writeendelement() return value type: void 3547apex reference guide xmlstreamwriter class writenamespace(prefix, namespaceuri) writes the specified namespace to the output stream. signature public void writenamespace(string prefix, string namespaceuri) parameters prefix type: string namespaceuri type: string return value type: void writeprocessinginstruction(target, data) writes the specified processing instruction. signature public void writeprocessinginstruction(string target, string data) parameters target type: string data type: string return value type: void writestartdocument(encoding, version) writes the xml declaration using the specified xml encoding and version. signature public void writestartdocument(string encoding, string version) parameters encoding type: string 3548apex reference guide territorymgmt namespace version type: string return value type: void writestartelement(prefix, localname, namespaceuri) writes the start tag specified by localname to the output stream. signature public void writestartelement(string prefix, string localname, string namespaceuri) parameters prefix type: string localname type: string namespaceuri type: string return value type: void territorymgmt namespace the territorymgmt namespace provides an interface used for territory management. the following is the interface in the territorymgmt namespace. in this section: opportunityterritory2assignmentfilter global interface apex interface that allows an implementing class to assign a single territory to an opportunity. opportunityterritory2assignmentfilter global interface apex interface that allows an implementing class to assign a single territory to an opportunity. namespace territorymgmt 3549apex reference guide opportunityterritory2assignmentfilter global interface usage method called by opportunity territory assignment job to assign territory to opportunity. input is a list of (up to 1000) opportunityids that have isexcludedfromterritory2filter=false. returns a map of opportunityid to territory2id, which is used to update the territory2id field on the opportunity object. in this section: opportunityterritory2assignmentfilter methods opportunityterritory2assignmentfilter example implementation opportunityterritory2assignmentfilter methods the following are methods for opportunityterritory2assignmentfilter. in this section: getopportunityterritory2assignments(opportunityids) returns the mapping of opportunities to territory ids. when salesforce invokes this method, it supplies the list of opportunity ids, except for opportunities that have been excluded from territory assignment (isexcludedfromterritory2filter=false). getopportunityterritory2assignments(opportunityids) returns the mapping of opportunities to territory ids. when salesforce invokes this method, it supplies the list of opportunity ids, except for opportunities that have been excluded from territory assignment (isexcludedfromterritory2filter=false). signature public map<id,id> getopportunityterritory2assignments(list<id> opportunityids) parameters opportunityids type: list<id> opportunity ids. return value type: map<id,id> a key value pair associating each territory id to an opportunity
id. opportunityterritory2assignmentfilter example implementation this is an example implementation of the territorymgmt.opportunityterritory2assignmentfilter interface. /*** apex version of the default logic. * if opportunity's assigned account is assigned to * case 1: 0 territories in active model * then set territory2id = null * case 2: 1 territory in active model 3550apex reference guide opportunityterritory2assignmentfilter global interface * then set territory2id = account's territory2id * case 3: 2 or more territories in active model * then set territory2id = account's territory2id that is of highest priority. * but if multiple territories have same highest priority, then set territory2id = null */ global class oppterrassigndefaultlogicfilter implements territorymgmt.opportunityterritory2assignmentfilter { /** * no-arg constructor. */ global oppterrassigndefaultlogicfilter() {} /** * get mapping of opportunity to territory2id. the incoming list of opportunityids contains only those with isexcludedfromterritory2filter=false. * if territory2id = null in result map, clear the opportunity.territory2id if set. * if opportunity is not present in result map, its territory2id remains intact. */ global map<id,id> getopportunityterritory2assignments(list<id> opportunityids) { map<id, id> oppidterritoryidresult = new map<id, id>(); // get the active territory model id id activemodelid = getactivemodelid(); if(activemodelid != null){ list<opportunity> opportunities = [select id, accountid, territory2id from opportunity where id in :opportunityids]; set<id> accountids = new set<id>(); // create set of parent accountids for(opportunity opp:opportunities){ if(opp.accountid != null){ accountids.add(opp.accountid); } } map<id,territory2priority> accountmaxpriorityterritory = getaccountmaxpriorityterritory(activemodelid, accountids); // for each opportunity, assign the highest priority territory if there is no conflict, else assign null. for(opportunity opp: opportunities){ territory2priority tp = accountmaxpriorityterritory.get(opp.accountid); // assign highest priority territory if there is only 1. if((tp != null) && (tp.moreterritoriesatpriority == false) && (tp.territory2id != opp.territory2id)){ oppidterritoryidresult.put(opp.id, tp.territory2id); }else{ oppidterritoryidresult.put(opp.id, null); } } } return oppidterritoryidresult; 3551apex reference guide opportunityterritory2assignmentfilter global interface } /** * query assigned territoryids in active model for given accountids. * create a map of accountid to max priority territory. */ private map<id,territory2priority> getaccountmaxpriorityterritory(id activemodelid, set<id> accountids){ map<id,territory2priority> accountmaxpriorityterritory = new map<id,territory2priority>(); for(objectterritory2association ota:[select objectid, territory2id, territory2.territory2type.priority from objectterritory2association where objectid in :accountids and territory2.territory2modelid = :activemodelid]){ territory2priority tp = accountmaxpriorityterritory.get(ota.objectid); if((tp == null) || (ota.territory2.territory2type.priority > tp.priority)){ // if this is the first territory examined for account or it has greater priority than current highest priority territory, then set this as new highest priority territory. tp = new territory2priority(ota.territory2id,ota.territory2.territory2type.priority,false); }else if(ota.territ
ory2.territory2type.priority == tp.priority){ // the priority of current highest territory is same as this, so set moreterritoriesatpriority to indicate multiple highest priority territories seen so far. tp.moreterritoriesatpriority = true; } accountmaxpriorityterritory.put(ota.objectid, tp); } return accountmaxpriorityterritory; } /** * get the id of the active territory model. * if none exists, return null. */ private id getactivemodelid() { list<territory2model> models = [select id from territory2model where state = 'active']; id activemodelid = null; if(models.size() == 1){ activemodelid = models.get(0).id; } return activemodelid; } /** * helper class to help capture territory2id, its priority, and whether there are more territories with same priority assigned to the account. */ private class territory2priority { public id territory2id { get; set; } 3552apex reference guide txnsecurity namespace public integer priority { get; set; } public boolean moreterritoriesatpriority { get; set; } territory2priority(id territory2id, integer priority, boolean moreterritoriesatpriority){ this.territory2id = territory2id; this.priority = priority; this.moreterritoriesatpriority = moreterritoriesatpriority; } } } txnsecurity namespace the txnsecurity namespace provides an interface used for transaction security. the following is the interface and its supporting class in the txnsecurity namespace. in this section: event class contains event information that the evaluate method uses to evaluate a transaction security policy. eventcondition interface allows an implementing class to specify whether to take action when certain events occur based on a transaction security policy. this interface is only used for apex policies created in real-time event monitoring. asynccondition interface allows an implementing class to make asynchronous apex calls. this interface is used only for transaction security apex policies created in real-time event monitoring. policycondition interface apex interface that allows an implementing class to specify actions to take when certain events occur based on a transaction security policy. event class contains event information that the evaluate method uses to evaluate a transaction security policy. namespace txnsecurity usage the event class contains the information needed to determine if the event triggers a transaction security policy. not all class attributes are used for every type of event. tip: the eventclass interface applies only to legacy transaction security, which is a retired feature as of summer '20. use the eventcondition interface instead of the eventclass interface. 3553apex reference guide event class in this section: event constructors event properties event constructors the following is the constructor for event. in this section: event() creates an instance of the txnsecurity.event class. event() creates an instance of the txnsecurity.event class. signature public event() event properties the following are properties for event. in this section: action specifies the action being taken on the resource for an entity event. for example, a login ip resource for an entity event could have an action of create. the action attribute is not used by any other event type. data contains data used by actions. for example, data for a login event includes the login history id. returns a map whose keys are the type of event data, like sourceip. entityid the id of any entity associated with the event. for example, the entityid of a dataexport event for an account object contains the account id. entityname the name of the object the event acts on. organizationid the id of the salesforce org where the event occurred. resourcetype the type of resource for the event. for example, an accessresource event could have a connected application as a resource type. not all event types have resources. timestamp the time the event occurred. 3554apex reference guide event class userid identifies the user that caused the event. action specifies the action being taken on the resource for an entity event. for example, a login ip resource for an entity event could have an action of create. the action attribute is not used by any other event type. signature public string action {get; set;} property value type
: string data contains data used by actions. for example, data for a login event includes the login history id. returns a map whose keys are the type of event data, like sourceip. signature public map<string,string> data {get; set;} property value type: map<string, string> the following table lists all the available data types. not all types appear with all event types. the data type values are always string representations. for example, the isapi value is a string in the map, but is actually a boolean value. convert the value from a string to its true type this way: boolean.valueof(event.data.get('isapi')); key name true value type events supported actionname string values are: entity • convert • delete • insert • undelete • update • upsert apitype string (enum manifested as a string) dataexport, login application string accessresource, dataexport clientid string (id of the client) dataexport connectedappid string (id of the connected app) accessresource, dataexport 3555apex reference guide event class key name true value type events supported executiontime milliseconds dataexport isapi boolean dataexport isscheduled boolean dataexport loginhistoryid string dataexport, login numberofrecords integer dataexport policyid string (id of the current policy) all events sessionlevel string (enum manifested as a string. values include accessresource standard and high_assurance) sourceip string (ipv4 address) accessresource username string entity entityid the id of any entity associated with the event. for example, the entityid of a dataexport event for an account object contains the account id. signature public string entityid {get; set;} property value type: string entityname the name of the object the event acts on. signature public string entityname {get; set;} property value type: string organizationid the id of the salesforce org where the event occurred. signature public string organizationid {get; set;} 3556apex reference guide eventcondition interface property value type: string resourcetype the type of resource for the event. for example, an accessresource event could have a connected application as a resource type. not all event types have resources. signature public string resourcetype {get; set;} property value type: string timestamp the time the event occurred. signature public datetime timestamp {get; set;} property value type: datetime userid identifies the user that caused the event. signature public string userid {get; set;} property value type: string eventcondition interface allows an implementing class to specify whether to take action when certain events occur based on a transaction security policy. this interface is only used for apex policies created in real-time event monitoring. usage the evaluate method is called upon the occurrence of a real-time event monitored by a transaction security policy. a typical implementation first selects the fields of interest from the event. then the fields are tested to see if they meet the conditions being monitored. if the conditions are met, the method returns true. 3557apex reference guide eventcondition interface for example, imagine a transaction security policy that triggers when a user queries more than 1,000 lead records. for each api event, the evaluate method checks whether the rowsprocessed value is greater than 1,000 and the queriedentities value contains “lead”. if so, true is returned. we recommend having test classes for the policy condition interface to ensure it works correctly. testing is required regardless of whether the policy is moved from a sandbox to production, with a change set, or some other way. for example, test your policies in your development environment before moving the policies to production. for more information about testing apex transaction security policies, read transaction security apex testing. in this section: eventcondition methods eventcondition example implementation eventcondition methods the following are methods for eventcondition. in this section: evaluate(event) evaluates an event against a transaction security policy created in real-time event monitoring. if the event triggers the policy, the method returns true. evaluate(event) evaluates an event against a transaction security policy created in real-time event monitoring. if the event triggers the policy, the method returns true. signature public boolean evaluate(sobject event) parameters var1 type: sobject the
event to check against the transaction security policy. return value type: boolean returns true when the policy is triggered. for example, suppose that the policy is to limit users to a single login session. if a user tries to log in a second time, the policy blocks the attempted login, and updates the status, policyid, and policyoutcome fields of that loginevent. the policy also sends an email notification to the salesforce admin. the evaluate method only checks the login event, and returns true if it’s the user’s second login attempt. the system performs the action and notification, not the evaluate method. 3558apex reference guide asynccondition interface eventcondition example implementation this example shows an implementation of the txnsecurity.eventcondition interface. the transaction security policy triggers when the user queries an account object. global class blockaccountquerieseventcondition implements txnsecurity.eventcondition { public boolean evaluate(sobject event) { switch on event { when apievent apievent { return handleapievent(apievent); } when null { // trigger action if event is null return true; } when else { // trigger action for unhandled events return true; } } } private boolean handleapievent(apievent apievent){ if(apievent.queriedentities.contains('account')){ return true; } return false; } } for more examples, see enhanced apex transaction security implementation examples. asynccondition interface allows an implementing class to make asynchronous apex calls. this interface is used only for transaction security apex policies created in real-time event monitoring. namespace txnsecurity usage if you make an asynchronous apex call in the class that implements your transaction security policy condition, the class must implement the txnsecurity.asynccondition interface in addition to txnsecurity.eventcondition. use asynchronous apex instead of apex callouts and dml statements, neither of which is allowed in transaction security apex policies. apex offers multiple ways to run your apex code asynchronously and all are supported in the txnsecurity.asynccondition interface. this interface has no methods. 3559apex reference guide policycondition interface in this section: asynccondition example implementation see also: apex developer guide:asynchronous apex asynccondition example implementation here’s an example implementation of the txnsecurity.asynccondition interface. the transaction security policy triggers when a user logs in. in the example, externalvalidation__c is a custom object that contains information from an external validation system. the result of the soql query on externalvalidation__c determines whether to block the user from logging in. the policy then queues the callouttoexternalvalidator class for asynchronous execution. when it executes, the callouttoexternalvalidator class makes an external call to the validation system to update it with information about this log in event. because callouttoexternalvalidator is triggered by asynchronous apex, you must implement the txnsecurity.asynccondition interface in the externallyvalidatedlogincondition apex class along with the usual txnsecurity.eventcondition interface. global class externallyvalidatedlogincondition implements txnsecurity.eventcondition, txnsecurity.asynccondition { public boolean evaluate(sobject event) { loginevent loginevent = (loginevent) event; boolean userblocked = [select blocked from externalvalidation__c where loginid = loginevent.userid][0].blocked; system.enqueuejob(new callouttoexternalvalidator(loginevent.sourceip, loginevent.loginurl)); return userblocked; } } public class callouttoexternalvalidator implements queueable { private string sourceip; private string loginurl; public callouttoexternalvalidator(string sourceip, string loginurl) { this.sourceip = sourceip; this.loginurl = loginurl; } public void execute(queueablecontext context) { // callout to external validation service // pass sourceip, loginurl // update externalvalidation__c } } policycondition interface apex interface that allows an implementing class to specify actions to take when certain events occur based on a transaction security policy. 3560apex reference guide policycondition interface namespace txnsecurity usage tip: the policycondition interface applies only to legacy transaction security, which is a retired feature as of summer '20. use the eventcondition interface instead of the policycondition interface. the evaluate method is called upon the
occurrence of an event monitored by a transaction security policy. a typical implementation first selects the item of interest from the event. then the item is tested to see if it meets the condition being monitored. if the condition is met, the method returns true. for example, imagine a transaction security policy that checks for the same user logging in more than once. for each login event, the method would check if the user logging in already has a login session in progress, and if so, true is returned. we recommend having test classes for the policy condition interface to ensure it works correctly. testing is required regardless of whether the policy is moved from a sandbox to production, with a change set, or some other way. for example, test your policies in your development environment before moving the policies to production. don’t include dml statements in your custom policies because they can cause errors. when you send a custom email via apex during transaction policy evaluation, you get an error, even if the record isn’t explicitly related to another record. for more information, see apex dml operations in the apex reference guide. in this section: policycondition methods policycondition methods the following is the method for policycondition. in this section: evaluate(event) evaluates an event against a transaction security policy. if the event triggers the policy, true is returned. evaluate(event) evaluates an event against a transaction security policy. if the event triggers the policy, true is returned. signature public boolean evaluate(txnsecurity.event event) parameters event type: txnsecurity.event the event to check against the transaction security policy. 3561apex reference guide userprovisioning namespace return value type: boolean when the policy is triggered, true is returned. for example, let’s suppose the policy is to limit users to a single login session. if anyone tries to log in a second time, the policy’s action requires that they end their current session. the policy also sends an email notification to the salesforce admin. the evaluate() method only checks the login event, and returns true if it’s the user’s second login. the transaction security system performs the action and notification, and not the evaluate() method. userprovisioning namespace the userprovisioning namespace provides methods for monitoring outbound user provisioning requests. the following is the class in the userprovisioning namespace. in this section: connectortestutil class enables developers to write apex test classes for connectors used by the connected app provisioning solution. this class simulates provisioning for the associated app. userprovisioninglog class provides methods for writing messages to monitor outbound user provisioning requests. userprovisioningplugin class the userprovisioningplugin base class implements process.plugin for programmatic customization of the user provisioning process for connected apps. connectortestutil class enables developers to write apex test classes for connectors used by the connected app provisioning solution. this class simulates provisioning for the associated app. namespace userprovisioning usage use this class for connector-based test accelerators. you can invoke it only from within an apex test. example this example creates an instance of a connected app, gets a value, and checks whether the value is correct. the test is simply a row inserted in the database table. @istest private class scimcreateuserplugintest { public static void callplugin(boolean validinputparams) { 3562apex reference guide connectortestutil class //create an instance of a connected app connectedapplication capp =userprovisioning.connectortestutil.createconnectedapp('testapp'); profile p = [select id from profile where name='standard user']; //create a user user user = new user(username='[email protected]', firstname= 'test', lastname='user1', email='[email protected]', federationidentifier='[email protected]', profileid= p.id, communitynickname='tuser1', alias='tuser', timezonesidkey='gmt', localesidkey='en_us', emailencodingkey='iso-8859-1', languagelocalekey='en_us'); //insert user into a row in the database table insert user; //create a upr userprovisioningrequest upr = new userprovisioningrequest(appname = capp.name, connectedappid=capp.id, operation='create',
state='new', approvalstatus='notrequired',salesforceuserid=user.id); //insert the upr to test the flow end to end insert upr; }} in this section: connectortestutil method see also: salesforce help: user provisioning for connected apps connectortestutil method the connectortestutil class has 1 method. in this section: createconnectedapp(connectedappname) creates an instance of a connected app to simulate provisioning. createconnectedapp(connectedappname) creates an instance of a connected app to simulate provisioning. signature public static connectedapplication createconnectedapp(string connectedappname) parameters connectedappname type: string 3563apex reference guide userprovisioninglog class name of the connected app to test for provisioning. return value type: connectedapplication the instance of the connected app to test for provisioning. userprovisioninglog class provides methods for writing messages to monitor outbound user provisioning requests. namespace userprovisioning example this example writes the user account information sent to a third-party system for a provisioning request to the userprovisioninglog object. string inputparamsstr = 'input parameters: uprid=' + uprid + ', endpointurl=' + endpointurl + ', adminusername=' + adminusername + ', email=' + email + ', username=' + username + ', defaultpassword=' + defaultpassword + ', defaultroles =' + defaultroles; userprovisioning.userprovisioninglog.log(uprid, inputparamsstr); in this section: userprovisioninglog methods userprovisioninglog methods the following are methods for userprovisioninglog. all methods are static. in this section: log(userprovisioningrequestid, details) writes a specific message, such as an error message, to monitor the progress of a user provisioning request. log(userprovisioningrequestid, status, details) writes a specific status and message, such a status and detailed error message, to monitor the progress of a user provisioning request. log(userprovisioningrequestid, externaluserid, externalusername, userid, details) writes a specific message, such as an error message, to monitor the progress of a user provisioning request associated with a specific user. log(userprovisioningrequestid, details) writes a specific message, such as an error message, to monitor the progress of a user provisioning request. 3564apex reference guide userprovisioninglog class signature public void log(string userprovisioningrequestid, string details) parameters userprovisioningrequestid type: string a unique identifier for the user provisioning request. details type: string the text for the message. return value type: void log(userprovisioningrequestid, status, details) writes a specific status and message, such a status and detailed error message, to monitor the progress of a user provisioning request. signature public void log(string userprovisioningrequestid, string status, string details) parameters userprovisioningrequestid type: string a unique identifier for the user provisioning request. status type: string a description of the current state. for example, while invoking a third-party api, the status could be invoke. details type: string the text for the message. return value type: void log(userprovisioningrequestid, externaluserid, externalusername, userid, details) writes a specific message, such as an error message, to monitor the progress of a user provisioning request associated with a specific user. 3565apex reference guide userprovisioningplugin class signature public void log(string userprovisioningrequestid, string externaluserid, string externalusername, string userid, string details) parameters userprovisioningrequestid type: string a unique identifier for the user provisioning request. externaluserid type: string the unique identifier for the user in the target system. externalusername type: string the username for the user in the target system. userid type: string salesforce id of the user making the request. details type: string the text for the message. return value type: void userprovisioningplugin class the userprovisioningplugin base class implements process.plugin for programmatic customization of
the user provisioning process for connected apps. namespace userprovisioning usage extending this class gives you a plug-in that can be used flow builder as a legacy apex action, with the following input and output parameters. input parameter name description userprovisioningrequestid the unique id of the request for the plug-in to process. userid the id of the associated user for the request. 3566apex reference guide userprovisioningplugin class input parameter name description namedcreddevname the unique api name for the named credential to use for a request. the named credential identifies the third-party system and the third-party authentication settings. when the named credential is set in the user provisioning wizard, salesforce stores the value in the userprovisioningconfig.namedcredentialid field. reconfilter when collecting and analyzing users on a third-party system, the plug-in uses this filter to limit the scope of the collection. when the filter is set in the user provisioning wizard, salesforce stores the value in the userprovisioningconfig.reconfilter field. reconoffset when collecting and analyzing users on a third-party system, the plug-in uses this value as the starting point for the collection. output parameter name description status the vendor-specific status of the provisioning operation on the third-party system. details the vendor-specific message related to the status of the provisioning operation on the third-party system. externaluserid the vendor-specific id for the associated user on the third-party system. externalusername the vendor-specific username for the associated user on the third-party system. externalemail the email address assigned to the user on the third-party system. externalfirstname the first name assigned to the user on the third-party system. externallastname the last name assigned to the user on the third-party system. reconstate the state of the collecting and analyzing process on the third-party system. when the value is complete, the process is finished and a subsequent call to the plug-in is no longer needed, nor made. nextreconoffset when collecting and analyzing users on a third-party system, the process may encounter a transaction limit and have to stop before finishing. the value specified here initiates a call to the plug-in with a new quota limit. if you want to add more custom parameters, use the builddescribecall() method. 3567apex reference guide userprovisioningplugin class example the following example uses the builddescribecall() method to add a new input parameter and a new output parameter. the example also demonstrates how to bypass the limit of the 10,000 records processed in dml statements in an apex transaction. global class sampleconnector extends userprovisioning.userprovisioningplugin { // example of adding more input and output parameters to those defined in the base class global override process.plugindescriberesult builddescribecall() { process.plugindescriberesult describeresult = new process.plugindescriberesult(); describeresult.inputparameters = new list<process.plugindescriberesult.inputparameter>{ new process.plugindescriberesult.inputparameter('testinputparam', process.plugindescriberesult.parametertype.string, false) }; describeresult.outputparameters = new list<process.plugindescriberesult.outputparameter>{ new process.plugindescriberesult.outputparameter('testoutputparam', process.plugindescriberesult.parametertype.string) }; return describeresult; } // example plugin that demonstrates how to leverage the reconoffset/nextreconoffset/reconstate // parameters to create more than 10,000 users. (i.e. go beyond the 10,000 dml limit per transaction) global override process.pluginresult invoke(process.pluginrequest request) { map<string,string> result = new map<string,string>(); string uprid = (string) request.inputparameters.get('userprovisioningrequestid'); userprovisioning.userprovisioninglog.log(uprid, 'inserting log from test apex connector'); userprovisioningrequest upr = [select id, operation, connectedappid, state from userprovisioningrequest where id = :uprid]; if (upr.operation.equals('reconcile')) { string reconoffsetstr = (string) request.inputparameters.get('reconoffset'); integer reconoffset
= 0; if (reconoffsetstr != null) { reconoffset = integer.valueof(reconoffsetstr); } if (reconoffset > 44999) { result.put('reconstate', 'completed'); } integer i = 0; list<userprovaccountstaging> upaslist = new list<userprovaccountstaging>(); for (i = 0; i < 5000; i++) { userprovaccountstaging upas = new userprovaccountstaging(); 3568apex reference guide userprovisioningplugin class upas.name = i + reconoffset + ''; upas.externalfirstname = upas.name; upas.externalemail = '[email protected]'; upas.linkstate = 'orphaned'; upas.status = 'active'; upas.connectedappid = upr.connectedappid; upaslist.add(upas); } insert upaslist; result.put('nextreconoffset', reconoffset + 5000 + ''); } return new process.pluginresult(result); } } in this section: userprovisioningplugin methods userprovisioningplugin methods the following are methods for userprovisioningplugin. in this section: builddescribecall() use this method to add more input and output parameters to those defined in the base class. describe() returns a process.plugindescriberesult object that describes this method call. getpluginclassname() returns the name of the class implementing the plugin. invoke(request) primary method that the system invokes when the class that implements the interface is instantiated. builddescribecall() use this method to add more input and output parameters to those defined in the base class. signature public process.plugindescriberesult builddescribecall() return value type: process.plugindescriberesult 3569apex reference guide visualeditor namespace describe() returns a process.plugindescriberesult object that describes this method call. signature public process.plugindescriberesult describe() return value type: process.plugindescriberesult getpluginclassname() returns the name of the class implementing the plugin. signature public string getpluginclassname() return value type: string invoke(request) primary method that the system invokes when the class that implements the interface is instantiated. signature public process.pluginresult invoke(process.pluginrequest request) parameters request type: process.pluginrequest return value type: process.plugindescriberesult visualeditor namespace the visualeditor namespace provides classes and methods for interacting with the lightning app builder. the classes and methods in this namespace operate on lightning components, which include lightning web components and aura components. 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. 3570apex reference guide datarow class 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. the following are the classes in the visualeditor namespace. in this section: datarow class contains information about one item in a picklist used in a lightning component on a lightning page. designtimepagecontext class an abstract class that provides context information about a lightning page. it can be used to help define the values of a picklist in a lightning component on a lightning page based on the page’s type and the object with which it’s associated. dynamicpicklist class an abstract class, used to display the values of a picklist in a lightning component on a lightning page. dynamicpicklistrows class contains a list of picklist items in a lightning component on a lightning page. datarow class contains information about one item in a picklist used in a lightning component on a lightning page. namespace visualeditor in this section: datarow constructors datarow methods datarow constructors the following are constructors for datarow. in this section: datarow(label, value, selected) creates an instance of the visualeditor.datarow class using the specified label, value, and selected option. datarow(label
, value) creates an instance of the visualeditor.datarow class using the specified label and value. datarow(label, value, selected) creates an instance of the visualeditor.datarow class using the specified label, value, and selected option. signature public datarow(string label, object value, boolean selected) 3571apex reference guide datarow class parameters label type: string user-facing label for the picklist item. value type: object the value of the picklist item. selected type: boolean specifies whether the picklist item is selected (true) or not (false). datarow(label, value) creates an instance of the visualeditor.datarow class using the specified label and value. signature public datarow(string label, object value) parameters label type: string user-facing label for the picklist item. value type: object the value of the picklist item. datarow methods the following are methods for datarow. in this section: clone() makes a duplicate copy of the visualeditor.datarow object. compareto(o) compares the current visualeditor.datarow object to the specified one. returns an integer value that is the result of the comparison. getlabel() returns the user-facing label of the picklist item. getvalue() returns the value of the picklist item. isselected() returns the state of the picklist item, indicating whether it’s selected or not. 3572apex reference guide datarow class clone() makes a duplicate copy of the visualeditor.datarow object. signature public object clone() return value type: object compareto(o) compares the current visualeditor.datarow object to the specified one. returns an integer value that is the result of the comparison. signature public integer compareto(visualeditor.datarow o) parameters o type: visualeditor.datarow a single item in a picklist. return value type: integer returns one of the following values: • zero if the current package version is equal to the specified package version • an integer value greater than zero if the current package version is greater than the specified package version • an integer value less than zero if the current package version is less than the specified package version getlabel() returns the user-facing label of the picklist item. signature public string getlabel() return value type: string getvalue() returns the value of the picklist item. 3573apex reference guide designtimepagecontext class signature public object getvalue() return value type: object isselected() returns the state of the picklist item, indicating whether it’s selected or not. signature public boolean isselected() return value type: boolean designtimepagecontext class an abstract class that provides context information about a lightning page. it can be used to help define the values of a picklist in a lightning component on a lightning page based on the page’s type and the object with which it’s associated. namespace visualeditor usage to use this class, create a parameterized constructor in the custom apex class that extends visualeditor.dynamicpicklist. example here’s an example of a custom apex class extending the visualeditor.dynamicpicklist class. it includes visualeditor.designtimepagecontext to define a picklist value that is available only if the page type is homepage. global class mycustompicklist extends visualeditor.dynamicpicklist{ visualeditor.designtimepagecontext context; global mycustompicklist(visualeditor.designtimepagecontext context) { this.context = context; } global override visualeditor.datarow getdefaultvalue(){ visualeditor.datarow defaultvalue = new visualeditor.datarow('red', 'red'); return defaultvalue; } global override visualeditor.dynamicpicklistrows getvalues() { visualeditor.datarow value1 = new visualeditor.datarow('red', 'red'); 3574apex reference guide designtimepagecontext class visualeditor.datarow value2 = new visualeditor.datarow('yellow', 'yellow'); visualeditor.dynamicpicklistrows myvalues = new visualeditor.dynamicpicklistrows(); myvalues.addrow(value1); myvalues.addrow(value2); if (context.pagetype == 'homepage') { visualeditor.datarow value3
= new visualeditor.datarow('purple', 'purple'); myvalues.addrow(value3); } return myvalues; } } in this section: designtimepagecontext properties designtimepagecontext methods designtimepagecontext properties the following are properties for designtimepagecontext. in this section: entityname the api name of the sobject that a lightning page is associated with, such as account, contact or custom_object__c. not all lightning pages are associated with objects. pagetype the type of lightning page, such as homepage, apppage, or recordpage. entityname the api name of the sobject that a lightning page is associated with, such as account, contact or custom_object__c. not all lightning pages are associated with objects. signature public string entityname {get; set;} property value type: string pagetype the type of lightning page, such as homepage, apppage, or recordpage. 3575apex reference guide dynamicpicklist class signature public string pagetype {get; set;} property value type: string designtimepagecontext methods the following are methods for designtimepagecontext. in this section: clone() makes a duplicate copy of the visualeditor.designtimepagecontext object. clone() makes a duplicate copy of the visualeditor.designtimepagecontext object. signature public object clone() return value type: object dynamicpicklist class an abstract class, used to display the values of a picklist in a lightning component on a lightning page. namespace visualeditor usage to use this class as the datasource of a picklist in a lightning component, it must be extended by a custom apex class and then that class must be called in the component’s design file. example here’s an example of a custom apex class extending the visualeditor.dynamicpicklist class. global class mycustompicklist extends visualeditor.dynamicpicklist{ global override visualeditor.datarow getdefaultvalue(){ visualeditor.datarow defaultvalue = new visualeditor.datarow('red', 'red'); 3576apex reference guide dynamicpicklist class return defaultvalue; } global override visualeditor.dynamicpicklistrows getvalues() { visualeditor.datarow value1 = new visualeditor.datarow('red', 'red'); visualeditor.datarow value2 = new visualeditor.datarow('yellow', 'yellow'); visualeditor.dynamicpicklistrows myvalues = new visualeditor.dynamicpicklistrows(); myvalues.addrow(value1); myvalues.addrow(value2); return myvalues; } } here’s an example of how the custom apex class gets called in a design file so that the picklist appears in the lightning component. <design:component> <design:attribute name="property1" datasource="apex://mycustompicklist"/> </design:component> in this section: dynamicpicklist methods dynamicpicklist methods the following are methods for dynamicpicklist. in this section: clone() makes a duplicate copy of the visualeditor.dynamicpicklist object. getdefaultvalue() returns the picklist item that is set as the default value for the picklist. getlabel(attributevalue) returns the user-facing label for a specified picklist value. getvalues() returns the list of picklist item values. isvalid(attributevalue) returns the valid state of the picklist item’s value. a picklist value is considered valid if it’s a part of any visualeditor.datarow in the visualeditor.dynamicpicklistrows returned by getvalues(). clone() makes a duplicate copy of the visualeditor.dynamicpicklist object. signature public object clone() 3577apex reference guide dynamicpicklist class return value type: object getdefaultvalue() returns the picklist item that is set as the default value for the picklist. signature public visualeditor.datarow getdefaultvalue() return value type: visualeditor.datarow getlabel(attributevalue) returns the user-facing label for a specified picklist value. signature public string getlabel(object attributevalue) parameters attributevalue type: object the value of the picklist item. return value type: string getvalues() returns the list of picklist item values. signature public visualeditor.dynamicpicklistrows getvalues() return
value type: visualeditor.dynamicpicklistrows isvalid(attributevalue) returns the valid state of the picklist item’s value. a picklist value is considered valid if it’s a part of any visualeditor.datarow in the visualeditor.dynamicpicklistrows returned by getvalues(). 3578apex reference guide dynamicpicklistrows class signature public boolean isvalid(object attributevalue) parameters attributevalue type: object the value of the picklist item. return value type: boolean dynamicpicklistrows class contains a list of picklist items in a lightning component on a lightning page. namespace visualeditor in this section: dynamicpicklistrows constructors dynamicpicklistrows methods dynamicpicklistrows constructors the following are constructors for dynamicpicklistrows. in this section: dynamicpicklistrows(rows, containsallrows) creates an instance of the visualeditor.dynamicpicklistrows class using the specified parameters. dynamicpicklistrows(rows) creates an instance of the visualeditor.dynamicpicklistrows class using the specified parameter. dynamicpicklistrows() creates an instance of the visualeditor.dynamicpicklistrows class. you can then add rows by using the class’s addrow or addallrows methods. dynamicpicklistrows(rows, containsallrows) creates an instance of the visualeditor.dynamicpicklistrows class using the specified parameters. signature public dynamicpicklistrows(list<visualeditor.datarow> rows, boolean containsallrows) 3579apex reference guide dynamicpicklistrows class parameters rows type: list visualeditor.datarow list of picklist items. containsallrows type: boolean indicates if all values of the picklist are included in a type-ahead search query (true) or only those values initially displayed when the list is clicked on (false). a picklist in a lightning component can display only the first 200 values of a list. if containsallrows is set to false, when a user does a type-ahead search to find values in the picklist, the search will only look at those first 200 values that were displayed, not the complete set of picklist values. dynamicpicklistrows(rows) creates an instance of the visualeditor.dynamicpicklistrows class using the specified parameter. signature public dynamicpicklistrows(list<visualeditor.datarow> rows) parameters rows type: list visualeditor.datarow list of picklist rows. dynamicpicklistrows() creates an instance of the visualeditor.dynamicpicklistrows class. you can then add rows by using the class’s addrow or addallrows methods. signature public dynamicpicklistrows() dynamicpicklistrows methods the following are methods for dynamicpicklistrows. in this section: addallrows(rows) adds a list of picklist items to a dynamic picklist rendered in a lightning component on a lightning page. addrow(row) adds a single picklist item to a dynamic picklist rendered in a lightning component on a lightning page. clone() makes a duplicate copy of the visualeditor.dynamicpicklistrows object. 3580apex reference guide dynamicpicklistrows class containsallrows() returns a boolean value indicating whether all values of the picklist are included when a user does a type-ahead search query (true) or only those values initially displayed when the list is clicked on (false). get(i) returns a picklist element stored at the specified index. getdatarows() returns a list of picklist items. setcontainsallrows(containsallrows) sets the value indicating whether all values of the picklist are included when a user does a type-ahead search query (true) or only those values initially displayed when the list is clicked on (false). size() returns the size of the list of visualeditor.dynamicpicklistrows. sort() sorts the list of visualeditor.dynamicpicklistrows. addallrows(rows) adds a list of picklist items to a dynamic picklist rendered in a lightning component on a lightning page. signature public void addallrows(list<visualeditor.datarow> rows) parameters rows type: list visualeditor.datarow list of picklist items. return value
type: void addrow(row) adds a single picklist item to a dynamic picklist rendered in a lightning component on a lightning page. signature public void addrow(visualeditor.datarow row) parameters row type: visualeditor.datarow a single picklist item. 3581apex reference guide dynamicpicklistrows class return value type: void clone() makes a duplicate copy of the visualeditor.dynamicpicklistrows object. signature public object clone() return value type: object containsallrows() returns a boolean value indicating whether all values of the picklist are included when a user does a type-ahead search query (true) or only those values initially displayed when the list is clicked on (false). signature public boolean containsallrows() return value type: boolean a picklist in a lightning component can display only the first 200 values of a list. if containsallrows is set to false, when a user does a type-ahead search to find values in the picklist, the search will only look at those first 200 values that were displayed, not the complete set of picklist values. get(i) returns a picklist element stored at the specified index. signature public visualeditor.datarow get(integer i) parameters i type: integer the index. return value type: visualeditor.datarow 3582
apex reference guide dynamicpicklistrows class getdatarows() returns a list of picklist items. signature public list<visualeditor.datarow> getdatarows() return value type: list visualeditor.datarow setcontainsallrows(containsallrows) sets the value indicating whether all values of the picklist are included when a user does a type-ahead search query (true) or only those values initially displayed when the list is clicked on (false). signature public void setcontainsallrows(boolean containsallrows) parameters containsallrows type: boolean indicates if all values of the picklist are included in a type-ahead search query (true) or only those values initially displayed when the list is clicked on (false). a picklist in a lightning component can display only the first 200 values of a list. if containsallrows is set to false, when a user does a type-ahead search to find values in the picklist, the search will only look at those first 200 values that were displayed, not the complete set of picklist values. return value type: void size() returns the size of the list of visualeditor.dynamicpicklistrows. signature public integer size() return value type: integer sort() sorts the list of visualeditor.dynamicpicklistrows. 3583apex reference guide wave namespace signature public void sort() return value type: void wave namespace the classes in the wave namespace are part of the crm analytics analytics sdk, designed to facilitate querying crm analytics data from apex code. the following are the classes in the wave namespace. in this section: querybuilder class the querybuilder class provides methods for constructing well-formed saql queries to pass to crm analytics. querynode class define each node of the query - such as projection, groups, order, filters. execute the query. projectionnode class add aggregate functions to the query, or define an alias. templates class the templates class provides methods for retrieving crm analytics template collections, individual templates, and template configurations. templatessearchoptions class the templatessearchoptions class provides optional properties to filter the template collection. querybuilder class the querybuilder class provides methods for constructing well-formed saql queries to pass to crm analytics. namespace wave usage use querybuilder and its associated classes, wave.projectionnode and wave.querynode, to incrementally build your saql statement. for example: public static void executeapexquery(string name){ wave.projectionnode[] projs = new wave.projectionnode[]{ wave.querybuilder.get('state').alias('state'), wave.querybuilder.get('city').alias('city'), wave.querybuilder.get('revenue').avg().alias('avg_revenue'), wave.querybuilder.get('revenue').sum().alias('sum_revenue'), 3584apex reference guide querybuilder class wave.querybuilder.count().alias('count')}; connectapi.literaljson result = wave.querybuilder.load('0fbd00000004dszkam', '0fcd00000004fezka2') .group(new string[]{'state', 'city'}) .foreach(projs) .execute('q'); string response = result.json; } examples querybuilder is the core of this first phase of the crm analytics apex sdk, so let’s take a closer look. here’s a simple count query. wave.projectionnode[] projs = new wave.projectionnode[]{wave.querybuilder.count().alias('c')}; string query = wave.querybuilder.load('datasetid', 'datasetversionid').group().foreach(projs).build('q'); the resulting saql query looks like this: q = load "datasetid/datasetversionid"; q = group q by all; q = foreach q generate count as c; here’s a more complex example that uses a union statement. wave.projectionnode[] projs = new wave.projectionnode[]{wave.querybuilder.get('name'), wave.querybuilder.get('annualrevenue').alias('revenue')}; wave.querynode nodeone = wave.querybuilder.load('datasetone','datasetversionone').foreach
(projs); wave.querynode nodetwo = wave.querybuilder.load('datasettwo', 'datasetversiontwo').foreach(projs); string query = wave.querybuilder.union(new list<wave.querynode>{nodeone, nodetwo}).build('q'); the resulting saql query has two projection streams, qa and qb. qa = load "datasetone/datasetversionone"; qa = foreach q generate name,annualrevenue as revenue; qb = load "datasettwo/datasetversiontwo"; qb = foreach q generate name,annualrevenue as revenue; q = union qa, qb; in this section: querybuilder methods querybuilder methods the following are methods for querybuilder. 3585apex reference guide querybuilder class in this section: load(datasetid, datasetversionid) load a stream from a dataset. count() calculate the number of rows that match the query criteria. get(projection) query by selecting specific attributes. union(unionnodes) combine multiple result sets into one result set. cogroup(cogroupnodes, groups) cogrouping means that two input streams are grouped independently and arranged side by side. only data that exists in both groups appears in the results. load(datasetid, datasetversionid) load a stream from a dataset. signature public static wave.querynode load(string datasetid, string datasetversionid) parameters datasetid type: string the id of the dataset. datasetversionid type: string the id identifying the version of the dataset. return value type: wave.querynode count() calculate the number of rows that match the query criteria. signature public static wave.projectionnode count() return value type: wave.projectionnode 3586apex reference guide querybuilder class get(projection) query by selecting specific attributes. signature public static wave.projectionnode get(string proj) parameters proj type: string the name of the column to query. return value type: wave.projectionnode union(unionnodes) combine multiple result sets into one result set. signature global static wave.querynode union(list<wave.querynode> unionnodes) parameters unionnodes type: list<wave.querynode> list of nodes to combine. return value type: wave.querynode cogroup(cogroupnodes, groups) cogrouping means that two input streams are grouped independently and arranged side by side. only data that exists in both groups appears in the results. signature global static wave.querynode cogroup(list<wave.querynode> cogroupnodes, list<list<string>> groups) parameters cogroupnodes type: wave.querynode 3587apex reference guide querynode class list of nodes to group. groups type: string the type of grouping. return value type: wave.querynode querynode class define each node of the query - such as projection, groups, order, filters. execute the query. namespace wave usage refer to the querybuilder example. in this section: querynode methods querynode methods the following are methods for querynode. in this section: build(streamname) build the query string represented by this querynode and assign it to a stream name. foreach(projections) applies a set of expressions to every row in a dataset. this action is often referred to as projection. group(groups) groups matched records (group by specific dataset attributes). group() groups matched records (group by all). order(orders) sorts in ascending or descending order on one or more fields. cap(cap) limits the number of results that are returned. filter(filtercondition) selects rows from a dataset based on a filter condition (a predicate). 3588apex reference guide querynode class filter(filterconditions) selects rows from a dataset based on multiple filter conditions (predicates). execute(streamname) execute the query and return rows as json. build(streamname) build the query string represented by this querynode and assign it to a stream name. signature public string build(string streamname) parameters streamname type
: string the identifier for the stream - for example, “q”. return value type: string the saql query string represented by the querynode. foreach(projections) applies a set of expressions to every row in a dataset. this action is often referred to as projection. signature public wave.querynode foreach(list<wave.projectionnode> projections) parameters projections type: list<wave.projectionnode> a list of projectionnodes to be added to this querynode. return value type: wave.querynode group(groups) groups matched records (group by specific dataset attributes). signature public wave.querynode group(list<string> groups) 3589apex reference guide querynode class parameters groups type: list<string> a list of expressions. return value type: wave.querynode example wave.projectionnode[] projs = new wave.projectionnode[]{wave.querybuilder.get('name'), wave.querybuilder.get('revenue').sum().alias('revenue_sum')}; connectapi.literaljson result = wave.querybuilder.load('datasetid', 'datasetversionid').group(new string[]{'name'}).foreach(projs).build('q'); group() groups matched records (group by all). signature public wave.querynode group() return value type: wave.querynode example string query = wave.querybuilder.load('datasetid', 'datasetversionid').group().foreach(projs).build('q'); order(orders) sorts in ascending or descending order on one or more fields. signature public wave.querynode group(list<string> groups) parameters groups type: list<string> a list of column names and associated ascending or descending keywords, for example list<list<string>>{new list<string>{'name', 'asc'}, new list<string>{'revenue', 'desc'}} 3590apex reference guide querynode class return value type: wave.querynode cap(cap) limits the number of results that are returned. signature global wave.querynode cap(integer cap) parameters cap type: integer the maximum number of rows to return. return value type: wave.querynode filter(filtercondition) selects rows from a dataset based on a filter condition (a predicate). signature public wave.querynode filter(string filtercondition) parameters filtercondition type: string for example: filter('name != \'my name\'') return value type: wave.querynode filter(filterconditions) selects rows from a dataset based on multiple filter conditions (predicates). signature public wave.querynode filter(list<string> filtercondition) 3591apex reference guide projectionnode class parameters filtercondition type: list<string> a list of filter conditions. return value type: wave.querynode execute(streamname) execute the query and return rows as json. signature global connectapi.literaljson execute(string streamname) parameters streamname type: string the query stream to execute. for example: connectapi.literaljson result = wave.querybuilder.load('datasetid', 'datasetversionid').group().foreach(projs).execute('q'); return value type: connectapi.literaljson projectionnode class add aggregate functions to the query, or define an alias. namespace wave on page 3584 usage refer to the querybuilder example. in this section: projectionnode methods projectionnode methods the following are methods for projectionnode. 3592apex reference guide projectionnode class in this section: sum() returns the sum of a numeric field. avg() returns the average value of a numeric field. min() returns the minimum value of a field. max() returns the maximum value of a field. count() returns the number of rows that match the query criteria. unique() returns the count of unique values. alias(name) define output column names. sum() returns the sum of a numeric field. signature public wave.projectionnode sum() return value type: wave.projectionnode avg()
returns the average value of a numeric field. signature public wave.projectionnode avg() return value type: wave.projectionnode min() returns the minimum value of a field. signature public wave.projectionnode min() 3593apex reference guide projectionnode class return value type: wave.projectionnode max() returns the maximum value of a field. signature public wave.projectionnode max() return value type: wave.projectionnode count() returns the number of rows that match the query criteria. signature public wave.projectionnode count() return value type: wave.projectionnode unique() returns the count of unique values. signature public wave.projectionnode unique() return value type: wave.projectionnode alias(name) define output column names. signature public wave.projectionnode alias(string name) 3594apex reference guide templates class parameters name type: string the name to use for this column. for example, this code defines the alias c: wave.projectionnode[] projs = new wave.projectionnode[]{wave.querybuilder.count().alias('c')}; return value type: wave.projectionnode templates class the templates class provides methods for retrieving crm analytics template collections, individual templates, and template configurations. namespace wave usage use templates and its associated class wave.templatessearchoptions to get crm analytics template information. examples this code sample declares a method that returns a list of the template names. @auraenabled(cacheable=true) public static void list<string> gettemplatenames() { map<string, object> o = wave.templates.gettemplates(new wave.templatessearchoptions()); list<object> templates = (list<object>) o.get('templates'); list<string> names = new list<string>(); for (object templateobj : templates) { names.add((string) ((map<string, object>) templateobj.get('name')); } return names; } adding the @auraenabled annotation allows lightning web components to access templates methods directly. for example, in the lwc.js file: import gettemplates from '@salesforce/apex/wave.templates.gettemplates'; export default class templates extends lightningelement { @wire(gettemplates, { // specifying 'options' is optional options: { // values in templatessearchoptions go here; all optional type: 'app' } 3595apex reference guide templates class }) ontemplates({ data, error }) { if (data) { console.log('template names=' + data.templates.map(l => l.name).join(', ')); } } } in this section: templates methods templates methods the following are methods for templates. in this section: gettemplate(templateidorapiname) gets a crm analytics template by the specified id or api name. the returned template is a map of the template json attributes as name/value pairs. gettemplateconfig(templateidorapiname) gets the crm analytics template configuration by the specified id or api name. the returned template configuration is a map of the json attributes as name/value pairs. gettemplates(options) get a filtered collection of crm analytics templates using search options. gettemplates() gets all crm analytics templates. gettemplate(templateidorapiname) gets a crm analytics template by the specified id or api name. the returned template is a map of the template json attributes as name/value pairs. signature public static map<string,object> gettemplate(string templateidorapiname) parameters templateidorapiname type: string the template id or api name of the template to retrieve. return value type: map<string,object> 3596apex reference guide templates class a map of the template json attribute name/value pairs, where the name is a string with an object value. for attributes details, see templaterepresentation. example string templatename = (string) wave.templates.gettemplate(templateid).get('name'); gettemplateconfig(templateidorapiname) gets the crm analytics template configuration by the specified id or api name. the returned template configuration is a map of the
json attributes as name/value pairs. signature public static map<string,object> gettemplateconfig(string templateidorapiname) parameters templateidorapiname type: string the template id or developer name to retrieve the template configuration for. return value type: map<string,object> a map of template configuration json attribute names and the object values. for attribute details, see templateconfigurationrepresentation. example map<string, object> templatevariables = (map<string, object>) wave.templates.gettemplateconfig(templateid).get('variables'); gettemplates(options) get a filtered collection of crm analytics templates using search options. signature public static map<string,object> gettemplates(wave.templatessearchoptions options) parameters options type: wave.templatessearchoptions on page 3598 the search options to use for filtering the template collection. 3597apex reference guide templatessearchoptions class return value type: map<string,object> a map of template names and the template object values. for template collection details, see templatecollectionrepresentation. example map<string,object> templatesmap = wave.templates.gettemplates(new wave.templatessearchoptions()); gettemplates() gets all crm analytics templates. signature public static map<string,object> gettemplates() return value type: map<string,object> a map of template names and the template object values. for template collection details, see templatecollectionrepresentation. example map<string,object> templatesmap = wave.templates.gettemplates(); templatessearchoptions class the templatessearchoptions class provides optional properties to filter the template collection. namespace wave usage use templatessearchoptions with wave.templates class to filter the crm analytics template collection returned. for example: public static void list<string> getapptemplates() { wave.templatesearchoptions tsoptions = new wave.templatessearchoptions(); tsoptions.type = 'app'; map<string, object> o = wave.templates.gettemplates(tsoptions); list<object> apptemplates = (list<object>) o.get('templates'); list<string> names = new list<string>(); for (object templateobj : apptemplates) { names.add((string) ((map<string, object>) templateobj.get('name')); } 3598apex reference guide templatessearchoptions class return names; } in this section: templatessearchoptions properties templatessearchoptions properties the following are properties for templatessearchoptions. in this section: filtergroup specifies the connect api filter group for crm analytics template search options. options specifies the template visibility option to filter the crm analytics template collection by. type sets the template type to filter the crm analytics template collection by. filtergroup specifies the connect api filter group for crm analytics template search options. signature public string filtergroup {get; set;} property value type: string uses the connectfiltergroupenum values. example wave.templatesearchoptions tsoptions = new wave.templatessearchoptions(); tsoptions.filtergroup = 'small'; options specifies the template visibility option to filter the crm analytics template collection by. signature public string options {get; set;} 3599apex reference guide appendices property value type: string uses the connectwavetemplatevisibilityoptionsenum values. valid values are createapp, viewonly, and manageableonly. example wave.templatesearchoptions tsoptions = new wave.templatessearchoptions(); tsoptions.options = 'viewonly'; type sets the template type to filter the crm analytics template collection by. signature public string type {get; set;} property value type: string uses the connectwavetemplatetypeenum values. valid values are app, dashboard, embedded, and lens. example wave.templatesearchoptions tsoptions = new wave.templatessearchoptions(); tsoptions.type = 'app'; appendices in this section: shipping invoice example reserved keywords documentation typographical conventions glossary shipping invoice example this appendix provides an example of an apex application. this is a more complex example than the hello world example. • shipping invoice walk-through • shipping invoice example code in this section: 1. shipping invoice example walk
-through 3600apex reference guide shipping invoice example 2. shipping invoice example code shipping invoice example walk-through the sample application in this section includes traditional salesforce functionality blended with apex. many of the syntactic and semantic features of apex, along with common idioms, are illustrated in this application. note: the shipping invoice 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 apex quick start. scenario in this sample application, the user creates a new shipping invoice, or order, and then adds items to the invoice. the total amount for the order, including shipping cost, is automatically calculated and updated based on the items added or deleted from the invoice. data and code models this sample application uses two new objects: item and shipping_invoice. the following assumptions are made: • item a cannot be in both orders shipping_invoice1 and shipping_invoice2. two customers cannot obtain the same (physical) product. • the tax rate is 9.25%. • the shipping rate is 75 cents per pound. • once an order is over $100, the shipping discount is applied (shipping becomes free). the fields in the item custom object include: name type description name string the name of the item price currency the price of the item quantity number the number of items in the order weight number the weight of the item, used to calculate shipping costs shipping_invoice master-detail (shipping_invoice) the order this item is associated with the fields in the shipping_invoice custom object include: name type description name string the name of the shipping invoice/order subtotal currency the subtotal grandtotal currency the total amount, including tax and shipping shipping currency the amount charged for shipping (assumes $0.75 per pound) 3601apex reference guide shipping invoice example name type description shippingdiscount currency only applied once when subtotal amount reaches $100 tax currency the amount of tax (assumes 9.25%) totalweight number the total weight of all items all of the apex for this application is contained in triggers. this application has the following triggers: object trigger name when runs description item calculate after insert, after update, after delete updates the shipping invoice, calculates the totals and shipping shipping_invoice shippingdiscount after update updates the shipping invoice, calculating if there is a shipping discount the following is the general flow of user actions and when triggers run: flow of user action and triggers for the shopping cart application 1. user clicks orders > new, names the shipping invoice and clicks save. 2. user clicks new item, fills out information, and clicks save. 3. calculate trigger runs. part of the calculate trigger updates the shipping invoice. 4. shippingdiscount trigger runs. 3602apex reference guide shipping invoice example 5. user can then add, delete or change items in the invoice. in shipping invoice example code both of the triggers and the test class are listed. the comments in the code explain the functionality. testing the shipping invoice application before an application can be included as part of a package, 75% of the code must be covered by unit tests. therefore, one piece of the shipping invoice application is a class used for testing the triggers. the test class verifies the following actions are completed successfully: • inserting items • updating items • deleting items • applying shipping discount • negative test for bad input shipping invoice example code the following triggers and test class make up the shipping invoice example application: • calculate trigger • shippingdiscount trigger • test class calculate trigger trigger calculate on item__c (after insert, after update, after delete) { // use a map because it doesn't allow duplicate values map<id, shipping_invoice__c> updatemap = new map<id, shipping_invoice__c>(); // set this integer to -1 if we are deleting integer subtract ; // populate the list of items based on trigger type list<item__c> itemlist; if(trigger.isinsert || trigger.isupdate){ itemlist = trigger.new; subtract = 1; } else if(trigger.isdelete) { // note -- there is no trigger.new in delete itemlist = trigger.old; subtract = -1; } // access all the information we
need in a single query // rather than querying when we need it. // this is a best practice for bulkifying requests 3603apex reference guide shipping invoice example set<id> allitems = new set<id>(); for(item__c i :itemlist){ // assert numbers are not negative. // none of the fields would make sense with a negative value system.assert(i.quantity__c > 0, 'quantity must be positive'); system.assert(i.weight__c >= 0, 'weight must be non-negative'); system.assert(i.price__c >= 0, 'price must be non-negative'); // if there is a duplicate id, it won't get added to a set allitems.add(i.shipping_invoice__c); } // accessing all shipping invoices associated with the items in the trigger list<shipping_invoice__c> allshippinginvoices = [select id, shippingdiscount__c, subtotal__c, totalweight__c, tax__c, grandtotal__c from shipping_invoice__c where id in :allitems]; // take the list we just populated and put it into a map. // this will make it easier to look up a shipping invoice // because you must iterate a list, but you can use lookup for a map, map<id, shipping_invoice__c> simap = new map<id, shipping_invoice__c>(); for(shipping_invoice__c sc : allshippinginvoices) { simap.put(sc.id, sc); } // process the list of items if(trigger.isupdate) { // treat updates like a removal of the old item and addition of the // revised item rather than figuring out the differences of each field // and acting accordingly. // note updates have both trigger.new and trigger.old for(integer x = 0; x < trigger.old.size(); x++) { shipping_invoice__c myorder; myorder = simap.get(trigger.old[x].shipping_invoice__c); // decrement the previous value from the subtotal and weight. myorder.subtotal__c -= (trigger.old[x].price__c * trigger.old[x].quantity__c); myorder.totalweight__c -= (trigger.old[x].weight__c * trigger.old[x].quantity__c); // increment the new subtotal and weight. myorder.subtotal__c += (trigger.new[x].price__c * trigger.new[x].quantity__c); myorder.totalweight__c += (trigger.new[x].weight__c * trigger.new[x].quantity__c); } 3604apex reference guide shipping invoice example for(shipping_invoice__c myorder : allshippinginvoices) { // set tax rate to 9.25% please note, this is a simple example. // generally, you would never hard code values. // leveraging custom settings for tax rates is a best practice. // see custom settings in the apex developer guide // for more information. myorder.tax__c = myorder.subtotal__c * .0925; // reset the shipping discount myorder.shippingdiscount__c = 0; // set shipping rate to 75 cents per pound. // generally, you would never hard code values. // leveraging custom settings for the shipping rate is a best practice. // see custom settings in the apex developer guide // for more information. myorder.shipping__c = (myorder.totalweight__c * .75); myorder.grandtotal__c = myorder.subtotal__c + myorder.tax__c + myorder.shipping__c; updatemap.put(myorder.id, myorder); } } else { for(item__c itemtoprocess : itemlist) { shipping_invoice__c myorder; // look up the correct shipping invoice from the ones we got earlier myorder = simap.get(itemtoprocess.shipping_invoice__c); myorder.subtotal__c += (itemtoprocess.price__c * itemtoprocess.quantity__c * subtract); myorder.totalweight__c += (itemtoprocess.weight__c * itemtoprocess.quantity__c * subtract); } for(shipping_invoice__c my
order : allshippinginvoices) { // set tax rate to 9.25% please note, this is a simple example. // generally, you would never hard code values. // leveraging custom settings for tax rates is a best practice. // see custom settings in the apex developer guide // for more information. myorder.tax__c = myorder.subtotal__c * .0925; // reset shipping discount myorder.shippingdiscount__c = 0; // set shipping rate to 75 cents per pound. // generally, you would never hard code values. // leveraging custom settings for the shipping rate is a best practice. 3605apex reference guide shipping invoice example // see custom settings in the apex developer guide // for more information. myorder.shipping__c = (myorder.totalweight__c * .75); myorder.grandtotal__c = myorder.subtotal__c + myorder.tax__c + myorder.shipping__c; updatemap.put(myorder.id, myorder); } } // only use one dml update at the end. // this minimizes the number of dml requests generated from this trigger. update updatemap.values(); } shippingdiscount trigger trigger shippingdiscount on shipping_invoice__c (before update) { // free shipping on all orders greater than $100 for(shipping_invoice__c myshippinginvoice : trigger.new) { if((myshippinginvoice.subtotal__c >= 100.00) && (myshippinginvoice.shippingdiscount__c == 0)) { myshippinginvoice.shippingdiscount__c = myshippinginvoice.shipping__c * -1; myshippinginvoice.grandtotal__c += myshippinginvoice.shippingdiscount__c; } } } shipping invoice test @istest private class testshippinginvoice{ // test for inserting three items at once public static testmethod void testbulkiteminsert(){ // create the shipping invoice. it's a best practice to either use defaults // or to explicitly set all values to zero so as to avoid having // extraneous data in your test. shipping_invoice__c order1 = new shipping_invoice__c(subtotal__c = 0, totalweight__c = 0, grandtotal__c = 0, shippingdiscount__c = 0, shipping__c = 0, tax__c = 0); // insert the order and populate with items insert order1; list<item__c> list1 = new list<item__c>(); item__c item1 = new item__c(price__c = 10, weight__c = 1, quantity__c = 1, shipping_invoice__c = order1.id); item__c item2 = new item__c(price__c = 25, weight__c = 2, quantity__c = 1, 3606apex reference guide shipping invoice example shipping_invoice__c = order1.id); item__c item3 = new item__c(price__c = 40, weight__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); list1.add(item1); list1.add(item2); list1.add(item3); insert list1; // retrieve the order, then do assertions order1 = [select id, subtotal__c, tax__c, shipping__c, totalweight__c, grandtotal__c, shippingdiscount__c from shipping_invoice__c where id = :order1.id]; system.assert(order1.subtotal__c == 75, 'order subtotal was not $75, but was '+ order1.subtotal__c); system.assert(order1.tax__c == 6.9375, 'order tax was not $6.9375, but was ' + order1.tax__c); system.assert(order1.shipping__c == 4.50, 'order shipping was not $4.50, but was ' + order1.shipping__c); system.assert(order1.totalweight__c == 6.00, 'order weight was not 6 but was ' + order1.totalweight__c); system.assert(order1.grandtotal__c == 86.4375, 'order grand total was not $86.4375 but was ' + order1.grandtotal__c);
system.assert(order1.shippingdiscount__c == 0, 'order shipping discount was not $0 but was ' + order1.shippingdiscount__c); } // test for updating three items at once public static testmethod void testbulkitemupdate(){ // create the shipping invoice. it's a best practice to either use defaults // or to explicitly set all values to zero so as to avoid having // extraneous data in your test. shipping_invoice__c order1 = new shipping_invoice__c(subtotal__c = 0, totalweight__c = 0, grandtotal__c = 0, shippingdiscount__c = 0, shipping__c = 0, tax__c = 0); // insert the order and populate with items. insert order1; list<item__c> list1 = new list<item__c>(); item__c item1 = new item__c(price__c = 1, weight__c = 1, quantity__c = 1, shipping_invoice__c = order1.id); item__c item2 = new item__c(price__c = 2, weight__c = 2, quantity__c = 1, shipping_invoice__c = order1.id); item__c item3 = new item__c(price__c = 4, weight__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); list1.add(item1); list1.add(item2); list1.add(item3); insert list1; 3607apex reference guide shipping invoice example // update the prices on the 3 items list1[0].price__c = 10; list1[1].price__c = 25; list1[2].price__c = 40; update list1; // access the order and assert items updated order1 = [select id, subtotal__c, tax__c, shipping__c, totalweight__c, grandtotal__c, shippingdiscount__c from shipping_invoice__c where id = :order1.id]; system.assert(order1.subtotal__c == 75, 'order subtotal was not $75, but was '+ order1.subtotal__c); system.assert(order1.tax__c == 6.9375, 'order tax was not $6.9375, but was ' + order1.tax__c); system.assert(order1.shipping__c == 4.50, 'order shipping was not $4.50, but was ' + order1.shipping__c); system.assert(order1.totalweight__c == 6.00, 'order weight was not 6 but was ' + order1.totalweight__c); system.assert(order1.grandtotal__c == 86.4375, 'order grand total was not $86.4375 but was ' + order1.grandtotal__c); system.assert(order1.shippingdiscount__c == 0, 'order shipping discount was not $0 but was ' + order1.shippingdiscount__c); } // test for deleting items public static testmethod void testbulkitemdelete(){ // create the shipping invoice. it's a best practice to either use defaults // or to explicitly set all values to zero so as to avoid having // extraneous data in your test. shipping_invoice__c order1 = new shipping_invoice__c(subtotal__c = 0, totalweight__c = 0, grandtotal__c = 0, shippingdiscount__c = 0, shipping__c = 0, tax__c = 0); // insert the order and populate with items insert order1; list<item__c> list1 = new list<item__c>(); item__c item1 = new item__c(price__c = 10, weight__c = 1, quantity__c = 1, shipping_invoice__c = order1.id); item__c item2 = new item__c(price__c = 25, weight__c = 2, quantity__c = 1, shipping_invoice__c = order1.id); item__c item3 = new item__c(price__c = 40, weight__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); item__c itema = new item__c(price__c = 1, weight
__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); item__c itemb = new item__c(price__c = 1, weight__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); item__c itemc = new item__c(price__c = 1, weight__c = 3, quantity__c = 1, 3608apex reference guide shipping invoice example shipping_invoice__c = order1.id); item__c itemd = new item__c(price__c = 1, weight__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); list1.add(item1); list1.add(item2); list1.add(item3); list1.add(itema); list1.add(itemb); list1.add(itemc); list1.add(itemd); insert list1; // seven items are now in the shipping invoice. // the following deletes four of them. list<item__c> list2 = new list<item__c>(); list2.add(itema); list2.add(itemb); list2.add(itemc); list2.add(itemd); delete list2; // retrieve the order and verify the deletion order1 = [select id, subtotal__c, tax__c, shipping__c, totalweight__c, grandtotal__c, shippingdiscount__c from shipping_invoice__c where id = :order1.id]; system.assert(order1.subtotal__c == 75, 'order subtotal was not $75, but was '+ order1.subtotal__c); system.assert(order1.tax__c == 6.9375, 'order tax was not $6.9375, but was ' + order1.tax__c); system.assert(order1.shipping__c == 4.50, 'order shipping was not $4.50, but was ' + order1.shipping__c); system.assert(order1.totalweight__c == 6.00, 'order weight was not 6 but was ' + order1.totalweight__c); system.assert(order1.grandtotal__c == 86.4375, 'order grand total was not $86.4375 but was ' + order1.grandtotal__c); system.assert(order1.shippingdiscount__c == 0, 'order shipping discount was not $0 but was ' + order1.shippingdiscount__c); } // testing free shipping public static testmethod void testfreeshipping(){ // create the shipping invoice. it's a best practice to either use defaults // or to explicitly set all values to zero so as to avoid having // extraneous data in your test. shipping_invoice__c order1 = new shipping_invoice__c(subtotal__c = 0, totalweight__c = 0, grandtotal__c = 0, shippingdiscount__c = 0, shipping__c = 0, tax__c = 0); // insert the order and populate with items. insert order1; 3609apex reference guide shipping invoice example list<item__c> list1 = new list<item__c>(); item__c item1 = new item__c(price__c = 10, weight__c = 1, quantity__c = 1, shipping_invoice__c = order1.id); item__c item2 = new item__c(price__c = 25, weight__c = 2, quantity__c = 1, shipping_invoice__c = order1.id); item__c item3 = new item__c(price__c = 40, weight__c = 3, quantity__c = 1, shipping_invoice__c = order1.id); list1.add(item1); list1.add(item2); list1.add(item3); insert list1; // retrieve the order and verify free shipping not applicable order1 = [select id, subtotal__c, tax__c, shipping__c, totalweight__c, grandtotal__c, shippingdiscount__c from shipping_invoice__c where id = :order1.id]; // free shipping not available on $75 orders system.assert(
order1.subtotal__c == 75, 'order subtotal was not $75, but was '+ order1.subtotal__c); system.assert(order1.tax__c == 6.9375, 'order tax was not $6.9375, but was ' + order1.tax__c); system.assert(order1.shipping__c == 4.50, 'order shipping was not $4.50, but was ' + order1.shipping__c); system.assert(order1.totalweight__c == 6.00, 'order weight was not 6 but was ' + order1.totalweight__c); system.assert(order1.grandtotal__c == 86.4375, 'order grand total was not $86.4375 but was ' + order1.grandtotal__c); system.assert(order1.shippingdiscount__c == 0, 'order shipping discount was not $0 but was ' + order1.shippingdiscount__c); // add items to increase subtotal item1 = new item__c(price__c = 25, weight__c = 20, quantity__c = 1, shipping_invoice__c = order1.id); insert item1; // retrieve the order and verify free shipping is applicable order1 = [select id, subtotal__c, tax__c, shipping__c, totalweight__c, grandtotal__c, shippingdiscount__c from shipping_invoice__c where id = :order1.id]; // order total is now at $100, so free shipping should be enabled system.assert(order1.subtotal__c == 100, 'order subtotal was not $100, but was '+ order1.subtotal__c); system.assert(order1.tax__c == 9.25, 'order tax was not $9.25, but was ' + order1.tax__c); system.assert(order1.shipping__c == 19.50, 'order shipping was not $19.50, but was ' + order1.shipping__c); system.assert(order1.totalweight__c == 26.00, 3610apex reference guide shipping invoice example 'order weight was not 26 but was ' + order1.totalweight__c); system.assert(order1.grandtotal__c == 109.25, 'order grand total was not $86.4375 but was ' + order1.grandtotal__c); system.assert(order1.shippingdiscount__c == -19.50, 'order shipping discount was not -$19.50 but was ' + order1.shippingdiscount__c); } // negative testing for inserting bad input public static testmethod void testnegativetests(){ // create the shipping invoice. it's a best practice to either use defaults // or to explicitly set all values to zero so as to avoid having // extraneous data in your test. shipping_invoice__c order1 = new shipping_invoice__c(subtotal__c = 0, totalweight__c = 0, grandtotal__c = 0, shippingdiscount__c = 0, shipping__c = 0, tax__c = 0); // insert the order and populate with items. insert order1; item__c item1 = new item__c(price__c = -10, weight__c = 1, quantity__c = 1, shipping_invoice__c = order1.id); item__c item2 = new item__c(price__c = 25, weight__c = -2, quantity__c = 1, shipping_invoice__c = order1.id); item__c item3 = new item__c(price__c = 40, weight__c = 3, quantity__c = -1, shipping_invoice__c = order1.id); item__c item4 = new item__c(price__c = 40, weight__c = 3, quantity__c = 0, shipping_invoice__c = order1.id); try{ insert item1; } catch(exception e) { system.assert(e.getmessage().contains('price must be non-negative'), 'price was negative but was not caught'); } try{ insert item2; } catch(exception e) { system.assert(e.getmessage().contains('weight must be non-negative'), '
weight was negative but was not caught'); } try{ insert item3; } catch(exception e) { system.assert(e.getmessage().contains('quantity must be positive'), 3611apex reference guide reserved keywords 'quantity was negative but was not caught'); } try{ insert item4; } catch(exception e) { system.assert(e.getmessage().contains('quantity must be positive'), 'quantity was zero but was not caught'); } } } reserved keywords the following words can only be used as keywords. table 3: reserved keywords abstract false package activate final parallel and finally pragma any float private array for protected as from public asc global retrieve autonomous goto return begin group rollback bigdecimal having select blob hint set boolean if short break implements sobject bulk import sort by in static byte inner string case insert super cast instanceof switch catch int synchronized char integer system class interface testmethod collect into then commit join this 3612apex reference guide documentation typographical conventions const like throw continue limit time currency list transaction date long trigger datetime loop true decimal map try default merge undelete delete new update desc not upsert do null using double nulls virtual else number void end object webservice enum of when exception on where exit or while export outer extends override the following are special types of keywords that aren't reserved words and can be used as identifiers. • after • before • count • excludes • first • includes • last • order • sharing • with documentation typographical conventions apex and visualforce documentation uses the following typographical conventions. 3613apex reference guide glossary convention description courier font in descriptions of syntax, monospace font indicates items that you should type as shown, except for brackets. for example: public class helloworld italics in descriptions of syntax, italics represent variables. you supply the actual value. in the following example, three values need to be supplied: datatype variable_name [ = value]; if the syntax is bold and italic, the text represents a code element that needs a value supplied by you, such as a class name or variable value: public static class yourclasshere { ... } bold courier font in code samples and syntax descriptions, bold courier font emphasizes a portion of the code or syntax. < > in descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as shown. <apex:pageblocktable value="{!account.contacts}" var="contact"> <apex:column value="{!contact.name}"/> <apex:column value="{!contact.mailingcity}"/> <apex:column value="{!contact.phone}"/> </apex:pageblocktable> { } in descriptions of syntax, braces ({ }) are typed exactly as shown. <apex:page> hello {!$user.firstname}! </apex:page> [ ] in descriptions of syntax, anything included in brackets is optional. in the following example, specifying value is optional: data_type variable_name [ = value]; | in descriptions of syntax, the pipe sign means “or”. you can do one of the following (not all). in the following example, you can create a new unpopulated set in one of two ways, or you can populate the set: set<data_type> set_name [= new set<data_type>();] | [= new set<data_type{value [, value2. . .] };] | ; glossary a |b |c |d |e |f |g |h |i |j | l |m |n |o |p |q |r |s |t |u |v |w |x |y |z 3614apex reference guide glossary a administrator (system administrator) one or more individuals in your organization who can configure and customize the application. users assigned to the system administrator profile have administrator privileges. ajax toolkit a javascript wrapper around the api that allows you to execute any api call and access any object you have permission to view from within javascript code. for more information, see the ajax toolkit developer's guide. anti-join an anti-join is a subquery on another object in a
not in clause in a soql query. you can use anti-joins to create advanced queries. see also semi-join. anonymous block, apex apex code that doesn’t get stored in salesforce, but that can be compiled and executed by using the executeanonymousresult() api call, or the equivalent in the ajax toolkit. ant migration tool a toolkit that allows you to write an apache ant build script for migrating lightning platform components between a local file system and a salesforce organization. apex apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the lightning platform server in conjunction with calls to the lightning platform 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. apex connector framework the apex connector framework is a set of classes and methods in the datasource namespace for creating a custom adapter for salesforce connect. create a custom adapter to connect to data that’s stored outside your salesforce org when the other available salesforce connect adapters aren’t suitable for your needs. apex-managed sharing enables developers to programmatically manipulate sharing to support their application's behavior. apex-managed sharing is only available for custom objects. apex page see visualforce page. app short for “application.” a collection of components such as tabs, reports, dashboards, and visualforce pages that address a specific business need. salesforce provides standard apps such as sales and service. you can customize the standard apps to match the way you work. in addition, you can package an app and upload it to appexchange along with related components such as custom fields, custom tabs, and custom objects. then, you can make the app available to other salesforce users from appexchange. appexchange the appexchange is a sharing interface from salesforce that allows you to browse and share apps and services for the lightning platform. application programming interface (api) the interface that a computer system, library, or application provides to allow other computer programs to request services from it and exchange data. approval process an approval process automates how records are approved in salesforce. an approval process specifies each step of approval, including who to request approval from and what to do at each point of the process. 3615apex reference guide glossary asynchronous calls a call that doesn’t return results immediately because the operation can take a long time. calls in the metadata api and bulk api 2.0 are asynchronous. b batch apex the ability to perform long, complex operations on many records at a scheduled time using apex. beta, managed package in the context of managed packages, a beta managed package is an early version of a managed package distributed to a sampling of your intended audience to test it. bulk api 2.0 the rest-based bulk api 2.0 is optimized for processing large sets of data. it allows you to query, insert, update, upsert, or delete a large number of records asynchronously by submitting a job that is processed in the background by salesforce. see also soap api. c callout, apex an apex callout enables you to tightly integrate your apex with an external service by making a call to an external web service or sending a http request from apex code and then receiving the response. child relationship a relationship that has been defined on an sobject that references another sobject as the “one” side of a one-to-many relationship. for example, contacts, opportunities, and tasks have child relationships with accounts. see also sobject. class, apex a template or blueprint from which apex objects are created. classes consist of other classes, user-defined methods, variables, exception types, and static initialization code. in most cases, apex classes are modeled on their counterparts in java. client app an app that runs outside the salesforce user interface and uses only the lightning platform api or bulk api 2.0. it typically runs on a desktop or mobile device. these apps treat the platform as a data source, using the development model of whatever tool and platform for which they’re designed. code coverage a way to identify which lines of code are exercised by a set of unit tests, and which aren’t. code coverage helps you identify sections of code that are untested and therefore at greatest risk of containing a bug or introducing a regression in the future. component, met
adata a component is an instance of a metadata type in the metadata api. for example, customobject is a metadata type for custom objects, and the mycustomobject__c component is an instance of a custom object. a component is described in an xml file and it can be deployed or retrieved using the metadata api, or tools built on top of it, such as the salesforce extensions for visual studio code or the ant migration tool. component, visualforce something that can be added to a visualforce page with a set of tags, for example, <apex:detail>. visualforce includes a number of standard components, or you can create your own custom components. component reference, visualforce a description of the standard and custom visualforce components that are available in your organization. you can access the component library from the development footer of any visualforce page or the visualforce developer's guide. 3616apex reference guide glossary composite app an app that combines native platform functionality with one or more external web services, such as yahoo! maps. composite apps allow for more flexibility and integration with other services, but can require running and managing external code. see also client app and native app. controller, visualforce an apex class that provides a visualforce page with the data and business logic it must run. visualforce pages can use the standard controllers that come by default with every standard or custom object, or they can use custom controllers. controller extension a controller extension is an apex class that extends the functionality of a standard or custom controller. cookie client-specific data used by some web applications to store user and session-specific information. salesforce issues a session “cookie” only to record encrypted authentication information for the duration of a specific session. custom app see app. custom controller a custom controller is an apex class that implements all of the logic for a page without using a standard controller. use custom controllers when you want your visualforce page to run entirely in system mode, which doesn’t enforce the permissions and field-level security of the current user. custom field a field that can be added in addition to the standard fields to customize salesforce for your organization's needs. custom links custom links are urls defined by administrators to integrate your salesforce data with external websites and back-office systems. formerly known as web links. custom object custom records that allow you to store information unique to your organization. custom settings custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create 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. this data can then be used by formula fields, validation rules, flows, apex, and soap api. see also hierarchy custom settings and list custom settings. d database an organized collection of information. the underlying architecture of the lightning platform includes a database where your data is stored. database table a list of information, presented with rows and columns, about the person, thing, or concept you want to track. see also object. data loader a lightning platform tool used to import and export data from your salesforce organization. data manipulation language (dml) an apex method or operation that inserts, updates, or deletes records. 3617apex reference guide glossary data state the structure of data in an object at a particular point in time. date literal a keyword in a soql or sosl query that represents a relative range of time such as last month or next year. decimal places parameter for number, currency, and percent custom fields that indicates the total number of digits you can enter to the right of a decimal point, for example, 4.98 for an entry of 2. the system rounds the decimal numbers you enter, if necessary. for example, if you enter 4.986 in a field with decimal places of 2, the number rounds to 4.99. salesforce uses the round half-up rounding algorithm. half-way values are always rounded up. for example, 1.45 is rounded to 1.5. –1.45 is rounded to –1.5. dependency a relationship where one object's existence depends on that of another. there are a number of different kinds of dependencies including mandatory fields, dependent objects (parent-child), file inclusion (referenced images, for example), and ordering dependencies (when one object must be deployed before another object). dependent field any custom picklist or multi-select picklist field that displays available values based on the value selected in its
corresponding controlling field. deploy to move functionality from an inactive state to active. for example, when developing new features in the salesforce user interface, you must select the “deployed” option to make the functionality visible to other users. the process by which an application or other functionality is moved from development to production. to move metadata components from a local file system to a salesforce organization. for installed apps, deployment makes any custom objects in the app available to users in your organization. before a custom object is deployed, it’s only available to administrators and any users with the “customize application” permission. deprecated component developers can refine the functionality in a managed package over time as the requirements evolve, such as redesign some of the components in the managed package.developers can’t delete some components in a managed - released package, but they can deprecate a component in a later package version so that new subscribers don’t receive the component, while the component continues to function for existing subscribers and api integrations. detail a page that displays information about a single object record. the detail page of a record allows you to view the information, whereas the edit page allows you to modify it. a term used in reports to distinguish between summary information and inclusion of all column data for all information in a report. you can toggle the show details/hide details button to view and hide report detail information. developer edition a free, fully functional salesforce organization designed for developers to extend, integrate, and develop with the lightning platform. developer edition accounts are available on developer.salesforce.com. salesforce developers the salesforce developers website at developer.salesforce.com provides a full range of resources for platform developers, including sample code, toolkits, an online developer community, and the ability to obtain limited lightning platform environments. development environment a salesforce organization where you can make configuration changes that don’t affect users on the production organization. there are two kinds of development environments, sandboxes and developer edition organizations. 3618apex reference guide glossary e email alert email alerts are actions that send emails, using a specified email template, to specified recipients. email template a form email that communicates a standard message, such as a welcome letter to new employees or an acknowledgment that a customer service request has been received. email templates can be personalized with merge fields, and can be written in text, html, or custom format. note: lightning email templates aren’t packageable. enterprise edition a salesforce edition designed for larger, more complex businesses. enterprise wsdl a strongly typed wsdl for customers who want to build an integration with their salesforce organization only, or for partners who are using tools like tibco or webmethods to build integrations that require strong typecasting. the downside of the enterprise wsdl is that it only works with the schema of a single salesforce organization because it’s bound to all of the unique objects and fields that exist in that organization's data model. entity relationship diagram (erd) a data modeling tool that helps you organize your data into entities (or objects, as they’re called in the lightning platform) and define the relationships between them. erds for key salesforce objects are published in the salesforce object reference. enumeration field an enumeration is the wsdl equivalent of a picklist field. the valid values of the field are restricted to a strict set of possible values, all having the same data type. f facet a child of another visualforce component that allows you to override an area of the rendered parent with the contents of the facet. field a part of an object that holds a specific piece of information, such as a text or currency value. field dependency a filter that allows you to change the contents of a picklist based on the value of another field. field-level security settings that determine whether fields are hidden, visible, read only, or editable for users. available in professional, enterprise, unlimited, performance, and developer editions. foreign key a field whose value is the same as the primary key of another table. you can think of a foreign key as a copy of a primary key from another table. a relationship is made between two tables by matching the values of the foreign key in one table with the values of the primary key in another. g getter methods methods that enable developers to display database and other computed values in page markup. methods that return values. see also setter methods. 3619apex reference guide glossary global variable a special merge field that you can use to reference
data in your organization. a method access modifier for any method that must be referenced outside of the application, either in soap api or by other apex code. governor limits apex execution limits that prevent developers who write inefficient code from monopolizing the resources of other salesforce users. gregorian year a calendar based on a 12-month structure used throughout much of the world. h hierarchy custom settings a type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. the hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. in the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings. http debugger an application that can be used to identify and inspect soap requests that are sent from the ajax toolkit. they behave as proxy servers running on your local machine and allow you to inspect and author individual requests. i id see salesforce record id. ideaexchange salesforce’s always-on feedback platform that connects the trailblazer community with salesforce product managers. it’s the go-to place to post ideas and contribute feedback about how to improve products and experiences. visit ideaexchange at ideas.salesforce.com. import wizard a tool for importing data into your salesforce organization, accessible from setup. instance the cluster of software and hardware represented as a single logical server that hosts an organization's data and runs their applications. the lightning platform runs on multiple instances, but data for any single organization is always stored on a single instance. integrated development environment (ide) a software application that provides comprehensive facilities for software developers including a source code editor, testing and debugging tools, and integration with source code control systems. integration user a salesforce user defined solely for client apps or integrations. also referred to as the logged-in user in a soap api context. iso code the international organization for standardization country code, which represents each country by two letters. 3620apex reference guide glossary j junction object a custom object with two master-detail relationships. using a custom junction object, you can model a “many-to-many” relationship between two objects.for example, you create a custom object called “bug” that relates to the standard case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs. l length parameter for custom text fields that specifies the maximum number of characters (up to 255) that a user can enter in the field. parameter for number, currency, and percent fields that specifies the number of digits you can enter to the left of the decimal point, for example, 123.98 for an entry of 3. lightning platform the salesforce platform for building applications in the cloud. lightning platform combines a powerful user interface, operating system, and database to allow you to customize and deploy applications in the cloud for your entire enterprise. list custom settings a type of custom setting that provides a reusable set of static data that can be accessed across your organization. if you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. data in list settings doesn’t vary with profile or user, but is available organization-wide. examples of list data include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. because the data is cached, access is low-cost and efficient: you don't have to use soql queries that count against your governor limits. list view a list display of items (for example, accounts or contacts) based on specific criteria. salesforce provides some predefined views. in the agent console, the list view is the top frame that displays a list view of records based on specific criteria. the list views you can select to display in the console are the same list views defined on the tabs of other objects. you can’t create a list view within the console. local name the value stored for the field in the user's or account's language. the local name for a field is associated with the standard name for that field. locale the country or geographic region in which the user is located. the setting affects the format of date and number fields, for example, dates in the english (united states) locale display as 06/30/2000 and as 30/06/2000 in the english (united kingdom) locale. in professional, enterprise, unlimited, performance, and developer edition
organizations, a user's individual locale setting overrides the organization's default locale setting. in personal and group editions, the organization-level locale field is called locale, not default locale. long text area data type of custom field that allows entry of up to 32,000 characters on separate lines. lookup relationship a relationship between two records so you can associate records with each other. for example, cases have a lookup relationship with assets that lets you associate a particular asset with a case. on one side of the relationship, a lookup field allows users to click a lookup icon and select another record from a window. on the associated record, you can then display a related list to show all of the records that have been linked to it. if a lookup field references a record that has been deleted, by default salesforce clears the lookup field. alternatively, you can prevent records from being deleted if they're in a lookup relationship. 3621apex reference guide glossary m managed package a collection of application components that is posted as a unit on appexchange and associated with a namespace and possibly a license management organization.to support upgrades, a package must be managed. an organization can create a single managed package that can be downloaded and installed by many different organizations. managed packages differ from unmanaged packages by having some locked components, allowing the managed package to be upgraded later. unmanaged packages don’t include locked components and can’t be upgraded. in addition, managed packages obfuscate certain components (like apex) on subscribing organizations to protect the intellectual property of the developer. manual sharing record-level access rules that allow record owners to give read and edit permissions to other users who don’t have access to the record any other way. many-to-many relationship a relationship where each side of the relationship can have many children on the other side. many-to-many relationships are implemented through the use of junction objects. master-detail relationship a relationship between two different types of records that associates the records with each other. for example, accounts have a master-detail relationship with opportunities. this type of relationship affects record deletion, security, and makes the lookup relationship field required on the page layout. metadata information about the structure, appearance, and functionality of an organization and any of its parts. lightning platform uses xml to describe metadata. metadata-driven development an app development model that allows apps to be defined as declarative “blueprints,” with no code required. apps built on the platform—their data models, objects, forms, workflows, and more—are defined by metadata. metadata wsdl a wsdl for users who want to use the lightning platform metadata api calls. multitenancy an application model where all users and apps share a single, common infrastructure and code base. mvc (model-view-controller) a design paradigm that deconstructs applications into components that represent data (the model), ways of displaying that data in a user interface (the view), and ways of manipulating that data with business logic (the controller). n namespace in a packaging context, a one- to 15-character alphanumeric identifier that distinguishes your package and its contents from packages of other developers on appexchange, similar to a domain name. salesforce automatically prepends your namespace prefix, followed by two underscores (“__”), to all unique component names in your salesforce organization. native app an app that is built exclusively with setup (metadata) configuration on lightning platform. native apps don’t require any external services or infrastructure. 3622apex reference guide glossary o object an object allows you to store information in your salesforce organization. the object is the overall definition of the type of information you’re storing. for example, the case object lets you store information regarding customer inquiries. for each object, your organization has multiple records that store the information about specific instances of that type of data. for example, you can have a case record to store the information about joe smith's training inquiry and another case record to store the information about mary johnson's configuration issue. object-level help custom help text that you can provide for any custom object. it displays on custom object record home (overview), detail, and edit pages, as well as list views and related lists. object-level security settings that allow an administrator to hide whole objects from users so that they don't know that type of data exists. object-level security is specified with object permissions. one-to-many relationship a relationship in which a single object is related to many other objects. for example, an
account can have one or more related contacts. organization a deployment of salesforce with a defined set of licensed users. an organization is the virtual space provided to an individual customer of salesforce. your organization includes all of your data and applications, and is separate from all other organizations. organization-wide defaults settings that allow you to specify the baseline level of data access that a user has in your organization. for example, you can set organization-wide defaults so that any user can see any record of a particular object that is enabled via their object permissions, but they need extra permissions to edit one. outbound call any call that originates from a user to a number outside of a call center in salesforce crm call center. outbound message an outbound message sends information to a designated endpoint, like an external service. outbound messages are configured from setup. you must configure the external endpoint and create a listener for the messages using soap api. owner individual user to which a record (for example, a contact or case) is assigned. p paas see platform as a service. package a group of lightning platform components and applications that are made available to other organizations through appexchange. you use packages to bundle an app along with any related components so that you can upload them to appexchange together. package dependency this dependency is created when one component references another component, permission, or preference that is required for the component to be valid. components can include but aren’t limited to: • standard or custom fields • standard or custom objects • visualforce pages 3623apex reference guide glossary • apex code permissions and preferences can include but aren’t limited to: • divisions • multicurrency • record types package installation installation incorporates the contents of a package into your salesforce organization. a package on appexchange can include an app, a component, or a combination of the two. after you install a package, you can deploy components in the package to make it generally available to the users in your organization. package version a package version is a number that identifies the set of components uploaded in a package. the version number has the format majornumber.minornumber.patchnumber (for example, 2.1.3). the major and minor numbers increase to a chosen value during every major release. the patchnumber is generated and updated only for a patch release. unmanaged packages aren’t upgradeable, so each package version is simply a set of components for distribution. a package version has more significance for managed packages. packages can exhibit different behavior for different versions.publishers can use package versions to evolve the components in their managed packages gracefully by releasing subsequent package versions without breaking existing customer integrations using the package.see also patch and patch development organization. partner wsdl a loosely typed wsdl for customers, partners, and isvs who want to build an integration or an appexchange app that can work across multiple salesforce organizations. with this wsdl, the developer is responsible for marshaling data in the correct object representation, which typically involves editing the xml. however, the developer is also freed from being dependent on any particular data model or salesforce organization. contrast to the enterprise wsdl, which is strongly typed. patch a patch enables a developer to change the functionality of existing components in a managed package, while ensuring subscribing organizations that there are no visible behavior changes to the package.for example, you can add new variables or change the body of an apex class, but you can’t add, deprecate, or remove any of its methods. patches are tracked by a patchnumber appended to every package version. see also patch development organization and package version. patch development organization the organization where patch versions are developed, maintained, and uploaded. patch development organizations are created automatically for a developer organization when they request to create a patch. see also patch and package version. personal edition product designed for individual sales representatives and single users. platform as a service (paas) an environment where developers use programming tools offered by a service provider to create applications and deploy them in a cloud. the application is hosted as a service and provided to customers via the internet. the paas vendor provides an api for creating and extending specialized applications. the paas vendor also takes responsibility for the daily maintenance, operation, and support of the deployed application and each customer's data. the service alleviates the need for programmers to install, configure, and maintain the applications on their own hardware, software, and related it resources. services can be delivered using the paas environment to any market segment
. platform edition a salesforce edition based on enterprise, unlimited, or performance edition that doesn’t include any of the standard salesforce apps, such as sales or service & support. 3624apex reference guide glossary primary key a relational database concept. each table in a relational database has a field in which the data value uniquely identifies the record. this field is called the primary key. the relationship is made between two tables by matching the values of the foreign key in one table with the values of the primary key in another. production organization a salesforce organization that has live users accessing data. professional edition a salesforce edition designed for businesses who need full-featured crm functionality. prototype the classes, methods, and variables that are available to other apex code. q query locator a parameter returned from the query() or querymore() api call that specifies the index of the last result record that was returned. query string parameter a name-value pair that's included in a url, typically after a '?' character. for example: https://yourinstance.salesforce.com/001/e?name=value r record a single instance of a salesforce object. for example, “john jones” can be the name of a contact record. record id the unique identifier for each record. record-level security a method of controlling data in which you can allow a particular user to view and edit an object, but then restrict the records that the user is allowed to see. record locking record locking prevents users from editing a record, regardless of field-level security or sharing settings. by default, salesforce locks records that are pending approval. only admins can edit locked records. record name a standard field on all salesforce objects. whenever a record name is displayed in a lightning platform application, the value is represented as a link to a detail view of the record. a record name can be either free-form text or an autonumber field. record name doesn’t have to be a unique value. recycle bin a page that lets you view and restore deleted information. access the recycle bin either by using the link in the sidebar in salesforce classic or from the app launcher in lightning experience. relationship a connection between two objects, used to create related lists in page layouts and detail levels in reports. matching values in a specified field in both objects are used to link related data; for example, if one object stores data about companies and another object stores data about people, a relationship allows you to find out which people work at the company. 3625apex reference guide glossary relationship query in a soql context, a query that traverses the relationships between objects to identify and return results. parent-to-child and child-to-parent syntax differs in soql queries. role hierarchy a record-level security setting that defines different levels of users such that users at higher levels can view and edit information owned by or shared with users beneath them in the role hierarchy, regardless of the organization-wide sharing model settings. roll-up summary field a field type that automatically provides aggregate values from child records in a master-detail relationship. running user each dashboard has a running user, whose security settings determine which data to display in a dashboard. if the running user is a specific user, all dashboard viewers see data based on the security settings of that user—regardless of their own personal security settings. for dynamic dashboards, you can set the running user to be the logged-in user, so that each user sees the dashboard according to their own access level. s saas see software as a service (saas). s-control note: s-controls have been superseded by visualforce pages. after march 2010 organizations that have never created s-controls, as well as new organizations, won't be allowed to create them. existing s-controls remain unaffected, and can still be edited. custom web content for use in custom links. custom s-controls can contain any type of content that you can display in a browser, for example a java applet, an active-x control, an excel file, or a custom html web form. salesforce certificate and key pair salesforce certificates and key pairs are used for signatures that verify a request is coming from your organization. they’re used for authenticated ssl communications with an external website, or when using your organization as an identity provider. you only must generate a salesforce certificate and key pair if you're working with an external website that wants verification that a request is coming from a salesforce organization. salesforce connect
salesforce connect provides access to data that’s stored outside the salesforce org, such as data in an enterprise resource planning (erp) system and records in another org. salesforce connect represents the data in external objects and accesses the external data in real time via web service callouts to external data sources. 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. salesforce record id a unique 15-character or 18-character alphanumeric string that identifies a single record in salesforce. salesforce service oriented architecture a powerful capability of lightning platform that allows you to make calls to external web services from within apex. sandbox a nearly identical copy of a salesforce production organization for development, testing, and training. the content and size of a sandbox varies depending on the type of sandbox and the edition of the production organization associated with the sandbox. 3626apex reference guide glossary semi-join a semi-join is a subquery on another object in an in clause in a soql query. you can use semi-joins to create advanced queries, such as getting all contacts for accounts that have an opportunity with a particular record type. see also anti-join. session id an authentication token that is returned when a user successfully logs in to salesforce. the session id prevents a user from having to log in again every time they want to perform another action in salesforce. different from a record id or salesforce id, which are terms for the unique id of a salesforce record. session timeout the time after login before a user is automatically logged out. sessions expire automatically after a predetermined length of inactivity, which can be configured in salesforce from setup by clicking security controls. the default is 120 minutes (two hours). the inactivity timer is reset to zero if a user takes an action in the web interface or makes an api call. setter methods methods that assign values. see also getter methods. setup a menu where administrators can customize and define organization settings and lightning platform apps. depending on your organization's user interface settings, setup can be a link in the user interface header or in the dropdown list under your name. sharing allowing other users to view or edit information you own. there are different ways to share data: • sharing model—defines the default organization-wide access levels that users have to each other's information and whether to use the hierarchies when determining access to data. • role hierarchy—defines different levels of users such that users at higher levels can view and edit information owned by or shared with users beneath them in the role hierarchy, regardless of the organization-wide sharing model settings. • sharing rules—allow an administrator to specify that all information created by users within a given group or role is automatically shared to the members of another group or role. • manual sharing—allows individual users to share records with other users or groups. • apex-managed sharing—enables developers to programmatically manipulate sharing to support their application's behavior. see apex-managed sharing. sharing model behavior defined by your administrator that determines default access by users to different types of records. sharing rule type of default sharing created by administrators. allows users in a specified group or role to have access to all information created by users within a given group or role. sites salesforce sites enables you to create public websites and applications that are directly integrated with your salesforce organization—without requiring users to log in with a username and password. soap (simple object access protocol) a protocol that defines a uniform way of passing xml-encoded data. soap api a soap-based web services application programming interface that provides access to your salesforce organization's information. sobject the abstract or parent object for all objects that can be stored in the lightning platform. software as a service (saas) a delivery model where a software application is hosted as a service and provided to customers via the internet. the saas vendor takes responsibility for the daily maintenance, operation, and support of the application and each customer's data. the service 3627apex reference guide glossary alleviates the need for customers to install, configure, and maintain applications with their own hardware, software, and related it resources. services can be delivered using the saas model to any market segment. soql (salesforce object query language) a query language that allows you to construct simple
but powerful query strings and to specify the criteria that selects data from the lightning platform database. sosl (salesforce object search language) a query language that allows you to perform text-based searches using the lightning platform api. standard object a built-in object included with the lightning platform. you can also build custom objects to store information that is unique to your app. system log part of the developer console, a separate window console that can be used for debugging code snippets. enter the code you want to test at the bottom of the window and click execute. the body of the system log displays system resource information, such as how long a line took to execute or how many database calls were made. if the code didn’t run to completion, the console also displays debugging information. t tag in salesforce, a word or short phrases that users can associate with most records to describe and organize their data in a personalized way. administrators can enable tags for accounts, activities, assets, campaigns, cases, contacts, contracts, dashboards, documents, events, leads, notes, opportunities, reports, solutions, tasks, and any custom objects (except relationship group members) tags can also be accessed through soap api. test case coverage test cases are the expected real-world scenarios in which your code is used. test cases aren’t actual unit tests, but are documents that specify what your unit tests do. high test case coverage means that most or all the real-world scenarios you have identified are implemented as unit tests. see also code coverage and unit test. test method an apex class method that verifies whether a particular piece of code is working properly. test methods take no arguments, commit no data to the database, and can be executed by the runtests() system method either through the command line or in an apex ide, such as the salesforce extensions for visual studio code. test organization see sandbox. transaction, apex an apex transaction represents a set of operations that are executed as a single unit. 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, a visualforce page, or a custom web service method. trigger a piece of apex that executes before or after records of a particular type are inserted, updated, or deleted from the database. every trigger runs with a set of context variables that provide access to the records that caused the trigger to fire, and all triggers run in bulk mode—that is, they process several records at once, rather than just one record at a time. trigger context variable default variables that provide access to information about the trigger and the records that caused it to fire. 3628apex reference guide glossary u unit test a unit is the smallest testable part of an application, usually a method. a unit test operates on that piece of code to make sure it works correctly. see also test method. unlimited edition unlimited edition is salesforce’s solution for maximizing your success and extending that success across the entire enterprise through the lightning platform. unmanaged package a package that can’t be upgraded or controlled by its developer. url (uniform resource locator) the global address of a website, document, or other resource on the internet. for example, https://salesforce.com. user acceptance testing (uat) a process used to confirm that the functionality meets the planned requirements. uat is one of the final stages before deployment to production. v validation rule a rule that prevents a record from being saved if it doesn’t meet the standards that are specified. version a number value that indicates the release of an item. items that can have a version include api objects, fields, and calls; apex classes and triggers; and visualforce pages and components. view the user interface in the model-view-controller model, defined by visualforce. view state where the information necessary to maintain the state of the database between requests is saved. visualforce a simple, tag-based markup language that allows developers to easily define custom pages and components for apps built on the platform. each tag corresponds to a coarse or fine-grained component, such as a section of a page, a related list, or a field. the components can either be controlled by the same logic that is used in standard salesforce pages, or developers can associate their own logic with a controller written in apex. visualforce controller see controller, visualforce. visualforce lifecycle the stages of execution
of a visualforce page, including how the page is created and destroyed during a user session. visualforce page a web page created using visualforce. typically, visualforce pages present information relevant to your organization, but they can also modify or capture data. they can be rendered in several ways, such as a pdf document or an email attachment, and can be associated with a css style. w web service a mechanism by which two applications can easily exchange data over the internet, even if they run on different platforms, are written in different languages, or are geographically remote from each other. 3629apex reference guide glossary webservice method an apex class method or variable that external systems can use, like a mash-up with a third-party application. web service methods must be defined in a global class. web services api term describing the original salesforce platform web services application programming interface (api) that provides access to your salesforce org's information. see relevant developer guides for soap, rest, or bulk apis of interest. automated actions automated actions, such as email alerts, tasks, field updates, and outbound messages, can be triggered by a process, workflow rule, approval process, or milestone. wrapper class a class that abstracts common functions such as logging in, managing sessions, and querying and batching records. a wrapper class makes an integration more straightforward to develop and maintain, keeps program logic in one place, and affords easy reuse across components. examples of wrapper classes in salesforce include the ajax toolkit, which is a javascript wrapper around the salesforce soap api, wrapper classes such as ccritical section in the cti adapter for salesforce crm call center, or wrapper classes created as part of a client integration application that accesses salesforce using soap api. wsdl (web services description language) file an xml file that describes the format of messages you send and receive from a web service. your development environment's soap client uses the salesforce enterprise wsdl or partner wsdl to communicate with salesforce using soap api. x xml (extensible markup language) a markup language that enables the sharing and transportation of structured data. all lightning platform components that are retrieved or deployed through the metadata api are represented by xml definitions. y no glossary items for this entry. z no glossary items for this entry. 3630